@hydra-acp/cli 0.1.122 → 0.1.124
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 +295 -295
- package/dist/daemon.js +44 -44
- package/package.json +1 -1
package/dist/daemon.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`;await
|
|
4
|
-
`,{encoding:"utf8",mode:384})}async function Bs(){let n=await
|
|
5
|
-
`),e}Te();var Ls="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",
|
|
6
|
-
`)}async function Tn(){return await
|
|
2
|
+
var sa=Object.defineProperty;var _t=(n,e)=>()=>(n&&(e=n(n=0)),e);var ra=(n,e)=>{for(var t in e)sa(n,t,{get:e[t],enumerable:!0})};import*as H from"path";import*as Mn from"os";function Pe(n){let e=Mn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function oa(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function j(){let n=process.env[ia];if(n&&n.length>0)return H.resolve(n);let e=oa();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 H.join(Mn.homedir(),".hydra-acp")}var ia,S,W=_t(()=>{"use strict";ia="HYDRA_ACP_HOME";S={home:j,config:()=>H.join(j(),"config.json"),authToken:()=>H.join(j(),"auth-token"),remotes:()=>H.join(j(),"remotes.json"),pidFile:()=>H.join(j(),"daemon.pid"),logFile:()=>H.join(j(),"daemon.log"),currentLogFile:()=>H.join(j(),"current.log"),registryCache:()=>H.join(j(),"registry.json"),ttySessionDir:()=>H.join(j(),"tty"),ttySessionFile:n=>H.join(j(),"tty",n),agentsDir:()=>H.join(j(),"agents"),agentLogFile:n=>H.join(j(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>H.join(j(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>H.join(j(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>H.join(j(),"sessions"),sessionDir:n=>H.join(j(),"sessions",n),sessionFile:n=>H.join(j(),"sessions",n,"meta.json"),historyFile:n=>H.join(j(),"sessions",n,"history.jsonl"),historyArchiveFile:(n,e)=>H.join(j(),"sessions",n,`history.jsonl.${e}`),toolsDir:n=>H.join(j(),"sessions",n,"tools"),toolBlobFile:(n,e)=>H.join(j(),"sessions",n,"tools",e),queueFile:n=>H.join(j(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>H.join(j(),"sessions",".tombstones"),tombstoneAgentDir:n=>H.join(j(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>H.join(j(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>H.join(j(),"extensions"),extensionLogDir:n=>H.join(j(),"extensions",n),extensionLogFile:n=>H.join(j(),"extensions",n,"current.log"),extensionPidFile:n=>H.join(j(),"extensions",n,"extension.pid"),transformersDir:()=>H.join(j(),"transformers"),transformerLogDir:n=>H.join(j(),"transformers",n),transformerLogFile:n=>H.join(j(),"transformers",n,"current.log"),transformerPidFile:n=>H.join(j(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>H.join(j(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>H.join(j(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>H.join(j(),"prompt-history"),tuiLogFile:()=>H.join(j(),"tui.log"),shimWireLogFile:()=>H.join(j(),"shim-wire.log")}});import*as K from"fs/promises";import*as Us from"fs";import*as de from"path";import{randomBytes as da}from"crypto";async function ce(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
3
|
+
`;await ca(n,r,t)}async function ca(n,e,t={}){let s=await ua(n),r=la(s);await K.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${fa()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await K.writeFile(i,e,o),await K.rename(i,s)}catch(o){throw await K.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Us.chmodSync(s,t.mode)}catch{}}async function ua(n){let e;try{e=await K.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await K.readlink(n),s=de.isAbsolute(t)?t:de.resolve(de.dirname(n),t);try{let r=await K.realpath(de.dirname(s));return de.join(r,de.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function ue(n){let e;try{e=await K.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 la(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function fa(){return da(4).toString("hex")}var Te=_t(()=>{"use strict"});function Cn(n,e){return`${n}:${e}`}var Jo=_t(()=>{"use strict";W();Te()});var Zo={};ra(Zo,{_resetForTests:()=>sf,clearPin:()=>Gl,fetchPeerFingerprint:()=>Zl,formatFingerprint:()=>Vo,getPin:()=>Yl,installGlobalTlsTrust:()=>ef,loadPinsFromStore:()=>Xl,setPin:()=>Qo,sha256Hex:()=>Os,wsTlsOptions:()=>nf});import{createHash as zl}from"crypto";import*as Wo from"tls";import{Agent as Jl,Dispatcher as Wl,buildConnector as Ql,getGlobalDispatcher as Vl,setGlobalDispatcher as Kl}from"undici";function Qo(n,e,t){Fe.set(Cn(n,e),Ko(t))}function Gl(n,e){Fe.delete(Cn(n,e))}function Yl(n,e){return Fe.get(Cn(n,e))}function Xl(n){Fe.clear();for(let e of n.list())e.entry.pinnedFingerprint&&Qo(e.host,e.port,e.entry.pinnedFingerprint)}async function Zl(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=Wo.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(c,f)=>{if(!a){a=!0,clearTimeout(u);try{o.destroy()}catch{}c?i(c):f&&r(f)}},u=setTimeout(()=>{d(new Error(`TLS connect to ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let c=o.getPeerCertificate(!1);if(!c||!c.raw){d(new Error(`${n}:${e} did not present a TLS certificate`));return}d(null,Os(c.raw))}),o.once("error",c=>d(c))})}function Os(n){return zl("sha256").update(n).digest("hex")}function Vo(n){let e=Ko(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function Ko(n){return n.replace(/:/g,"").toLowerCase()}function ef(){if(Fs)return;Fs=!0;let n=Vl(),e=new Jl({connect:Ql({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Yo(s,r)})}),t=new Wl;t.dispatch=(s,r)=>{let i=tf(s.origin);return(i&&Go(i)?e:n).dispatch(s,r)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(s=>Promise.all([e.destroy(s??null),n.destroy(s??null)]).then(()=>{})),Kl(t)}function tf(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function Go(n){for(let e of Fe.keys())if(Xo(e)?.host===n)return!0;return!1}function Yo(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Os(e.raw);for(let[s,r]of Fe.entries()){let i=Xo(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${Vo(t)})`)}function Xo(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}function nf(n){return Go(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>Yo(e,t)}:{autoSelectFamily:!0}}function sf(){Fe.clear(),Fs=!1}var Fe,Fs,ea=_t(()=>{"use strict";Jo();Fe=new Map,Fs=!1});W();import*as ke from"fs/promises";import{homedir as Pn}from"os";import{z as I}from"zod";W();import*as Ne from"fs/promises";function Rn(){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 aa(){try{let e=(await Ne.readFile(S.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function En(n){await Ne.mkdir(S.home(),{recursive:!0}),await Ne.writeFile(S.authToken(),n+`
|
|
4
|
+
`,{encoding:"utf8",mode:384})}async function Bs(){let n=await aa();if(n)return n;let e=Rn();return await En(e),process.stderr.write(`hydra-acp: initialized ${S.authToken()} with a fresh service token.
|
|
5
|
+
`),e}Te();var Ls="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",pa=I.object({cert:I.string(),key:I.string()}),qs=55514,ma=I.object({host:I.string().default("127.0.0.1"),port:I.number().int().positive().default(qs),logLevel:I.enum(["debug","info","warn","error"]).default("info"),tls:pa.optional(),sessionIdleTimeoutSeconds:I.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:I.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:I.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:I.number().int().positive().default(10),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)}),ga=I.object({url:I.string().url().default(Ls),ttlHours:I.number().positive().default(24),pinned:I.boolean().default(!1)}),ha=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()}),ya=I.object({packageSpec:I.string().optional()}),wa=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"]),va=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),sidebar:I.object({enabled:I.boolean().default(!1),width:I.number().int().positive().optional(),border:I.enum(["none","rule","frame"]).default("frame"),gadgets:I.array(I.string()).default(["activity","context","queue","todo","files","git","resources","session","tools"])}).default({enabled:!1,border:"frame",gadgets:["activity","context","queue","todo","files","git","resources","session","tools"]}),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(wa,I.object({command:I.union([I.string(),I.array(I.string())])})).default({})}),Ds=I.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),ba=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)}),Ia=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)}),Sa=I.object({daemon:ma.default({}),registry:ga.default({url:Ls,ttlHours:24,pinned:!1}),agents:I.record(I.string(),ha).default({}),agentOverrides:I.record(I.string(),ya).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(Ds,ba).default({}),transformers:I.record(Ds,Ia).default({}),defaultTransformers:I.array(I.string()).default([]),npmRegistry:I.string().url().optional(),tui:va.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",sidebar:{enabled:!1,border:"frame",gadgets:["activity","context","queue","todo","files","git","resources","session","tools"]}})});function zs(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Js(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Ws(){return await ka(),await ue(S.config())??{}}async function ka(){let n;try{n=await ke.lstat(S.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await ke.stat(S.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await ke.readlink(S.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${S.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Aa(){let n=await Ws(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await ke.access(S.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${S.authToken()} and ${S.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await En(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ce(S.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${S.config()} to ${S.authToken()}.
|
|
6
|
+
`)}async function Tn(){return await Aa(),Sa.parse(await Ws())}function Z(n){return n==="~"||n==="$HOME"?Pn():n.startsWith("~/")?Pn()+n.slice(1):n.startsWith("$HOME/")?Pn()+n.slice(5):n}import*as Do from"fs";import*as we from"fs/promises";import*as Lo from"net";import*as dt from"path";import*as qo from"tls";import Hl from"fastify";import jl from"@fastify/websocket";var Qs="acp.v1";function Vs(n,e){return n.has(Qs)?Qs:!1}import Bo from"pino";import Bl from"pino-roll";W();import*as G from"fs/promises";import{createHash as Ca}from"crypto";import{gzip as xa,gunzip as Ma}from"zlib";import{promisify as Ks}from"util";var Gs=Ks(xa),Ra=Ks(Ma),Ys=/^[A-Za-z0-9_-]+$/,Ea=/^[a-f0-9]{64}$/,_n=!0;function Xs(n){_n=n}function $t(n,e){return Ys.test(n)?e===void 0||Ea.test(e):!1}function Ft(n,e){return`${S.toolBlobFile(n,e)}.gz`}async function $n(n,e){if(!$t(n))return null;let t=Ca("sha256").update(e,"utf8").digest("hex"),s=Ft(n,t),r=S.toolBlobFile(n,t);for(let a of[s,r])try{return await G.access(a),t}catch{}await G.mkdir(S.toolsDir(n),{recursive:!0});let i=_n?s:r,o=_n?await Gs(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await G.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function ct(n,e){if(!$t(n,e))return null;try{let t=await G.readFile(Ft(n,e));return(await Ra(t)).toString("utf8")}catch{}try{return await G.readFile(S.toolBlobFile(n,e),"utf8")}catch{return null}}async function Zs(n,e){if(!$t(n,e))return null;try{return await G.readFile(Ft(n,e))}catch{}try{let t=await G.readFile(S.toolBlobFile(n,e));return await Gs(t)}catch{return null}}async function er(n,e,t){if(!$t(n,e))return;let s=Ft(n,e);try{await G.access(s);return}catch{}await G.mkdir(S.toolsDir(n),{recursive:!0}),await G.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function tr(n){Ys.test(n)&&await G.rm(S.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}W();import*as fr from"fs/promises";import*as Nt from"path";import{z as F}from"zod";Te();W();import*as sr from"fs";import*as ee from"fs/promises";import*as Ae from"path";import{spawn as rr}from"child_process";import{Readable as Pa}from"stream";function pe(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function Nn(n,e=pe()){if(e)return n[e]}var He=n=>{process.stderr.write(n+`
|
|
7
7
|
`)};function Hn(n){He=n??(e=>process.stderr.write(e+`
|
|
8
|
-
`))}async function ir(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${pe()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=pe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentInstallDir(n.agentId,e,n.version),s=Ae.resolve(t,n.target.cmd);if(await On(s))return s;if(await
|
|
8
|
+
`))}async function ir(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${pe()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=pe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentInstallDir(n.agentId,e,n.version),s=Ae.resolve(t,n.target.cmd);if(await On(s))return s;if(await Ta({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await On(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await ee.chmod(s,493).catch(()=>{}),s}async function Ta(n){await ee.mkdir(Ae.dirname(n.installDir),{recursive:!0});let e=await ee.mkdtemp(`${n.installDir}.partial-`);try{He(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await _a({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});He(`hydra-acp: extracting ${n.agentId}`),je(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await Fa(t,e),await ee.unlink(t).catch(()=>{});try{await ee.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await On(n.installDir)){await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),je(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}He(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),je(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function je(n,e){if(n)try{n(e)}catch{}}async function _a(n){let e=$a(n.url),t=Ae.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=sr.createWriteStream(t),o=Pa.fromWeb(s.body);je(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),u=0,c=2e3,f=150;return o.on("data",p=>{a+=p.length;let l=Date.now();l-u>=f&&(u=l,je(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),l-d>=c&&(d=l,He(nr(n.agentId,a,r)))}),await new Promise((p,l)=>{o.on("error",l),i.on("error",l),i.on("finish",()=>p()),o.pipe(i)}),He(nr(n.agentId,a,r,!0)),je(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function nr(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function $a(n){let e=new URL(n);return Ae.posix.basename(e.pathname)||"archive"}async function Fa(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await Fn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await Oa("unzip")){await Fn("unzip",["-q",n,"-d",e]);return}await Fn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function Fn(n,e){return new Promise((t,s)=>{let r=rr(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function Oa(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=rr(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function On(n){try{return await ee.access(n),!0}catch{return!1}}W();import*as ne from"fs/promises";import*as me from"path";import{spawn as Na}from"child_process";var Bn=n=>{process.stderr.write(n+`
|
|
9
9
|
`)};function Un(n){Bn=n??(e=>process.stderr.write(e+`
|
|
10
|
-
`))}async function ar(n){let e=pe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentNpmInstallDir(n.agentId,e,n.version),s=
|
|
11
|
-
stderr: ${c}`:`npm install ${n.packageSpec} failed (${u})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<Ha)return await new Promise(r=>setTimeout(r,ja*(e+1))),dr(n,e+1);throw t}}function Ua(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function Da(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function cr(n,e){let t=me.join(n,"node_modules",e,"package.json");try{let s=await ne.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 or(n){let e=me.join(n.installDir,"node_modules",".bin"),t=me.join(e,n.hint);if(await _e(t))return{binName:n.hint,binPath:t};let s=await cr(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=me.join(e,i);if(await _e(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=me.join(e,i);if(await _e(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=me.join(e,n.basename);if(await _e(r))return{binName:n.basename,binPath:r}}}async function _e(n){try{return await ne.access(n),!0}catch{return!1}}var La=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Be=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),qa=F.object({"darwin-aarch64":Be.optional(),"darwin-x86_64":Be.optional(),"linux-aarch64":Be.optional(),"linux-x86_64":Be.optional(),"windows-x86_64":Be.optional(),"windows-aarch64":Be.optional()}),za=F.object({package:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Ja=F.object({command:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Wa=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),Qa=F.object({npx:La.optional(),binary:qa.optional(),uvx:za.optional(),exec:Ja.optional()}),Va=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:Qa,onboarding:Wa.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),ur=F.object({version:F.string(),agents:F.array(Va),extensions:F.array(F.unknown()).optional()}),Ot=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>Dn(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(d=>d.id.toLowerCase().startsWith(o));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:Z(t.command??e),args:t.args?.map(Z),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:Ka(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=ur.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(S.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=ur.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ce(S.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Ka(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Dn(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ue(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await Ln(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function Ln(n){let e=pe();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Nn(n.distribution.binary,e);if(s?.cmd){let r=Nt.resolve(S.agentInstallDir(n.id,e,t),s.cmd);if(await lr(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??Dn(n)??s.package,i=S.agentNpmInstallDir(n.id,e,t),o=Nt.join(i,"node_modules",".bin",r);if(await lr(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function lr(n){try{return await fr.access(n),!0}catch{return!1}}async function oe(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Dn(n)??r.package,a=t.onInstallProgress;return{command:await ar({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?u=>a({source:"npm",...u}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=Nn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${pe()??"this platform"}.`);let i=t.onInstallProgress,o=await ir({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as ed}from"child_process";import*as Bt from"fs";import*as Mr from"path";var k={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as q}from"zod";var pr=q.object({protocolVersion:q.number().optional(),clientCapabilities:q.record(q.unknown()).optional(),clientInfo:q.object({name:q.string(),version:q.string().optional()}).optional()}),Ga=q.enum(["full","pending_only","none","after_message"]),mr=q.object({cwd:q.string(),mcpServers:q.array(q.unknown()).optional(),_meta:q.record(q.unknown()).optional()}),gr=q.object({upstreamSessionId:q.string(),agentId:q.string(),cwd:q.string(),title:q.string().optional(),agentArgs:q.array(q.string()).optional()}),hr=q.object({sessionId:q.string(),historyPolicy:Ga.default("full"),afterMessageId:q.string().optional(),clientId:q.string().optional(),clientInfo:q.object({name:q.string(),version:q.string().optional()}).optional(),_meta:q.record(q.unknown()).optional()});import{z as N}from"zod";var yr=N.object({sessionId:N.string()}),wr=N.object({cwd:N.string().optional(),cursor:N.string().optional()}),qn=N.object({used:N.number().optional(),size:N.number().optional(),costAmount:N.number().optional(),costCurrency:N.string().optional()}),zf=N.object({sessionId:N.string(),upstreamSessionId:N.string().optional(),cwd:N.string(),title:N.string().optional(),agentId:N.string().optional(),currentModel:N.string().optional(),currentUsage:qn.optional(),importedFromMachine:N.string().optional(),importedFromUpstreamSessionId:N.string().optional(),parentSessionId:N.string().optional(),forkedFromSessionId:N.string().optional(),forkedFromMessageId:N.string().optional(),originatingClient:N.object({name:N.string(),version:N.string().optional()}).optional(),interactive:N.boolean().optional(),priority:N.number().int().nonnegative().optional(),updatedAt:N.string(),attachedClients:N.number().int().nonnegative(),status:N.enum(["warm","cold"]).default("warm"),busy:N.boolean().default(!1),awaitingInput:N.boolean().default(!1),compactionState:N.any().optional(),agentPid:N.number().int().positive().optional(),forkSynthesisState:N.enum(["running","failed"]).optional(),_meta:N.record(N.unknown()).optional()}),Ya=N.object({sessionId:N.string(),cwd:N.string(),title:N.string().optional(),updatedAt:N.string().optional(),_meta:N.record(N.unknown()).optional()}),Jf=N.object({sessions:N.array(Ya),nextCursor:N.string().optional()});function Ht(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),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 vr(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ut(n._meta,Ht(n))};return n.title!==void 0&&(e.title=n.title),e}var lt="hydra-acp";function Xa(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 ft(n){if(!n)return{};let e=n[lt];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=gr.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=qn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="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=Xa(t.env);r!==void 0&&(s.env=r)}return s}function ut(n,e){return{...n??{},[lt]:e}}import{z as M}from"zod";var br=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),jt=M.object({sessionId:M.string()}),Ir=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Yf=M.object({sessionId:M.string(),messageId:M.string(),originator:Ir,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Xf=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Zf=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),Sr=M.object({sessionId:M.string(),messageId:M.string()}),ep=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),kr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),tp=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),Ar=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),np=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),sp=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:Ir,amendedAt:M.number()});import{z as Ce}from"zod";var op=Ce.object({agentId:Ce.string(),version:Ce.string(),source:Ce.enum(["binary","npm"]),phase:Ce.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Ce.number().optional(),totalBytes:Ce.number().optional(),packageSpec:Ce.string().optional()}),Cr="hydra-acp/agents/install_progress",De={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function xr(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
|
|
10
|
+
`))}async function ar(n){let e=pe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentNpmInstallDir(n.agentId,e,n.version),s=Da(n.packageSpec),r=La(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=me.join(t,"node_modules",".bin",n.bin);if(await _e(o))return o;if(await _e(t)){let f=await or(i);if(f)return f.binPath}await Ha({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await or(i);if(a)return a.binPath;let d=await cr(t,s),u=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],c=u.length>0?` (package declares bins: ${u.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${c}`)}async function Ha(n){await ne.mkdir(me.dirname(n.installDir),{recursive:!0});let e=await ne.mkdtemp(`${n.installDir}.partial-`);try{Bn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),jn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await Ua({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await ne.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await _e(n.installDir)){await ne.rm(e,{recursive:!0,force:!0}).catch(()=>{}),jn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Bn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),jn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await ne.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function jn(n,e){if(n)try{n(e)}catch{}}var ja=5,Ba=25;function Ua(n){return dr(n,0)}async function dr(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=Na("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,d)=>{if(a===0){t();return}let u=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,c=o.trim();s(new Error(c?`npm install ${n.packageSpec} failed (${u})
|
|
11
|
+
stderr: ${c}`:`npm install ${n.packageSpec} failed (${u})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<ja)return await new Promise(r=>setTimeout(r,Ba*(e+1))),dr(n,e+1);throw t}}function Da(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function La(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function cr(n,e){let t=me.join(n,"node_modules",e,"package.json");try{let s=await ne.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 or(n){let e=me.join(n.installDir,"node_modules",".bin"),t=me.join(e,n.hint);if(await _e(t))return{binName:n.hint,binPath:t};let s=await cr(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=me.join(e,i);if(await _e(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=me.join(e,i);if(await _e(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=me.join(e,n.basename);if(await _e(r))return{binName:n.basename,binPath:r}}}async function _e(n){try{return await ne.access(n),!0}catch{return!1}}var qa=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Be=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),za=F.object({"darwin-aarch64":Be.optional(),"darwin-x86_64":Be.optional(),"linux-aarch64":Be.optional(),"linux-x86_64":Be.optional(),"windows-x86_64":Be.optional(),"windows-aarch64":Be.optional()}),Ja=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()}),Qa=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),Va=F.object({npx:qa.optional(),binary:za.optional(),uvx:Ja.optional(),exec:Wa.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:Va,onboarding:Qa.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),ur=F.object({version:F.string(),agents:F.array(Ka),extensions:F.array(F.unknown()).optional()}),Ot=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>Dn(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(d=>d.id.toLowerCase().startsWith(o));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:Z(t.command??e),args:t.args?.map(Z),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:Ga(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=ur.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(S.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=ur.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ce(S.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Ga(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Dn(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ue(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await Ln(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function Ln(n){let e=pe();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Nn(n.distribution.binary,e);if(s?.cmd){let r=Nt.resolve(S.agentInstallDir(n.id,e,t),s.cmd);if(await lr(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??Dn(n)??s.package,i=S.agentNpmInstallDir(n.id,e,t),o=Nt.join(i,"node_modules",".bin",r);if(await lr(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function lr(n){try{return await fr.access(n),!0}catch{return!1}}async function oe(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Dn(n)??r.package,a=t.onInstallProgress;return{command:await ar({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?u=>a({source:"npm",...u}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=Nn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${pe()??"this platform"}.`);let i=t.onInstallProgress,o=await ir({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as td}from"child_process";import*as Bt from"fs";import*as Mr from"path";var k={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as q}from"zod";var pr=q.object({protocolVersion:q.number().optional(),clientCapabilities:q.record(q.unknown()).optional(),clientInfo:q.object({name:q.string(),version:q.string().optional()}).optional()}),Ya=q.enum(["full","pending_only","none","after_message"]),mr=q.object({cwd:q.string(),mcpServers:q.array(q.unknown()).optional(),_meta:q.record(q.unknown()).optional()}),gr=q.object({upstreamSessionId:q.string(),agentId:q.string(),cwd:q.string(),title:q.string().optional(),agentArgs:q.array(q.string()).optional()}),hr=q.object({sessionId:q.string(),historyPolicy:Ya.default("full"),afterMessageId:q.string().optional(),clientId:q.string().optional(),clientInfo:q.object({name:q.string(),version:q.string().optional()}).optional(),_meta:q.record(q.unknown()).optional()});import{z as N}from"zod";var yr=N.object({sessionId:N.string()}),wr=N.object({cwd:N.string().optional(),cursor:N.string().optional()}),qn=N.object({used:N.number().optional(),size:N.number().optional(),costAmount:N.number().optional(),costCurrency:N.string().optional()}),Jf=N.object({sessionId:N.string(),upstreamSessionId:N.string().optional(),cwd:N.string(),title:N.string().optional(),agentId:N.string().optional(),currentModel:N.string().optional(),currentUsage:qn.optional(),importedFromMachine:N.string().optional(),importedFromUpstreamSessionId:N.string().optional(),parentSessionId:N.string().optional(),forkedFromSessionId:N.string().optional(),forkedFromMessageId:N.string().optional(),originatingClient:N.object({name:N.string(),version:N.string().optional()}).optional(),interactive:N.boolean().optional(),priority:N.number().int().nonnegative().optional(),updatedAt:N.string(),attachedClients:N.number().int().nonnegative(),status:N.enum(["warm","cold"]).default("warm"),busy:N.boolean().default(!1),awaitingInput:N.boolean().default(!1),compactionState:N.any().optional(),agentPid:N.number().int().positive().optional(),forkSynthesisState:N.enum(["running","failed"]).optional(),_meta:N.record(N.unknown()).optional()}),Xa=N.object({sessionId:N.string(),cwd:N.string(),title:N.string().optional(),updatedAt:N.string().optional(),_meta:N.record(N.unknown()).optional()}),Wf=N.object({sessions:N.array(Xa),nextCursor:N.string().optional()});function Ht(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),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 vr(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ut(n._meta,Ht(n))};return n.title!==void 0&&(e.title=n.title),e}var lt="hydra-acp";function Za(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 ft(n){if(!n)return{};let e=n[lt];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=gr.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=qn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="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=Za(t.env);r!==void 0&&(s.env=r)}return s}function ut(n,e){return{...n??{},[lt]:e}}import{z as M}from"zod";var br=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),jt=M.object({sessionId:M.string()}),Ir=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Xf=M.object({sessionId:M.string(),messageId:M.string(),originator:Ir,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Zf=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),ep=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),Sr=M.object({sessionId:M.string(),messageId:M.string()}),tp=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),kr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),np=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),Ar=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),sp=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),rp=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:Ir,amendedAt:M.number()});import{z as Ce}from"zod";var ap=Ce.object({agentId:Ce.string(),version:Ce.string(),source:Ce.enum(["binary","npm"]),phase:Ce.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Ce.number().optional(),totalBytes:Ce.number().optional(),packageSpec:Ce.string().optional()}),Cr="hydra-acp/agents/install_progress",De={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function xr(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
|
|
12
12
|
`);for(;d!==-1;){let u=t.slice(0,d).trim();if(t=t.slice(d+1),u.length>0)try{let c=JSON.parse(u);for(let f of s)f(c)}catch(c){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse ndjson line: ${c.message}`}})}d=t.indexOf(`
|
|
13
13
|
`)}}),n.on("end",()=>o()),n.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let d=JSON.stringify(a)+`
|
|
14
|
-
`;await new Promise((u,c)=>{e.write(d,f=>{if(f){c(f);return}u()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as
|
|
14
|
+
`;await new Promise((u,c)=>{e.write(d,f=>{if(f){c(f);return}u()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as ed}from"nanoid";var zn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Le=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 zn;let s=ed(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:k.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??k.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}};W();var nd=4096,xe=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??nd,this.killEscalationMs=e.killEscalationMs??sd,this.logger=e.logger,this.fileLog=rd(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()} ---
|
|
15
15
|
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=xr(t.stdout,t.stdin);this.connection=new Le(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
|
|
16
16
|
`),this.connection.fail(new Error(i))}),t.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
17
17
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
18
|
-
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=
|
|
18
|
+
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=td(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()} ---
|
|
19
19
|
`),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()} ---
|
|
20
|
-
`),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)})}},nd=2e3;function sd(n){try{let e=S.agentLogFile(n);Bt.mkdirSync(Mr.dirname(e),{recursive:!0});let t=Bt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as $e from"fs/promises";import*as Ei from"os";import*as Rr from"os";function pt(){return Rr.hostname()}import*as kt from"path";import{customAlphabet as Ac}from"nanoid";async function qe(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function ze(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as zr}from"nanoid";var Er="edit",Ut=class{kinds=new Map;note(e,t){t!==void 0&&t.length>0&&!this.kinds.has(e)&&this.kinds.set(e,t)}get(e){return this.kinds.get(e)}effective(e,t){return t!==void 0&&t.length>0?t:this.kinds.get(e)}clear(){this.kinds.clear()}get size(){return this.kinds.size}};function Pr(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let s=t.path;typeof s=="string"&&s.length>0&&e.push(s)}return e}import*as _r from"fs/promises";var rd=64*1024*1024,id=1*1024*1024,Je=64*1024,od=6e4,ad=100,dd=1e3,cd=64*1024,ud=256*1024,Tr=20;function ld(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Dt=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??rd,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(id,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,Je));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),c={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(c.gap=i),this.closed&&r+d>=this.writeCursor&&(c.eof=!0),c}tail(e){let t=Math.max(0,Math.min(e,Je)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Je)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,od));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",u=a?new RegExp(e.pattern,d):new RegExp(ld(e.pattern),d),c=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??ad,dd)),p=Math.max(1,Math.min(e.maxBytes??cd,ud)),l=Math.max(0,Math.min(e.contextBefore??0,Tr)),g=Math.max(0,Math.min(e.contextAfter??0,Tr)),m=[],h=[],y=[],v=0,w=!1,b=0,A=0,C=(_,U)=>{for(let J of y)J.remaining>0&&(J.match.after===void 0&&(J.match.after=[]),J.match.after.push({cursor:_,line:U}),J.remaining--,v+=U.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(u.test(U)!==c&&m.length<f){let J={cursor:_,line:U};if(l>0&&h.length>0){J.before=h.slice();for(let ie of J.before)v+=ie.line.length}v+=U.length,m.push(J),g>0&&y.push({match:J,remaining:g})}if(l>0)for(h.push({cursor:_,line:U});h.length>l;)h.shift();let P=m.length>=f&&y.length===0,B=v>=p;return P||B};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let U=o.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,C($,U)){w=!0;break}}if(!w&&b<o.length&&this.closed){let _=o.subarray(b).toString("utf8"),U=r+b;C(U,_)&&(w=!0),A=o.length}let x=Math.min(r+A,this.writeCursor),T={matches:m,truncated:w,nextCursor:x,scannedBytes:A};return i>0&&(T.gap=i),this.closed&&x>=this.writeCursor&&(T.eof=!0),T}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>_r.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var We=[{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:"fork",name:"hydra fork",argsHint:"[verbatim]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass 'verbatim' to slice at the last completed turn instead)"},{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."}],Ep=new Map(We.map(n=>[n.verb,n]));function $r(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=$r(n),s=e.filter(i=>$r(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function Fr(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let u=Wn(d);if(u?.sessionUpdate!=="tool_call_update")continue;let c=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(c!==void 0&&(e.set(c,a),u.rawInput&&typeof u.rawInput=="object"&&!Array.isArray(u.rawInput)&&Object.keys(u.rawInput).length>0&&s.set(c,u.rawInput),Array.isArray(u.content)&&u.content.length>0)){let f=t.get(c);f?f.push(...u.content):t.set(c,[...u.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let u=Wn(d);if(!u||typeof u.sessionUpdate!="string"){r.push(d),i=null;continue}let c=u.sessionUpdate;if(c==="agent_message_chunk"||c==="agent_thought_chunk"||c==="user_message_chunk"){i&&i.kind===c?pd(r,i.outIndex,fd(u.content)):(r.push(d),i={outIndex:r.length-1,kind:c});continue}if(i=null,c==="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)?md(d,t.get(f)??[]):d;f!==void 0&&s.has(f)&&!gd(p)&&(p=hd(p,s.get(f))),r.push(p);continue}if(c==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(c==="prompt_received"||c==="turn_complete")&&(o=null),r.push(d)}return r}function Wn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function fd(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function pd(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function md(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function gd(n){let t=Wn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function hd(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Or=`[older history truncated]
|
|
21
|
-
`,
|
|
22
|
-
`),t)}function Qn(n){let e=
|
|
23
|
-
`);for(;t.length>0;){let s=
|
|
24
|
-
`);if(s.length<=e)return s;t.shift()}return
|
|
20
|
+
`),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)})}},sd=2e3;function rd(n){try{let e=S.agentLogFile(n);Bt.mkdirSync(Mr.dirname(e),{recursive:!0});let t=Bt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as $e from"fs/promises";import*as Pi from"os";import*as Rr from"os";function pt(){return Rr.hostname()}import*as kt from"path";import{customAlphabet as Cc}from"nanoid";async function qe(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function ze(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as Jr}from"nanoid";var Er="edit",Ut=class{kinds=new Map;note(e,t){t!==void 0&&t.length>0&&!this.kinds.has(e)&&this.kinds.set(e,t)}get(e){return this.kinds.get(e)}effective(e,t){return t!==void 0&&t.length>0?t:this.kinds.get(e)}clear(){this.kinds.clear()}get size(){return this.kinds.size}};function Pr(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let s=t.path;typeof s=="string"&&s.length>0&&e.push(s)}return e}import*as _r from"fs/promises";var id=64*1024*1024,od=1*1024*1024,Je=64*1024,ad=6e4,dd=100,cd=1e3,ud=64*1024,ld=256*1024,Tr=20;function fd(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Dt=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??id,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(od,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,Je));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),c={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(c.gap=i),this.closed&&r+d>=this.writeCursor&&(c.eof=!0),c}tail(e){let t=Math.max(0,Math.min(e,Je)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Je)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,ad));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",u=a?new RegExp(e.pattern,d):new RegExp(fd(e.pattern),d),c=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??dd,cd)),p=Math.max(1,Math.min(e.maxBytes??ud,ld)),l=Math.max(0,Math.min(e.contextBefore??0,Tr)),g=Math.max(0,Math.min(e.contextAfter??0,Tr)),m=[],h=[],y=[],v=0,w=!1,b=0,A=0,C=(_,U)=>{for(let J of y)J.remaining>0&&(J.match.after===void 0&&(J.match.after=[]),J.match.after.push({cursor:_,line:U}),J.remaining--,v+=U.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(u.test(U)!==c&&m.length<f){let J={cursor:_,line:U};if(l>0&&h.length>0){J.before=h.slice();for(let ie of J.before)v+=ie.line.length}v+=U.length,m.push(J),g>0&&y.push({match:J,remaining:g})}if(l>0)for(h.push({cursor:_,line:U});h.length>l;)h.shift();let P=m.length>=f&&y.length===0,B=v>=p;return P||B};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let U=o.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,C($,U)){w=!0;break}}if(!w&&b<o.length&&this.closed){let _=o.subarray(b).toString("utf8"),U=r+b;C(U,_)&&(w=!0),A=o.length}let x=Math.min(r+A,this.writeCursor),T={matches:m,truncated:w,nextCursor:x,scannedBytes:A};return i>0&&(T.gap=i),this.closed&&x>=this.writeCursor&&(T.eof=!0),T}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>_r.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var We=[{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:"fork",name:"hydra fork",argsHint:"[verbatim]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass 'verbatim' to slice at the last completed turn instead)"},{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."}],Pp=new Map(We.map(n=>[n.verb,n]));function $r(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=$r(n),s=e.filter(i=>$r(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function Or(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let u=Wn(d);if(u?.sessionUpdate!=="tool_call_update")continue;let c=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(c!==void 0){e.set(c,a);for(let f of hd){if(!Fr(u[f]))continue;let p=s.get(c);p===void 0?s.set(c,new Map([[f,u[f]]])):p.set(f,u[f])}if(Array.isArray(u.content)&&u.content.length>0){let f=t.get(c);f?f.push(...u.content):t.set(c,[...u.content])}}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let u=Wn(d);if(!u||typeof u.sessionUpdate!="string"){r.push(d),i=null;continue}let c=u.sessionUpdate;if(c==="agent_message_chunk"||c==="agent_thought_chunk"||c==="user_message_chunk"){i&&i.kind===c?md(r,i.outIndex,pd(u.content)):(r.push(d),i={outIndex:r.length-1,kind:c});continue}if(i=null,c==="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)?gd(d,t.get(f)??[]):d,l=f===void 0?void 0:s.get(f);if(l!==void 0)for(let[g,m]of l)Fr(Wn(p)?.[g])||(p=yd(p,g,m));r.push(p);continue}if(c==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(c==="prompt_received"||c==="turn_complete")&&(o=null),r.push(d)}return r}function Wn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function pd(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function md(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function gd(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}var hd=["rawInput","locations"];function Fr(n){return n==null||typeof n!="object"?!1:Array.isArray(n)?n.length>0:Object.keys(n).length>0}function yd(n,e,t){let s=n.params??{},r=s.update??{};return{...n,params:{...s,update:{...r,[e]:t}}}}var Nr=`[older history truncated]
|
|
21
|
+
`,wd=["file_path","filePath","path","command","pattern","query"];function Ve(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let u=d.sessionUpdate;if(u==="prompt_received"){i();let c=Vn(d.prompt).trim();c.length>0&&s.push(`User: ${c}`)}else if(u==="agent_message_chunk"){let c=Kn(d.content);c.length>0&&(r+=c)}else u==="tool_call"?(i(),s.push(Qn(d))):u==="turn_complete"&&i()}return i(),Sd(s.join(`
|
|
22
|
+
`),t)}function Qn(n){let e=vd(n),t=bd(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function vd(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function bd(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of wd){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Id(r,200)}`)}return t}function Vn(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 Kn(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Id(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Sd(n,e){if(n.length<=e)return n;let t=n.split(`
|
|
23
|
+
`);for(;t.length>0;){let s=Nr+t.join(`
|
|
24
|
+
`);if(s.length<=e)return s;t.shift()}return Nr}var Hr="(untitled)";function Gn(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??Hr}`),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 o=mt("Open threads",t.open_threads);o.length>0&&e.push(o);let a=mt("Decisions",t.decisions);a.length>0&&e.push(a);let d=mt("File edit intentions",t.file_edit_intentions);d.length>0&&e.push(d);let u=mt("Unresolved errors",t.unresolved_errors);u.length>0&&e.push(u);let c=mt("Tool state",t.tool_state);c.length>0&&e.push(c);let f=jr(t.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let p=jr(t.tools_used);p.length>0&&e.push(`[Tools previously used] ${p}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??Hr}`);let{closedText:s,openText:r,keptCount:i}=kd(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),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(`
|
|
25
25
|
`)}function mt(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(`
|
|
26
|
-
`)}`}function
|
|
27
|
-
`)}function
|
|
26
|
+
`)}`}function jr(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 kd(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Ad(n),o=0,a=[];if(e>0&&r.length>0){let c=r.filter(l=>l.startEntryIndex>=t).length,f=Math.max(c,s),p=Math.min(f,e,r.length);o=p,a=p>0?r.slice(-p):[]}let d=a.length>0?Br(a):"",u=i?Br([i]):"";return{closedText:d,openText:u,keptCount:o}}function Br(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(`
|
|
27
|
+
`)}function Ad(n){let e=[],t=null;for(let r=0;r<n.length;r++){let i=n[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let d=a.sessionUpdate;if(d==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Vn(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(d==="agent_message_chunk"&&t!==null){let u=Kn(a.content);u.length>0&&(t.agent+=u)}else d==="tool_call"&&t!==null?t.tools.push(Qn(a)):d==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}W();import*as ge from"fs/promises";async function gt(n,e){let t=S.queueFile(n);if(e.length===0){await ge.unlink(t).catch(()=>{});return}await ge.mkdir(S.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
28
28
|
`)+`
|
|
29
|
-
`;await ge.writeFile(t,s,"utf8")}async function
|
|
30
|
-
`))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Ur(n){let e=S.queueFile(n);await ge.unlink(e).catch(()=>{})}import*as Vr from"fs/promises";var Jr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wr=zr(Jr,16),Yn=zr(Jr,16),Ad=20,Cd=20,xd=5,ve="hydra_session_";function Me(){return`m_${Wr()}`}function Qr(n){return n.startsWith(ve)?n.slice(ve.length):n}var Md=1e3,Lt=300*1e3,Rd=64,Ye=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;forkHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Ut;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??`${ve}${Wr()}`,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.forkHook=e.forkHook,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??Md,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){Fd(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=Lr(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),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 i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let c=s;c<this.transformChain.length;c++){let f=this.transformChain[c];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${Yn()}`,l;try{l=await f.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let g=l?.action??"continue";if(g==="stop")return;if(g==="processing"){let m=c,h=o,y=new Set(t),v=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:f.name}),this.runResponseChain(h,new Set([...y,f.name]),m+1,v).then(()=>w()).catch(()=>w()))},Lt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:v,envelope:h,chainIdx:m,originatedBy:y,side:"response"})});return}l?.payload&&typeof l.payload=="object"&&(o=l.payload),t.add(f.name)}if(r!=="session/update")return;let d=Od(o);if(d!==null){this.setAgentAdvertisedCommands(d);return}let u=$d(o);if(u!==null){this.setAgentAdvertisedModes(u);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}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 agentPid(){return this.agent.pid}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,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,d=this.forwardedEnv,u=this.currentModel,c=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:o,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),i||(await ze({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:u,agentReportedModel:l.initialModel,logger:this.logger}),await qe({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger})),l.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=Gn({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 l.agent.connection.request("session/prompt",{sessionId:l.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,y=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=l.initialModel,this.currentMode=l.initialMode,this.setAgentAdvertisedModels(l.initialModels??[]),this.setAgentAdvertisedModes(l.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(C){this.logger?.warn(`swapUpstream: agentChange handler failed: ${C.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...y!==void 0?{previousSummarizedThroughEntry:y}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let w=i?`
|
|
29
|
+
`;await ge.writeFile(t,s,"utf8")}async function Ur(n){let e=S.queueFile(n),t;try{t=await ge.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
|
|
30
|
+
`))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Dr(n){let e=S.queueFile(n);await ge.unlink(e).catch(()=>{})}import*as Kr from"fs/promises";var Wr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qr=Jr(Wr,16),Yn=Jr(Wr,16),Cd=20,xd=20,Md=5,ve="hydra_session_";function Me(){return`m_${Qr()}`}function Vr(n){return n.startsWith(ve)?n.slice(ve.length):n}var Rd=1e3,Lt=300*1e3,Ed=64,Ye=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;forkHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Ut;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??`${ve}${Qr()}`,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.forkHook=e.forkHook,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??Rd,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){Od(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=qr(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),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 i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let c=s;c<this.transformChain.length;c++){let f=this.transformChain[c];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${Yn()}`,l;try{l=await f.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let g=l?.action??"continue";if(g==="stop")return;if(g==="processing"){let m=c,h=o,y=new Set(t),v=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:f.name}),this.runResponseChain(h,new Set([...y,f.name]),m+1,v).then(()=>w()).catch(()=>w()))},Lt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:v,envelope:h,chainIdx:m,originatedBy:y,side:"response"})});return}l?.payload&&typeof l.payload=="object"&&(o=l.payload),t.add(f.name)}if(r!=="session/update")return;let d=Nd(o);if(d!==null){this.setAgentAdvertisedCommands(d);return}let u=Fd(o);if(u!==null){this.setAgentAdvertisedModes(u);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}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 agentPid(){return this.agent.pid}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,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,d=this.forwardedEnv,u=this.currentModel,c=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:o,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),i||(await ze({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:u,agentReportedModel:l.initialModel,logger:this.logger}),await qe({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger})),l.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=Gn({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 l.agent.connection.request("session/prompt",{sessionId:l.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,y=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=l.initialModel,this.currentMode=l.initialMode,this.setAgentAdvertisedModels(l.initialModels??[]),this.setAgentAdvertisedModes(l.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(C){this.logger?.warn(`swapUpstream: agentChange handler failed: ${C.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...y!==void 0?{previousSummarizedThroughEntry:y}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let w=i?`
|
|
31
31
|
Switched to ${r}.
|
|
32
32
|
`:`
|
|
33
33
|
Compaction completed.
|
|
34
|
-
`,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,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,u=this.currentMode,c=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(c.agent),await ze({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedModel:d,agentReportedModel:c.initialModel,logger:this.logger}),await qe({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedMode:u,agentReportedMode:c.initialMode,logger:this.logger}),c.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=c.agent,this.upstreamSessionId=c.upstreamSessionId,this.agentMeta=c.agentMeta,this.agentCapabilities=c.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=Ad){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,i=new Set;for(let o of s){let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let u=d.sessionUpdate,c=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(c){if(u==="tool_call")r.add(c);else if(u==="tool_call_update"){let f=d.status;(f==="completed"||f==="failed")&&i.add(c)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(r=>r.entry):[]}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 se(new Error("session is closed"),k.SessionNotFound);if(this.clients.has(e.clientId))throw se(new Error(`client ${e.clientId} is already attached`),k.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Fr(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Dr(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?qt(i,t.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return 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 se(new Error("client not attached"),k.SessionNotFound);if(this.closing)throw se(new Error("session is closing; new prompts cannot be accepted"),k.SessionClosing);let r=Me();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(ft((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Ke(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 i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Me()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Rd;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw se(new Error("client not attached"),k.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(c=>c.messageId===r&&c.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let 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,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=Me(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}d.push(u)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=Me(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw se(new Error("client not attached"),k.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let u=`request:${e}`;if(!d.intercepts.has(u))continue;let c=`t_${Yn()}`,f;try{f=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(l){this.logger?.warn(`transformer ${d.name} error on ${u}: ${l.message}`);continue}let p=f?.action??"continue";if(p==="stop")return i==="notification"?void 0:f?.payload??Xn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(o=f.payload),s.add(d.name);continue}if(p==="processing"){let l=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),l+1,i).then(h).catch(()=>h(i==="notification"?void 0:Xn(e))))},Lt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:l,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name)||!d.intercepts.has(o))continue;let u=`t_${Yn()}`,c;try{c=await d.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${o}: ${p.message}`);continue}let f=c?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:c?.payload??Ud(e)};if(f==="continue"){c?.payload&&typeof c.payload=="object"&&(i=c.payload),s.add(d.name);continue}if(f==="processing"){let p=a,l=i,g=new Set(s),m=e;return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:d.name}),this.runAgentRequestChain(m,l,new Set([...g,d.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:l})))},Lt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(u,{resolve:v=>h({shortCircuit:!0,payload:v}),timer:y,transformerName:d.name,method:m,envelope:l,chainIdx:p,originatedBy:g,side:"agent-request"})})}s.add(d.name)}return{shortCircuit:!1,envelope:i}}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):Lt,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else 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 o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:Xn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(u=>u.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=Me(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((u,c)=>{let f={kind:"user",messageId:o,originator:d,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:u,reject:c},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=Ke((e??{}).prompt),r=Zn(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=Ge(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ge(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let u=d.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(o.id==="mode"){let a=ht(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let u=d.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 o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=Ge(o.options);if(d.length>0){let u=ht(o.options),c=u.length>0?u.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),f=o.name,p=typeof f=="string"&&f.trim()?f.trim():a,l=o.currentValue,g=typeof l=="string"&&l.trim()?l.trim():c[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=c,typeof l=="string"&&l.trim()&&(h.currentValue=l.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:g,options:c})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;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 i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}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(Pd(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Td(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),_d(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(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of We){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 i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let d=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&d.length>0){let u=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}if(d.length>0&&t.get(d)===s){let u=r.verb?`${d} ${r.verb}`:d,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=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of We)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let d=r.get(a);d===void 0?r.set(a,o):d!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,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 i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(We.some(f=>f.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(o,t):this.runForkCommand(o);default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=k.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let u=We.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 c=new Error(`unknown /hydra verb: ${i} (known: ${u.join(", ")})`);throw c.code=k.InvalidParams,c}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let u=()=>{},c=new Promise(g=>{u=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>u({stopReason:"cancelled",reason:g})});let f,p=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,c]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return p=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let l=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return l.length>0?this.emitExtensionReply(l):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
34
|
+
`,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,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,u=this.currentMode,c=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(c.agent),await ze({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedModel:d,agentReportedModel:c.initialModel,logger:this.logger}),await qe({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedMode:u,agentReportedMode:c.initialMode,logger:this.logger}),c.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=c.agent,this.upstreamSessionId=c.upstreamSessionId,this.agentMeta=c.agentMeta,this.agentCapabilities=c.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=Cd){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,i=new Set;for(let o of s){let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let u=d.sessionUpdate,c=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(c){if(u==="tool_call")r.add(c);else if(u==="tool_call_update"){let f=d.status;(f==="completed"||f==="failed")&&i.add(c)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(r=>r.entry):[]}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 se(new Error("session is closed"),k.SessionNotFound);if(this.clients.has(e.clientId))throw se(new Error(`client ${e.clientId} is already attached`),k.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Or(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Lr(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?qt(i,t.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return 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 se(new Error("client not attached"),k.SessionNotFound);if(this.closing)throw se(new Error("session is closing; new prompts cannot be accepted"),k.SessionClosing);let r=Me();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(ft((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Ke(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 i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Me()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Ed;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw se(new Error("client not attached"),k.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(c=>c.messageId===r&&c.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let 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,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=Me(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}d.push(u)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=Me(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw se(new Error("client not attached"),k.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let u=`request:${e}`;if(!d.intercepts.has(u))continue;let c=`t_${Yn()}`,f;try{f=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(l){this.logger?.warn(`transformer ${d.name} error on ${u}: ${l.message}`);continue}let p=f?.action??"continue";if(p==="stop")return i==="notification"?void 0:f?.payload??Xn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(o=f.payload),s.add(d.name);continue}if(p==="processing"){let l=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),l+1,i).then(h).catch(()=>h(i==="notification"?void 0:Xn(e))))},Lt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:l,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name)||!d.intercepts.has(o))continue;let u=`t_${Yn()}`,c;try{c=await d.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${o}: ${p.message}`);continue}let f=c?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:c?.payload??Dd(e)};if(f==="continue"){c?.payload&&typeof c.payload=="object"&&(i=c.payload),s.add(d.name);continue}if(f==="processing"){let p=a,l=i,g=new Set(s),m=e;return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:d.name}),this.runAgentRequestChain(m,l,new Set([...g,d.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:l})))},Lt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(u,{resolve:v=>h({shortCircuit:!0,payload:v}),timer:y,transformerName:d.name,method:m,envelope:l,chainIdx:p,originatedBy:g,side:"agent-request"})})}s.add(d.name)}return{shortCircuit:!1,envelope:i}}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):Lt,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else 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 o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:Xn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(u=>u.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=Me(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((u,c)=>{let f={kind:"user",messageId:o,originator:d,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:u,reject:c},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=Ke((e??{}).prompt),r=Zn(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=Ge(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ge(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let u=d.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(o.id==="mode"){let a=ht(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let u=d.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 o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=Ge(o.options);if(d.length>0){let u=ht(o.options),c=u.length>0?u.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),f=o.name,p=typeof f=="string"&&f.trim()?f.trim():a,l=o.currentValue,g=typeof l=="string"&&l.trim()?l.trim():c[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=c,typeof l=="string"&&l.trim()&&(h.currentValue=l.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:g,options:c})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;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 i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}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(Td(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(_d(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(",")}]`),$d(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(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of We){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 i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let d=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&d.length>0){let u=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}if(d.length>0&&t.get(d)===s){let u=r.verb?`${d} ${r.verb}`:d,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=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of We)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let d=r.get(a);d===void 0?r.set(a,o):d!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,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 i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(We.some(f=>f.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(o,t):this.runForkCommand(o);default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=k.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let u=We.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 c=new Error(`unknown /hydra verb: ${i} (known: ${u.join(", ")})`);throw c.code=k.InvalidParams,c}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let u=()=>{},c=new Promise(g=>{u=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>u({stopReason:"cancelled",reason:g})});let f,p=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,c]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return p=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.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:`
|
|
35
35
|
${e}
|
|
36
36
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",d=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${d}`});e=`Sessions (${t.length}):
|
|
37
37
|
${s.join(`
|
|
@@ -54,7 +54,7 @@ ${c}:
|
|
|
54
54
|
${o}
|
|
55
55
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(i=>i.id).join(", ");throw se(new Error(`unknown mode: ${t} (known: ${r})`),k.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[2]??"";if(!s){let c=this.buildConfigOptions();if(c.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
56
56
|
_(no config options advertised yet)_
|
|
57
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=c.map(p=>
|
|
57
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=c.map(p=>zr(p));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
58
58
|
${f.join(`
|
|
59
59
|
|
|
60
60
|
`)}
|
|
@@ -64,7 +64,7 @@ ${f.join(`
|
|
|
64
64
|
Available options:
|
|
65
65
|
${c}
|
|
66
66
|
`},_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:`
|
|
67
|
-
${
|
|
67
|
+
${zr(o)}
|
|
68
68
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(c=>c.value),d=Jn(r,a),u=r;if(d.kind==="resolved")u=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let c=r.toLowerCase(),f=d.kind==="ambiguous"?d.candidates:a.filter(m=>m.toLowerCase().includes(c)),p=f.length>0?f:a,l=d.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${d.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=d.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:`
|
|
69
69
|
${l}.
|
|
70
70
|
${g}:
|
|
@@ -72,10 +72,10 @@ ${g}:
|
|
|
72
72
|
`)}
|
|
73
73
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(u!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:u}),this.applyModelChange(u),{stopReason:"end_turn"}):s==="mode"?(u!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:u}),this.applyModeChange(u),{stopReason:"end_turn"}):s==="agent"?(u!==this.agentId&&await this.runAgentCommandInline(u),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:u}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw se(new Error("/hydra agent requires an agent id"),k.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw se(new Error(`already on agent ${r}`),k.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw se(new Error("agent restart not configured for this session"),k.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),t=this._summarizedThroughEntry;if(e==null&&t==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
|
|
74
74
|
`)),{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"}}runForkCommand(e){return this.enqueuePrompt(()=>this.runForkCommandInline(e,void 0))}async findMessageIdBefore(e){if(!this.historyStore)return;let t=await this.historyStore.load(this.sessionId),s;for(let r of t){if(r.method!=="session/update")continue;let o=r.params?.update?.messageId;if(typeof o=="string"){if(o===e)return s;s=o}}}async runForkCommandInline(e,t){if(!this.forkHook)return this.emitExtensionReply("Fork not configured for this session."),{stopReason:"end_turn"};let s=(e??"").trim(),r;if(s==="verbatim")r="verbatim";else if(s==="synthesis"||s==="")r=void 0;else return this.emitExtensionReply(`Unknown fork argument: \`${s}\`. Use \`/hydra fork\` or \`/hydra fork verbatim\`.`),{stopReason:"end_turn"};try{let i={};if(r&&(i.mode=r),t&&this.historyStore){let d=await this.findMessageIdBefore(t).catch(()=>{});d&&(i.forkAt=d)}let a=(await this.forkHook(Object.keys(i).length>0?i:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(`Forked to [\`${a}\`](hydra://sessions/${a}).`)}catch(i){this.emitExtensionReply(`Fork failed: ${i instanceof Error?i.message:String(i)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw se(new Error("session is closing"),k.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let u of r){if(u.method!=="session/update")continue;let f=(u.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let l=f.sessionUpdate;if(l==="prompt_received"){let g=Ke(f.prompt);g&&s.push({speaker:"user",text:g})}else if(l==="agent_message_chunk"){let m=f.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(l==="tool_call"||l==="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 i=[],o;for(let u of s)o&&o.speaker===u.speaker?o.text+=u.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:u.speaker,text:u.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
|
|
75
|
-
`)}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(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=Gn({synopsis:e,title:t,tail:s,tailK:Cd,tailFloor:xd,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 i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.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 i=new Dt(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Je,Je)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=k.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"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 i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.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(()=>Ur(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>Vr.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{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 i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;this.toolCallKind.note(i,o);let a=this.toolCallKind.effective(i,o);if(a===Er&&Array.isArray(s.locations))for(let c of s.locations){if(!c||typeof c!="object")continue;let f=c.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=c.line,l={path:f,toolCallId:i};typeof p=="number"&&(l.line=p),this.notifyChain("file.edited",l)}if(r!=="tool_call_update")return;let d=typeof s.status=="string"?s.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,d);let u={toolCallId:i,status:d};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),i=!Dr(e,r),o=i?Nd(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw se(new Error("no clients attached to handle permission request"),k.PermissionDenied);let s=this.rewriteForClient(e),r=Lr(s),i=Me(),{toolCall:o,options:a}=s??{};return new Promise((d,u)=>{let c=!1,f=[],p=0,l,g=this.sessionId,m=v=>{c||(c=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},h=v=>v?.code===k.MethodNotFound;function y(v){if(c)return;let w=v.connection.request("session/request_permission",s);f.push({client:v}),p++,w.then(b=>{p--,m(()=>{let A=Hd({toolCallId:r,result:b,resolver:v});for(let C of f)C.client.clientId!==v.clientId&&C.client.connection.notify("session/update",{sessionId:g,update:A}).catch(()=>{});d(b)})}).catch(b=>{if(p--,h(b)||(l=b),p===0&&!c){let A=l??se(new Error("no client handled permission request"),k.PermissionDenied);m(()=>u(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,y);for(let v of t)y(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Me(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let u={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},c=this.insertEntryAt(u,o);this.persistRewrite(),this.broadcastQueueAdded(u,{position:c}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>gt(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=Ke(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
76
|
-
`)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){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(i){let d=t.slice(s.length).trim(),u=d?`/hydra ${r} ${d}`:`/hydra ${r}`;a=await this.handleSlashCommand(u,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=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,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function se(n,e){return n.code=e,n}var
|
|
75
|
+
`)}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(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=Gn({synopsis:e,title:t,tail:s,tailK:xd,tailFloor:Md,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 i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.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 i=new Dt(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Je,Je)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=k.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"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 i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.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(()=>Dr(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>Kr.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{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 i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;this.toolCallKind.note(i,o);let a=this.toolCallKind.effective(i,o);if(a===Er&&Array.isArray(s.locations))for(let c of s.locations){if(!c||typeof c!="object")continue;let f=c.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=c.line,l={path:f,toolCallId:i};typeof p=="number"&&(l.line=p),this.notifyChain("file.edited",l)}if(r!=="tool_call_update")return;let d=typeof s.status=="string"?s.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,d);let u={toolCallId:i,status:d};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),i=!Lr(e,r),o=i?Hd(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw se(new Error("no clients attached to handle permission request"),k.PermissionDenied);let s=this.rewriteForClient(e),r=qr(s),i=Me(),{toolCall:o,options:a}=s??{};return new Promise((d,u)=>{let c=!1,f=[],p=0,l,g=this.sessionId,m=v=>{c||(c=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},h=v=>v?.code===k.MethodNotFound;function y(v){if(c)return;let w=v.connection.request("session/request_permission",s);f.push({client:v}),p++,w.then(b=>{p--,m(()=>{let A=jd({toolCallId:r,result:b,resolver:v});for(let C of f)C.client.clientId!==v.clientId&&C.client.connection.notify("session/update",{sessionId:g,update:A}).catch(()=>{});d(b)})}).catch(b=>{if(p--,h(b)||(l=b),p===0&&!c){let A=l??se(new Error("no client handled permission request"),k.PermissionDenied);m(()=>u(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,y);for(let v of t)y(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Me(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let u={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},c=this.insertEntryAt(u,o);this.persistRewrite(),this.broadcastQueueAdded(u,{position:c}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>gt(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=Ke(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
76
|
+
`)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){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(i){let d=t.slice(s.length).trim(),u=d?`/hydra ${r} ${d}`:`/hydra ${r}`;a=await this.handleSlashCommand(u,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=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,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function se(n,e){return n.code=e,n}var Pd=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 Lr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Pd.has(s)}function Td(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 _d(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 $d(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 Ge(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function ht(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Fd(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function Od(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.chunks.push(i.text),n.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.thinkingChars+=i.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 Nd(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function Hd(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:Me()}}}function qt(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 qr(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 jd(n){let e=Bd(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=Ud(n.resolver),t}function Bd(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function Ud(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 Ke(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Xn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Dd(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function zr(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
|
|
77
77
|
${s.join(`
|
|
78
|
-
`)}`}function Zn(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}}W();Te();import*as et from"fs/promises";import*as
|
|
78
|
+
`)}`}function Zn(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}}W();Te();import*as et from"fs/promises";import*as em from"path";import{customAlphabet as zd}from"nanoid";import{z as R}from"zod";import{z as Xe}from"zod";var Ld=Xe.object({source:Xe.string(),reason:Xe.string(),raisedAt:Xe.number(),payload:Xe.unknown()}),Gr=Xe.array(Ld);import{z}from"zod";var Yr=z.object({status:z.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:z.number(),iter:z.number().int().nonnegative().optional(),attempts:z.number().int().nonnegative().optional(),lastError:z.string().optional(),worker:z.object({upstreamSessionId:z.string(),pid:z.number().int().nonnegative()}).optional()}),yt=z.object({goal:z.string().optional(),outcome:z.string().optional(),files_touched:z.array(z.string()).optional(),tools_used:z.array(z.string()).optional(),rejected_approaches:z.array(z.string()).optional(),open_threads:z.array(z.string()).optional(),decisions:z.array(z.string()).optional(),file_edit_intentions:z.array(z.string()).optional(),unresolved_errors:z.array(z.string()).optional(),tool_state:z.array(z.string()).optional()}),Xr=200,es=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
79
79
|
{
|
|
80
80
|
"title": "short summary, max 80 chars",
|
|
81
81
|
"synopsis": {
|
|
@@ -85,7 +85,7 @@ ${s.join(`
|
|
|
85
85
|
"open_threads": ["work started but not finished"]
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
|
-
Use empty arrays/strings where a field doesn't apply.`;function
|
|
88
|
+
Use empty arrays/strings where a field doesn't apply.`;function Zr(n){let e=n.trim();if(e.length===0)return;let t=Ze(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=Ze(e.slice(i,o+1)))}if(t===void 0){let i=ti(e);i!==void 0&&(t=Ze(i))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Xr))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=yt.safeParse(s.synopsis);i.success&&qd(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var ts=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
89
89
|
{
|
|
90
90
|
"title": "short summary, max 80 chars",
|
|
91
91
|
"goal": "the user's original ask",
|
|
@@ -97,19 +97,19 @@ Use empty arrays/strings where a field doesn't apply.`;function Xr(n){let e=n.tr
|
|
|
97
97
|
"unresolved_errors": ["errors left open at session end"],
|
|
98
98
|
"tool_state": ["runtime state relevant for recall"]
|
|
99
99
|
}
|
|
100
|
-
Use empty arrays/strings where a field doesn't apply.`;function Zr(n){let e=n.trim();if(e.length===0)return;let t=Ze(e);if(t===void 0){let u=e.indexOf("{"),c=e.lastIndexOf("}");u>=0&&c>u&&(t=Ze(e.slice(u,c+1)))}if(t===void 0){let u=ei(e);u!==void 0&&(t=Ze(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,Yr))}let i={},o=!1,a=["goal","outcome"];for(let u of a)if(typeof s[u]=="string"){let c=s[u].trim();c.length>0&&(i[u]=c,o=!0)}let d=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let u of d)if(Array.isArray(s[u])){let c=s[u],f=z.array(z.string()).safeParse(c);f.success&&c.length>0&&(i[u]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Ze(n){try{return JSON.parse(n)}catch{return}}function ei(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function Ld(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 zd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Jd=qd(zd,16),Wd="hydra_lineage_";function wt(){return`${Wd}${Jd()}`}var ss=R.object({name:R.string(),description:R.string().optional()}),rs=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),Qd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),is=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),os=R.object({name:R.string(),version:R.string().optional()}),Vd=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Kd=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:yt.optional(),compactionState:Gr.optional(),rollbackBreadcrumb:Vd.optional(),summarizedThroughEntry:R.number().int().nonnegative().optional(),agentArgs:R.array(R.string()).optional(),currentModel:R.string().optional(),currentMode:R.string().optional(),currentUsage:is.optional(),agentCommands:R.array(ss).optional(),agentModes:R.array(rs).optional(),agentModels:R.array(Qd).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:os.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:Kr.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),ns=/^[A-Za-z0-9_-]+$/;function Gd(n){if(!ns.test(n))throw new Error(`unsafe session id: ${n}`)}var zt=class{async write(e){Gd(e.sessionId);let t={version:1,...e};await ce(S.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!ns.test(e))return;let t=await ue(S.sessionFile(e));if(t!==void 0)try{return Kd.parse(t)}catch{return}}async delete(e){if(ns.test(e)){try{await et.unlink(S.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await et.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 et.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 as(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}}W();Te();import*as be from"fs/promises";import{z as he}from"zod";var Yd=he.object({version:he.literal(1),agentId:he.string(),upstreamSessionId:he.string(),deletedAt:he.string(),upstreamUpdatedAt:he.string().optional(),cwd:he.string().optional(),title:he.string().optional(),reason:he.enum(["user","expired"]).optional(),interactive:he.boolean().optional()}),Jt=class{async add(e){let t={version:1,...e};await ce(S.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await be.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 Yd.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await be.unlink(S.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await be.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 be.readdir(S.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await be.readdir(S.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function ti(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as pi from"fs/promises";import{fileURLToPath as Xd}from"url";import*as vt from"path";import*as Wt from"fs";function Zd(){try{let n=vt.dirname(Xd(import.meta.url));for(let e=0;e<8;e+=1){let t=vt.join(n,"package.json");if(Wt.existsSync(t)){let r=JSON.parse(Wt.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=vt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var Y=Zd(),Qt="hydra-acp-cat";var ec=12e4;async function si(n,e,t){let s=n.timeoutMs??ec,r,i,o=!1;try{let a=(async()=>{r=xe.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let d=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:Y}}),u=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),c=u.sessionId;if(typeof c!="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?.(c,r.pid),n.modelId){let g=nc(u);if(g.size===0||g.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:c,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=tc(g);m.length>0&&f.push(m)}),await r.connection.request("session/prompt",{sessionId:c,prompt:[{type:"text",text:e}]});let p=f.join(""),l=t(p);if(!l){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 l})();return await new Promise((d,u)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),d(void 0)},s),i.unref?.(),a.then(c=>{i&&clearTimeout(i),o||d(c)},c=>{i&&clearTimeout(i),o||u(c)})})}catch(a){let d=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${d}`),n.onFailure?.(`agent ${n.agentId} failed: ${d}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Vt(n){let e=Ve(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
|
+
Use empty arrays/strings where a field doesn't apply.`;function ei(n){let e=n.trim();if(e.length===0)return;let t=Ze(e);if(t===void 0){let u=e.indexOf("{"),c=e.lastIndexOf("}");u>=0&&c>u&&(t=Ze(e.slice(u,c+1)))}if(t===void 0){let u=ti(e);u!==void 0&&(t=Ze(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,Xr))}let i={},o=!1,a=["goal","outcome"];for(let u of a)if(typeof s[u]=="string"){let c=s[u].trim();c.length>0&&(i[u]=c,o=!0)}let d=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let u of d)if(Array.isArray(s[u])){let c=s[u],f=z.array(z.string()).safeParse(c);f.success&&c.length>0&&(i[u]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Ze(n){try{return JSON.parse(n)}catch{return}}function ti(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function qd(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 Jd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wd=zd(Jd,16),Qd="hydra_lineage_";function wt(){return`${Qd}${Wd()}`}var ss=R.object({name:R.string(),description:R.string().optional()}),rs=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),Vd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),is=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),os=R.object({name:R.string(),version:R.string().optional()}),Kd=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Gd=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:yt.optional(),compactionState:Yr.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:is.optional(),agentCommands:R.array(ss).optional(),agentModes:R.array(rs).optional(),agentModels:R.array(Vd).optional(),pendingHistorySync:R.boolean().optional(),pendingAgentSwap:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),forkSynthesisState:R.enum(["running","failed"]).optional(),originatingClient:os.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:Gr.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),ns=/^[A-Za-z0-9_-]+$/;function Yd(n){if(!ns.test(n))throw new Error(`unsafe session id: ${n}`)}var zt=class{async write(e){Yd(e.sessionId);let t={version:1,...e};await ce(S.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!ns.test(e))return;let t=await ue(S.sessionFile(e));if(t!==void 0)try{return Gd.parse(t)}catch{return}}async delete(e){if(ns.test(e)){try{await et.unlink(S.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await et.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 et.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 as(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}}W();Te();import*as be from"fs/promises";import{z as he}from"zod";var Xd=he.object({version:he.literal(1),agentId:he.string(),upstreamSessionId:he.string(),deletedAt:he.string(),upstreamUpdatedAt:he.string().optional(),cwd:he.string().optional(),title:he.string().optional(),reason:he.enum(["user","expired"]).optional(),interactive:he.boolean().optional()}),Jt=class{async add(e){let t={version:1,...e};await ce(S.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await be.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 Xd.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await be.unlink(S.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await be.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 be.readdir(S.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await be.readdir(S.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function ni(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as mi from"fs/promises";import{fileURLToPath as Zd}from"url";import*as vt from"path";import*as Wt from"fs";function ec(){try{let n=vt.dirname(Zd(import.meta.url));for(let e=0;e<8;e+=1){let t=vt.join(n,"package.json");if(Wt.existsSync(t)){let r=JSON.parse(Wt.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=vt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var Y=ec(),Qt="hydra-acp-cat";var tc=12e4;async function ri(n,e,t){let s=n.timeoutMs??tc,r,i,o=!1;try{let a=(async()=>{r=xe.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let d=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:Y}}),u=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),c=u.sessionId;if(typeof c!="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?.(c,r.pid),n.modelId){let g=sc(u);if(g.size===0||g.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:c,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=nc(g);m.length>0&&f.push(m)}),await r.connection.request("session/prompt",{sessionId:c,prompt:[{type:"text",text:e}]});let p=f.join(""),l=t(p);if(!l){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 l})();return await new Promise((d,u)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),d(void 0)},s),i.unref?.(),a.then(c=>{i&&clearTimeout(i),o||d(c)},c=>{i&&clearTimeout(i),o||u(c)})})}catch(a){let d=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${d}`),n.onFailure?.(`agent ${n.agentId} failed: ${d}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Vt(n){let e=Ve(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}
|
|
101
101
|
|
|
102
102
|
${e}
|
|
103
103
|
|
|
104
104
|
${es}`:`${t}
|
|
105
105
|
|
|
106
|
-
${es}`;return
|
|
106
|
+
${es}`;return ri(n,s,Zr)}async function ii(n){let e=Ve(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}
|
|
107
107
|
|
|
108
108
|
${e}
|
|
109
109
|
|
|
110
110
|
${ts}`:`${t}
|
|
111
111
|
|
|
112
|
-
${ts}`;return si(n,s,Zr)}function tc(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 nc(n){let e=new Set;ni(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&ni(e,t.availableModels),e}function ni(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 sc(n){let e=new Map;for(let t of ci(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 ai(n){return sc(n).map(e=>e.name)}function rc(n){let e=new Map;for(let t of ci(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function di(n){return rc(n).map(e=>e.path)}function ci(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,u=e.get(d);u===void 0?(u={toolName:ii(i),paths:new Set},e.set(d,u)):u.toolName=ii(i);for(let c of oi(i.rawInput,i.locations))u.paths.add(c);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of oi(i.rawInput,i.locations))a.paths.add(d)}return e}function ii(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function oi(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}for(let s of Pr(e))t.add(s);return t}W();var ic=2,Kt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??ic}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(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},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 i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let d=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,u=await this.opts.registry.getAgent(d);if(!u){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let c=await oe(u,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?i.currentModel:void 0):this.opts.synopsisModel,l=S.sessionDir(e);if(await pi.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${o.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),s==="compaction"){let g=this.opts.compactionMaxIterations??3,m=0,h=a??0,y,v=0,w,b=Date.now(),A={targetAgentId:r},C=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),x=T=>{this.opts.broadcastHydraCompaction?.(e,T,A)};await C({status:"requested",requestedAt:b}),x({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${h}`);let T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await ri({agentId:d,cwd:l,plan:c,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{C({status:"running",requestedAt:b,iter:m,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=ui(_.synopsis,T);$&&li($)&&(await this.opts.persistSynopsis(e,$,T.length),y=$,v=T.length,w=void 0,await C({status:"running",requestedAt:b,iter:m}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${fi($)}`))}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(y)m>=g&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} 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 C({status:"failed",requestedAt:b,iter:m,lastError:T}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await C({status:"failed",requestedAt:b,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let g=await Vt({agentId:d,cwd:l,plan:c,history:o,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=ui(g.synopsis,o);m&&li(m)?(await this.opts.persistSynopsis(e,m,o.length),g.title&&await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!g.title)} fields=${fi(m)}`)):g.title&&(await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function ui(n,e){let t=di(e),s=ai(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 li(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 fi(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(",")}]`}W();import*as L from"fs/promises";import{createReadStream as uc}from"fs";import{createGunzip as lc,gzip as fc,gunzip as pc}from"zlib";import{createInterface as mc}from"readline";import{promisify as vi}from"util";function mi(n){return n==="summary"?"summary":"inline"}var ds=256;function gi(n,e){return e!=="summary"?n:n.map(oc)}function oc(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(hi));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=cs(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function ac(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function hi(n){if(ac(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=cs(e.text)),typeof e.content=="string"?t.content=cs(e.content):e.content&&typeof e.content=="object"&&(t.content=hi(e.content)),t}function cs(n){if(typeof n=="string"&&n.length>ds){let e=n.length-ds;return`${n.slice(0,ds)}\u2026[+${e} chars omitted from summary export]`}return n}var dc=2048;function yi(n){let e=new Set,t=s=>{if(wi(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 wi(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function cc(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 fs(n,e){if(!cc(n))return n;let t=n.params,s=t.update,r=await us(s,e);return{...n,params:{...t,update:r}}}async function us(n,e){if(typeof n=="string"){if(n.length<=dc)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 us(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await us(r,e);return t}return n}async function ps(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await ls(t,e);return s===t?n:{...n,params:s}}async function ls(n,e){if(wi(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await ls(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await ls(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var gc=vi(fc),hc=vi(pc),yc=/^history\.jsonl\.(\d+)(\.gz)?$/,le=/^[A-Za-z0-9_-]+$/,wc=1e3,vc=1e7,bc=10,Gt=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??wc,this.archiveMaxBytes=e.archiveMaxBytes??vc,this.archiveTiers=e.archiveTiers??bc}async append(e,t){if(le.test(e))return this.enqueue(e,async()=>{await L.mkdir(S.sessionDir(e),{recursive:!0});let s=await fs(t,i=>$n(e,i)),r=JSON.stringify(s)+`
|
|
112
|
+
${ts}`;return ri(n,s,ei)}function nc(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 sc(n){let e=new Set;si(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&si(e,t.availableModels),e}function si(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 rc(n){let e=new Map;for(let t of ui(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 di(n){return rc(n).map(e=>e.name)}function ic(n){let e=new Map;for(let t of ui(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function ci(n){return ic(n).map(e=>e.path)}function ui(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,u=e.get(d);u===void 0?(u={toolName:oi(i),paths:new Set},e.set(d,u)):u.toolName=oi(i);for(let c of ai(i.rawInput,i.locations))u.paths.add(c);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of ai(i.rawInput,i.locations))a.paths.add(d)}return e}function oi(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function ai(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}for(let s of Pr(e))t.add(s);return t}W();var oc=2,Kt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??oc}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(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},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 i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let d=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,u=await this.opts.registry.getAgent(d);if(!u){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let c=await oe(u,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?i.currentModel:void 0):this.opts.synopsisModel,l=S.sessionDir(e);if(await mi.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${o.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),s==="compaction"){let g=this.opts.compactionMaxIterations??3,m=0,h=a??0,y,v=0,w,b=Date.now(),A={targetAgentId:r},C=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),x=T=>{this.opts.broadcastHydraCompaction?.(e,T,A)};await C({status:"requested",requestedAt:b}),x({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${h}`);let T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await ii({agentId:d,cwd:l,plan:c,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{C({status:"running",requestedAt:b,iter:m,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=li(_.synopsis,T);$&&fi($)&&(await this.opts.persistSynopsis(e,$,T.length),y=$,v=T.length,w=void 0,await C({status:"running",requestedAt:b,iter:m}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${pi($)}`))}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(y)m>=g&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} 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 C({status:"failed",requestedAt:b,iter:m,lastError:T}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await C({status:"failed",requestedAt:b,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let g=await Vt({agentId:d,cwd:l,plan:c,history:o,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=li(g.synopsis,o);m&&fi(m)?(await this.opts.persistSynopsis(e,m,o.length),g.title&&await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!g.title)} fields=${pi(m)}`)):g.title&&(await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function li(n,e){let t=ci(e),s=di(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 fi(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 pi(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(",")}]`}W();import*as L from"fs/promises";import{createReadStream as lc}from"fs";import{createGunzip as fc,gzip as pc,gunzip as mc}from"zlib";import{createInterface as gc}from"readline";import{promisify as bi}from"util";function gi(n){return n==="summary"?"summary":"inline"}var ds=256;function hi(n,e){return e!=="summary"?n:n.map(ac)}function ac(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(yi));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=cs(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function dc(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function yi(n){if(dc(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=cs(e.text)),typeof e.content=="string"?t.content=cs(e.content):e.content&&typeof e.content=="object"&&(t.content=yi(e.content)),t}function cs(n){if(typeof n=="string"&&n.length>ds){let e=n.length-ds;return`${n.slice(0,ds)}\u2026[+${e} chars omitted from summary export]`}return n}var cc=2048;function wi(n){let e=new Set,t=s=>{if(vi(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 vi(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function uc(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 fs(n,e){if(!uc(n))return n;let t=n.params,s=t.update,r=await us(s,e);return{...n,params:{...t,update:r}}}async function us(n,e){if(typeof n=="string"){if(n.length<=cc)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 us(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await us(r,e);return t}return n}async function ps(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await ls(t,e);return s===t?n:{...n,params:s}}async function ls(n,e){if(vi(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await ls(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await ls(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var hc=bi(pc),yc=bi(mc),wc=/^history\.jsonl\.(\d+)(\.gz)?$/,le=/^[A-Za-z0-9_-]+$/,vc=1e3,bc=1e7,Ic=10,Gt=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??vc,this.archiveMaxBytes=e.archiveMaxBytes??bc,this.archiveTiers=e.archiveTiers??Ic}async append(e,t){if(le.test(e))return this.enqueue(e,async()=>{await L.mkdir(S.sessionDir(e),{recursive:!0});let s=await fs(t,i=>$n(e,i)),r=JSON.stringify(s)+`
|
|
113
113
|
`;await L.appendFile(S.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(le.test(e))return this.enqueue(e,async()=>{await L.mkdir(S.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await fs(i,o=>$n(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
|
|
114
114
|
`)+`
|
|
115
115
|
`;await L.writeFile(S.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(le.test(e))return this.enqueue(e,async()=>{let s;try{s=await L.readFile(S.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=s.split(`
|
|
@@ -117,38 +117,38 @@ ${ts}`;return si(n,s,Zr)}function tc(n){if(!n||typeof n!="object")return"";let e
|
|
|
117
117
|
`)+`
|
|
118
118
|
`,{encoding:"utf8",mode:384})})}async spillToArchive(e,t){let s=t.join(`
|
|
119
119
|
`)+`
|
|
120
|
-
`,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=S.historyArchiveFile(e,r);await L.mkdir(S.sessionDir(e),{recursive:!0}),await L.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await L.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?(await this.sealArchive(e,r),this.nextArchiveIndex.set(e,r+1)):this.nextArchiveIndex.set(e,r),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let s=S.historyArchiveFile(e,t),r;try{r=await L.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await
|
|
121
|
-
`)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let u=d;typeof u.method=="string"&&typeof u.recordedAt=="number"&&r.push({method:u.method,params:u.params,recordedAt:u.recordedAt})}}return r}async*streamFile(e){let t;try{t=
|
|
122
|
-
`)){if(p.length===0)continue;let l;try{l=JSON.parse(p)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let g=l;typeof g.method=="string"&&typeof g.recordedAt=="number"&&o.push({method:g.method,params:g.params,recordedAt:g.recordedAt})}let a=t.maxEntries??this.maxEntries,d=o.length>a?o.slice(-a):o;if(!s)return d;let u=new Map,c=async p=>{let l=u.get(p);if(l!==void 0)return l;let g=await ct(e,p);return u.set(p,g),g},f=[];for(let p of d)f.push(await ps(p,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(le.test(e))return this.enqueue(e,async()=>{try{await L.unlink(S.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let t=await this.listArchiveIndices(e);for(let s of t)await this.unlinkArchive(e,s);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await tr(e);try{await L.rmdir(S.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};W();import{promises as
|
|
120
|
+
`,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=S.historyArchiveFile(e,r);await L.mkdir(S.sessionDir(e),{recursive:!0}),await L.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await L.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?(await this.sealArchive(e,r),this.nextArchiveIndex.set(e,r+1)):this.nextArchiveIndex.set(e,r),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let s=S.historyArchiveFile(e,t),r;try{r=await L.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await hc(r);await L.writeFile(s+".gz",i,{mode:384});try{await L.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let s=await this.listArchiveIndices(e),r=s.length===0?0:s[s.length-1],i=r===0?1:r;if(r>0){let o=S.historyArchiveFile(e,r),a=o+".gz",d=!1;try{await L.access(a),d=!0}catch{d=!1}if(d)i=r+1;else try{(await L.stat(o)).size>=this.archiveMaxBytes&&(i=r+1)}catch{i=r}}return this.nextArchiveIndex.set(e,i),i}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let s=await this.listArchiveIndices(e),i=(s.includes(t)?s.length:s.length+1)-this.archiveTiers,o=0;for(;i>0&&o<s.length;){let a=s[o];a!==t&&(await this.unlinkArchive(e,a),i-=1),o+=1}}async unlinkArchive(e,t){let s=S.historyArchiveFile(e,t);for(let r of[s,s+".gz"])try{await L.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await L.readdir(S.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=new Set;for(let r of t){let i=wc.exec(r);if(!i)continue;let o=Number.parseInt(i[1],10);Number.isFinite(o)&&o>0&&s.add(o)}return[...s].sort((r,i)=>r-i)}async listArchives(e){if(!le.test(e))return[];let t=await this.listArchiveIndices(e),s=[];for(let r of t){let i=S.historyArchiveFile(e,r),o=i+".gz",a=i;try{await L.access(o),a=o}catch{a=i}s.push({index:r,path:a})}return s}async loadArchives(e){if(!le.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let s=await this.listArchives(e),r=[];for(let{path:i}of s){let o;try{if(i.endsWith(".gz")){let a=await L.readFile(i);o=(await yc(a)).toString("utf8")}else o=await L.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
|
|
121
|
+
`)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let u=d;typeof u.method=="string"&&typeof u.recordedAt=="number"&&r.push({method:u.method,params:u.params,recordedAt:u.recordedAt})}}return r}async*streamFile(e){let t;try{t=lc(e)}catch(o){if(o.code==="ENOENT")return;throw o}if(await new Promise(o=>{let a=!1,d=u=>{a||(a=!0,o(u))};t.once("error",u=>{u.code==="ENOENT"?d(!0):(t.destroy(),d(!1))}),t.once("readable",()=>d(!1)),t.once("end",()=>d(!1))}))return;let r=e.endsWith(".gz")?t.pipe(fc()):t,i=gc({input:r,crlfDelay:1/0});try{for await(let o of i){if(o.length===0)continue;let a;try{a=JSON.parse(o)}catch{continue}if(!a||typeof a!="object"||Array.isArray(a))continue;let d=a;typeof d.method=="string"&&typeof d.recordedAt=="number"&&(yield{method:d.method,params:d.params,recordedAt:d.recordedAt})}}finally{i.close(),t.destroy()}}async getArchiveLineCounts(e){if(!le.test(e))return[];let t=this.archiveLineCounts.get(e),s=await this.listArchives(e);if(t&&t.length===s.length&&t.every((i,o)=>i.index===s[o].index&&i.path===s[o].path))return t;let r=[];for(let{index:i,path:o}of s){let a=t?.find(u=>u.index===i&&u.path===o);if(a){r.push(a);continue}let d=0;for await(let u of this.streamFile(o))d+=1;r.push({index:i,path:o,lineCount:d})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,s){return ps(t,async r=>{let i=s.get(r);if(i!==void 0)return i;let o=await ct(e,r);return s.set(r,o),o})}async*iterRecallNewestFirst(e){if(!le.test(e))return;let t=this.writeQueues.get(e);t&&await t;let s=await this.getArchiveLineCounts(e),r=0;for(let u of s)r+=u.lineCount;let i=new Map,o=[];for await(let u of this.streamFile(S.historyFile(e)))o.push(u);for(let u=o.length-1;u>=0;u--){let c=await this.hydrateEntry(e,o[u],i);yield{entryId:r+u,entry:c}}let a=new Array(s.length),d=0;for(let u=0;u<s.length;u++)a[u]=d,d+=s[u].lineCount;for(let u=s.length-1;u>=0;u--){let c=s[u],f=[];for await(let l of this.streamFile(c.path))f.push(l);let p=a[u];for(let l=f.length-1;l>=0;l--){let g=await this.hydrateEntry(e,f[l],i);yield{entryId:p+l,entry:g}}}}async rangeSlice(e,t,s){if(!le.test(e))return[];if(s<t)return[];let r=this.writeQueues.get(e);r&&await r;let i=await this.getArchiveLineCounts(e),o=0;for(let c of i)o+=c.lineCount;let a=[],d=new Map,u=0;for(let c of i){let f=u,p=u+c.lineCount;if(u=p,p<=t)continue;if(f>s)break;let l=0;for await(let g of this.streamFile(c.path)){let m=f+l;if(l+=1,m<t)continue;if(m>s)break;let h=await this.hydrateEntry(e,g,d);a.push({entryId:m,entry:h})}}if(s>=o){let c=Math.max(t-o,0),f=s-o,p=0;for await(let l of this.streamFile(S.historyFile(e))){if(p>f)break;if(p>=c){let g=await this.hydrateEntry(e,l,d);a.push({entryId:o+p,entry:g})}p+=1}}return a}async getRecallTotalCount(e){if(!le.test(e))return 0;let t=await this.getArchiveLineCounts(e),s=0;for(let i of t)s+=i.lineCount;let r=0;for await(let i of this.streamFile(S.historyFile(e)))r+=1;return s+r}async load(e,t={}){if(!le.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await L.readFile(S.historyFile(e),"utf8")}catch(p){if(p.code==="ENOENT")return[];throw p}let o=[];for(let p of i.split(`
|
|
122
|
+
`)){if(p.length===0)continue;let l;try{l=JSON.parse(p)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let g=l;typeof g.method=="string"&&typeof g.recordedAt=="number"&&o.push({method:g.method,params:g.params,recordedAt:g.recordedAt})}let a=t.maxEntries??this.maxEntries,d=o.length>a?o.slice(-a):o;if(!s)return d;let u=new Map,c=async p=>{let l=u.get(p);if(l!==void 0)return l;let g=await ct(e,p);return u.set(p,g),g},f=[];for(let p of d)f.push(await ps(p,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(le.test(e))return this.enqueue(e,async()=>{try{await L.unlink(S.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let t=await this.listArchiveIndices(e);for(let s of t)await this.unlinkArchive(e,s);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await tr(e);try{await L.rmdir(S.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};W();import{promises as Ii}from"fs";import*as Si from"path";async function ki(n,e){await Ii.mkdir(Si.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await Ii.writeFile(n,t.length>0?t.join(`
|
|
123
123
|
`)+`
|
|
124
|
-
`:"")}import{z as D}from"zod";var Ic=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),Sc=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:yt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:is.optional(),agentCommands:D.array(ss).optional(),agentModes:D.array(rs).optional(),interactive:D.boolean().optional(),originatingClient:os.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),kc=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:Sc,history:D.array(Ic),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.string()).optional()});function bt(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 ki(n){return kc.parse(n)}var Ai=900*1e3,Cc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Yt=Ac(Cc,16),Xt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>xe.spawn(a)),this.store=s??new zt,this.tombstones=r.tombstones??new Jt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Gt({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),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 i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new Kt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,d)=>{let u=this.get(a);if(u){await u.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,u)=>this.persistSynopsis(a,d,u),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,u)=>{if(u.targetAgentId)return;let c=this.get(a);c&&(c.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,u)=>{this.emitSwapPhase(a,u.targetAgentId,d)},onSynthesisArtifact:async(a,d,u,c)=>{await this.dispatchSynthesisSwap(a,d,u,c)}}),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 i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,o,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 d=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,d)}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 d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.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 o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ue(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 i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Yt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Ye({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:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.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:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),forkHook:i=>this.forkSession(r.sessionId,i??{}),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).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 i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=k.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=k.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await oe(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}});o=m.agentCapabilities,i.authMethods=It(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Re(m,i)}let a;try{let m=Ci(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===k.AuthRequired)throw await i.kill().catch(()=>{}),Re(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
125
|
-
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=ws(a??{}),u=e.agentModes??gs(ys(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(u?.map(m=>m.id))}`);let c=await qe({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:u,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(c)} for sessionId=${e.hydraSessionId}`);let f=ms(a??{}),p=gs(hs(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=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let l=await ze({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new Ye({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers: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:l,currentMode:c,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(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),forkHook:m=>this.forkSession(g.sessionId,m??{}),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,i=await qe({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await ze({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Ye({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,c)=>this.bootstrapAgentLoad(u,{...c,mcpServers:c.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,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(d.sessionId),scheduleCompaction:u=>this.scheduleCompaction(d.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(d.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(d.sessionId),uncompactHook:()=>this.performUncompact(d.sessionId),forkHook:u=>this.forkSession(d.sessionId,u??{}),onCompactionSwapHook:u=>{this.mutateRecord(d.sessionId,{rollbackBreadcrumb:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(d.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(d),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${d.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?d.seedFromFork(e.synopsis).catch(()=>{}):d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await $e.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:Z(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=k.AgentNotInstalled,l}let s=await oe(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Ei.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}})}catch(l){throw await r.kill().catch(()=>{}),Re(l,r)}if(r.authMethods=It(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(l){throw await r.kill().catch(()=>{}),l}await r.kill().catch(()=>{});let d=new Set;for(let l of this.sessions.values())d.add(`${l.agentId}::${l.upstreamSessionId}`);let u=await this.store.list().catch(()=>[]);for(let l of u)d.add(`${l.agentId}::${l.upstreamSessionId}`);let c=S.sessionsDir(),f=[],p=0;for(let l of a){let g=`${e}::${l.sessionId}`;if(d.has(g)){p+=1;continue}if(xc(l.cwd,c)){p+=1;continue}let m=await this.tombstones.read(e,l.sessionId).catch(()=>{});if(m){if(!ti(m,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 ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ve}${Yt()}`,y=new Date().toISOString(),v=l.updatedAt??y,w={sessionId:h,lineageId:wt(),upstreamSessionId:l.sessionId,agentId:e,cwd:l.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};l.title!==void 0&&(w.title=l.title);let b=as(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 i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let u of d){if(typeof u.sessionId!="string"||typeof u.cwd!="string")continue;let c={sessionId:u.sessionId,cwd:u.cwd};typeof u.title=="string"&&(c.title=u.title),typeof u.updatedAt=="string"&&(c.updatedAt=u.updatedAt),t.push(c)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=k.AgentNotInstalled,i}let s=await oe(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}}),o=i.agentCapabilities;r.authMethods=It(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=ms(a),c=hs(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==u){let g=Qe(f,c),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,d,f,m)&&(u=f);else if(g.kind==="resolved")(g.modelId===u||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(u=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(u)}`);else{let h=c.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let p=ys(a),l=ws(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:u,initialModels:c.length>0?c:void 0,initialModes:p.length>0?p:void 0,initialMode:l}}catch(i){throw await r.kill().catch(()=>{}),Re(Mi(i,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 o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=k.AgentNotInstalled,o}let r=await oe(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}}),a=o.agentCapabilities;i.authMethods=It(o.authMethods);let d=Ci(t.agentId,void 0),u=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...d&&{_meta:d}}),c=ms(u),f=gs(hs(u)),p=ys(u),l=ws(u);return{agent:i,upstreamSessionId:e,agentMeta:u._meta,agentCapabilities:a,initialModel:c,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:l}}catch(o){throw await i.kill().catch(()=>{}),Re(Mi(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}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 i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.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 d=new Error(`agent ${e} not found in registry`);throw d.code=k.AgentNotInstalled,d}let i=await oe(r,[],{npmRegistry:this.npmRegistry}),o=t??Z(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}});a.authMethods=It(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Re(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=k.AgentNotInstalled,s}return oe(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=tt({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=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)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);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:Pi(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=Mc(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 ct(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:Rc(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 i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Ke(r.update.prompt),o=Zn(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ve))return;let t=ve+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=k.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await St(t.sessionId),d=tt({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:d,priority:t.priority,updatedAt:u,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await St(s.sessionId),i=tt(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=c=>e.includeNonInteractive?!0:c===!0,i=[...this.sessions.values()].filter(c=>!e.cwd||c.cwd===e.cwd),o=await Promise.all(i.map(c=>St(c.sessionId)));for(let c=0;c<i.length;c+=1){let f=i[c],p=o[c];s.add(f.sessionId);let l=tt({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(l))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:l,priority:f.priority,updatedAt:g,attachedClients:f.attachedCount,status:"warm",agentPid:f.agentPid,busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let d=(await this.store.list().catch(c=>{throw this.logger?.warn(`session list: store.list() failed: ${c?.message??String(c)}`),c})).filter(c=>!s.has(c.sessionId)&&(!e.cwd||c.cwd===e.cwd)),u=await Promise.all(d.map(c=>St(c.sessionId)));for(let c=0;c<d.length;c+=1){let f=d[c],p=u[c],l=tt(f,p.hasContent);if(!r(l))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:l,priority:f.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((c,f)=>c.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=wt(),c={...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=c}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Ri(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let u of yi(o)){let c=await Zs(e,u);c&&(d[u]=c.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=k.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ve}${Yt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=k.SessionNotFound,w}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}let o=await this.histories.load(e).catch(()=>[]),a=o,d,u=t.mode??"synthesis",c,f,p,l=12e4;if(u==="verbatim")if(t.forkAt!==void 0){let w=qt(o,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=k.InvalidParams,b}d=t.forkAt,a=o.slice(0,w+1)}else{let w=Pc(o);w?(d=w.messageId,a=o.slice(0,w.index+1)):(d="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let b=qt(o,t.forkAt);if(b<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=k.InvalidParams,A}d=t.forkAt,a=o.slice(0,b+1)}else d="",a=o;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}p=w,f=s.currentModel,c="running"}let g=await Ri(e),m=u==="synthesis",h={...s,lineageId:wt(),agentId:r,interactive:!1,...c!==void 0?{forkSynthesisState:c}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=bt({record:h,history:a,promptHistory:g.length>0?g:void 0,hydraVersion:Y,machine:pt()}),v=`${ve}${Yt()}`;return await this.writeImportedRecord({sessionId:v,bundle:y,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d,...c!==void 0?{forkSynthesisState:c}:{}}),m&&(async()=>{try{let w=await oe(p,[],{npmRegistry:this.npmRegistry}),b=await Vt({agentId:r,cwd:t.cwd??S.sessionDir(e),plan:w,history:a,modelId:f,sessionId:e,logger:this.logger,timeoutMs:l});b&&b.synopsis?await this.mutateRecord(v,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await er(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await $e.utimes(S.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Si(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 St(e),i=tt(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,...i!==void 0?{interactive:i}:{}}).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 i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}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 i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let u={...i,extensionState:o,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 i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}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 i=s.phase==="failed";r.broadcastPendingAgentSwap(i?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??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).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(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}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 Br(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ai),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ai/1e3}s)`),await gt(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await gt(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function xc(n,e){if(typeof n!="string"||n.length===0)return!1;let t=kt.resolve(n),s=kt.resolve(e);return t===s||t.startsWith(s+kt.sep)}function Mc(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(c=>c.description!==void 0?{name:c.name,description:c.description}:{name:c.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(c=>{let f={id:c.id};return c.name!==void 0&&(f.name=c.name),c.description!==void 0&&(f.description=c.description),f}):void 0)??e?.agentModes,a=n.availableModels(),u=(a.length>0?a.map(c=>{let f={modelId:c.modelId};return c.name!==void 0&&(f.name=c.name),c.description!==void 0&&(f.description=c.description),f}):void 0)??e?.agentModels;return as({sessionId:n.sessionId,lineageId:e?.lineageId??wt(),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:Pi(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,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 Pi(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 Rc(n){return n?{...n}:void 0}function Ci(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Zt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Ec(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function ms(n){return Zt(n,{nestedKey:"models",configId:"model",fromObject:e=>ye(e.currentModelId)??ye(e.currentModel)??ye(e.modelId)??ye(e.model),fromConfig:e=>ye(e.currentValue)})}function Re(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==k.AuthRequired)return n;let s=u=>!!u&&typeof u=="object"&&!Array.isArray(u),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=k.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function xi(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Mi(n,e,t,s){if(n&&typeof n=="object"&&n.code===k.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${xi(s.cwd)} && ${[s.command,...s.args].map(xi).join(" ")})`:"";if(!o&&!a)return n;let d=[i?r:`agent ${t} failed to start: ${r}`];o&&d.push(`stderr: ${o}`),a&&d.push(a);let u=new Error(d.join(`
|
|
126
|
-
`));if(n&&typeof n=="object"){let c=n;typeof c.code=="number"&&(u.code=c.code),c.data!==void 0&&(u.data=c.data)}return u}function It(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function ye(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function
|
|
127
|
-
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function St(n){try{let e=await $e.stat(S.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function tt(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Qt?!1:e?!0:void 0}import{spawn as
|
|
124
|
+
`:"")}import{z as D}from"zod";var Sc=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),kc=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:yt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:is.optional(),agentCommands:D.array(ss).optional(),agentModes:D.array(rs).optional(),interactive:D.boolean().optional(),originatingClient:os.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),Ac=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:kc,history:D.array(Sc),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.string()).optional()});function bt(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 Ai(n){return Ac.parse(n)}var Ci=900*1e3,xc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Yt=Cc(xc,16),Xt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>xe.spawn(a)),this.store=s??new zt,this.tombstones=r.tombstones??new Jt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Gt({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),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 i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new Kt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,d)=>{let u=this.get(a);if(u){await u.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,u)=>this.persistSynopsis(a,d,u),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,u)=>{if(u.targetAgentId)return;let c=this.get(a);c&&(c.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,u)=>{this.emitSwapPhase(a,u.targetAgentId,d)},onSynthesisArtifact:async(a,d,u,c)=>{await this.dispatchSynthesisSwap(a,d,u,c)}}),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 i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,o,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 d=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,d)}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 d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.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 o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ue(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 i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Yt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Ye({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:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.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:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),forkHook:i=>this.forkSession(r.sessionId,i??{}),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).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 i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=k.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=k.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await oe(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}});o=m.agentCapabilities,i.authMethods=It(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Re(m,i)}let a;try{let m=xi(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===k.AuthRequired)throw await i.kill().catch(()=>{}),Re(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
125
|
+
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=ws(a??{}),u=e.agentModes??gs(ys(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(u?.map(m=>m.id))}`);let c=await qe({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:u,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(c)} for sessionId=${e.hydraSessionId}`);let f=ms(a??{}),p=gs(hs(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=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let l=await ze({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new Ye({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers: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:l,currentMode:c,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(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),forkHook:m=>this.forkSession(g.sessionId,m??{}),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,i=await qe({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await ze({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Ye({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,c)=>this.bootstrapAgentLoad(u,{...c,mcpServers:c.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,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(d.sessionId),scheduleCompaction:u=>this.scheduleCompaction(d.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(d.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(d.sessionId),uncompactHook:()=>this.performUncompact(d.sessionId),forkHook:u=>this.forkSession(d.sessionId,u??{}),onCompactionSwapHook:u=>{this.mutateRecord(d.sessionId,{rollbackBreadcrumb:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(d.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(d),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${d.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?d.seedFromFork(e.synopsis).catch(()=>{}):d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await $e.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:Z(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=k.AgentNotInstalled,l}let s=await oe(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Pi.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}})}catch(l){throw await r.kill().catch(()=>{}),Re(l,r)}if(r.authMethods=It(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(l){throw await r.kill().catch(()=>{}),l}await r.kill().catch(()=>{});let d=new Set;for(let l of this.sessions.values())d.add(`${l.agentId}::${l.upstreamSessionId}`);let u=await this.store.list().catch(()=>[]);for(let l of u)d.add(`${l.agentId}::${l.upstreamSessionId}`);let c=S.sessionsDir(),f=[],p=0;for(let l of a){let g=`${e}::${l.sessionId}`;if(d.has(g)){p+=1;continue}if(Mc(l.cwd,c)){p+=1;continue}let m=await this.tombstones.read(e,l.sessionId).catch(()=>{});if(m){if(!ni(m,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 ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ve}${Yt()}`,y=new Date().toISOString(),v=l.updatedAt??y,w={sessionId:h,lineageId:wt(),upstreamSessionId:l.sessionId,agentId:e,cwd:l.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};l.title!==void 0&&(w.title=l.title);let b=as(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 i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let u of d){if(typeof u.sessionId!="string"||typeof u.cwd!="string")continue;let c={sessionId:u.sessionId,cwd:u.cwd};typeof u.title=="string"&&(c.title=u.title),typeof u.updatedAt=="string"&&(c.updatedAt=u.updatedAt),t.push(c)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=k.AgentNotInstalled,i}let s=await oe(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}}),o=i.agentCapabilities;r.authMethods=It(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=ms(a),c=hs(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==u){let g=Qe(f,c),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,d,f,m)&&(u=f);else if(g.kind==="resolved")(g.modelId===u||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(u=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(u)}`);else{let h=c.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let p=ys(a),l=ws(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:u,initialModels:c.length>0?c:void 0,initialModes:p.length>0?p:void 0,initialMode:l}}catch(i){throw await r.kill().catch(()=>{}),Re(Ri(i,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 o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=k.AgentNotInstalled,o}let r=await oe(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}}),a=o.agentCapabilities;i.authMethods=It(o.authMethods);let d=xi(t.agentId,void 0),u=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...d&&{_meta:d}}),c=ms(u),f=gs(hs(u)),p=ys(u),l=ws(u);return{agent:i,upstreamSessionId:e,agentMeta:u._meta,agentCapabilities:a,initialModel:c,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:l}}catch(o){throw await i.kill().catch(()=>{}),Re(Ri(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}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 i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.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 d=new Error(`agent ${e} not found in registry`);throw d.code=k.AgentNotInstalled,d}let i=await oe(r,[],{npmRegistry:this.npmRegistry}),o=t??Z(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:De,clientInfo:{name:"hydra",version:Y}});a.authMethods=It(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Re(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=k.AgentNotInstalled,s}return oe(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=tt({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=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)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);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:Ti(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=Rc(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 ct(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:Ec(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 i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Ke(r.update.prompt),o=Zn(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ve))return;let t=ve+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=k.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await St(t.sessionId),d=tt({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:d,priority:t.priority,updatedAt:u,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await St(s.sessionId),i=tt(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=c=>e.includeNonInteractive?!0:c===!0,i=[...this.sessions.values()].filter(c=>!e.cwd||c.cwd===e.cwd),o=await Promise.all(i.map(c=>St(c.sessionId)));for(let c=0;c<i.length;c+=1){let f=i[c],p=o[c];s.add(f.sessionId);let l=tt({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(l))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:l,priority:f.priority,updatedAt:g,attachedClients:f.attachedCount,status:"warm",agentPid:f.agentPid,busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let d=(await this.store.list().catch(c=>{throw this.logger?.warn(`session list: store.list() failed: ${c?.message??String(c)}`),c})).filter(c=>!s.has(c.sessionId)&&(!e.cwd||c.cwd===e.cwd)),u=await Promise.all(d.map(c=>St(c.sessionId)));for(let c=0;c<d.length;c+=1){let f=d[c],p=u[c],l=tt(f,p.hasContent);if(!r(l))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:l,priority:f.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((c,f)=>c.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=wt(),c={...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=c}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Ei(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let u of wi(o)){let c=await Zs(e,u);c&&(d[u]=c.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=k.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ve}${Yt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=k.SessionNotFound,w}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}let o=await this.histories.load(e).catch(()=>[]),a=o,d,u=t.mode??"synthesis",c,f,p,l=12e4;if(u==="verbatim")if(t.forkAt!==void 0){let w=qt(o,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=k.InvalidParams,b}d=t.forkAt,a=o.slice(0,w+1)}else{let w=Tc(o);w?(d=w.messageId,a=o.slice(0,w.index+1)):(d="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let b=qt(o,t.forkAt);if(b<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=k.InvalidParams,A}d=t.forkAt,a=o.slice(0,b+1)}else d="",a=o;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}p=w,f=s.currentModel,c="running"}let g=await Ei(e),m=u==="synthesis",h={...s,lineageId:wt(),agentId:r,interactive:!1,...c!==void 0?{forkSynthesisState:c}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=bt({record:h,history:a,promptHistory:g.length>0?g:void 0,hydraVersion:Y,machine:pt()}),v=`${ve}${Yt()}`;return await this.writeImportedRecord({sessionId:v,bundle:y,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d,...c!==void 0?{forkSynthesisState:c}:{}}),m&&(async()=>{try{let w=await oe(p,[],{npmRegistry:this.npmRegistry}),b=await Vt({agentId:r,cwd:t.cwd??S.sessionDir(e),plan:w,history:a,modelId:f,sessionId:e,logger:this.logger,timeoutMs:l});b&&b.synopsis?await this.mutateRecord(v,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await er(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await $e.utimes(S.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ki(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 St(e),i=tt(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,...i!==void 0?{interactive:i}:{}}).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 i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}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 i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let u={...i,extensionState:o,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 i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}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 i=s.phase==="failed";r.broadcastPendingAgentSwap(i?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??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).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(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}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 Ur(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ci),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ci/1e3}s)`),await gt(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await gt(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Mc(n,e){if(typeof n!="string"||n.length===0)return!1;let t=kt.resolve(n),s=kt.resolve(e);return t===s||t.startsWith(s+kt.sep)}function Rc(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(c=>c.description!==void 0?{name:c.name,description:c.description}:{name:c.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(c=>{let f={id:c.id};return c.name!==void 0&&(f.name=c.name),c.description!==void 0&&(f.description=c.description),f}):void 0)??e?.agentModes,a=n.availableModels(),u=(a.length>0?a.map(c=>{let f={modelId:c.modelId};return c.name!==void 0&&(f.name=c.name),c.description!==void 0&&(f.description=c.description),f}):void 0)??e?.agentModels;return as({sessionId:n.sessionId,lineageId:e?.lineageId??wt(),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:Ti(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,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 Ti(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 Ec(n){return n?{...n}:void 0}function xi(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Zt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Pc(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function ms(n){return Zt(n,{nestedKey:"models",configId:"model",fromObject:e=>ye(e.currentModelId)??ye(e.currentModel)??ye(e.modelId)??ye(e.model),fromConfig:e=>ye(e.currentValue)})}function Re(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==k.AuthRequired)return n;let s=u=>!!u&&typeof u=="object"&&!Array.isArray(u),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=k.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function Mi(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Ri(n,e,t,s){if(n&&typeof n=="object"&&n.code===k.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${Mi(s.cwd)} && ${[s.command,...s.args].map(Mi).join(" ")})`:"";if(!o&&!a)return n;let d=[i?r:`agent ${t} failed to start: ${r}`];o&&d.push(`stderr: ${o}`),a&&d.push(a);let u=new Error(d.join(`
|
|
126
|
+
`));if(n&&typeof n=="object"){let c=n;typeof c.code=="number"&&(u.code=c.code),c.data!==void 0&&(u.data=c.data)}return u}function It(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function ye(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Pc(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 gs(n){return n.length>0?n:void 0}function hs(n){return Zt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ge(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ge(e.options);return t.length>0?t:void 0}})??[]}function ys(n){return Zt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=ht(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=ht(e.options);return t.length>0?t:void 0}})??[]}function ws(n){return Zt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ye(e.currentModeId)??ye(e.currentMode)??ye(e.modeId)??ye(e.mode),fromConfig:e=>ye(e.currentValue)})}function Tc(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 Ei(n){try{let e=await $e.readFile(S.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
|
|
127
|
+
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function St(n){try{let e=await $e.stat(S.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function tt(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Qt?!1:e?!0:void 0}import{spawn as _c}from"child_process";import*as tn from"fs";import*as Se from"fs/promises";import*as nn from"path";import $c from"pino-roll";var en=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Fc=1e3,Oc=6e4,vs=3e3,nt=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??Fc,this.restartCapMs=r.restartCapMs??Oc;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Se.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 i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},vs);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw At(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw At(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw At(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw At(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw At(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},vs);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 en(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Se.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 i=await Se.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&bs(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+vs;for(;Date.now()<i&&bs(r);)await new Promise(o=>setTimeout(o,50));if(bs(r))try{process.kill(r,"SIGKILL")}catch{}}await Se.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,i=r.command.length>0?r.command:[r.name],o=nn.dirname(this.adapter.paths.logFile(r.name)),a;try{await Se.mkdir(o,{recursive:!0}),a=await $c({file:nn.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",h=>{e.failureReason=`log stream: ${h.message}`})}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})
|
|
128
128
|
`);let d=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=d,e.version=void 0;let u={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[c,...f]=i;if(c===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
|
|
129
|
-
`),a.end();return}let p=Z(c),l=[...f,...r.args].map(Z),g;try{g=
|
|
129
|
+
`),a.end();return}let p=Z(c),l=[...f,...r.args].map(Z),g;try{g=_c(p,l,{env:u,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
|
|
130
130
|
`),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{tn.writeFileSync(this.adapter.paths.pidFile(r.name),`${g.pid}
|
|
131
131
|
`,{encoding:"utf8",mode:384})}catch(h){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
|
|
132
132
|
`)}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}
|
|
133
133
|
`)}),g.on("exit",(h,y)=>{try{tn.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${y??"null"}
|
|
134
134
|
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let v=e.exitWaiters.splice(0);for(let b of v)b();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let w=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof w=="object"){e.failureReason=w.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${w.tripped}
|
|
135
|
-
`);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 bs(n){try{return process.kill(n,0),!0}catch{return!1}}function At(n,e){return n.code=e,n}W();var
|
|
135
|
+
`);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 bs(n){try{return process.kill(n,0),!0}catch{return!1}}function At(n,e){return n.code=e,n}W();var Nc={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:S.extensionsDir,logFile:S.extensionLogFile,pidFile:S.extensionPidFile}},sn=class extends nt{constructor(e,t,s={}){super(e,Nc,t,s)}};W();var Hc={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:S.transformersDir,logFile:S.transformerLogFile,pidFile:S.transformerPidFile}},rn=class extends nt{connected=new Map;constructor(e,t,s={}){super(e,Hc,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 on=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{}}};W();W();import*as Is from"fs/promises";async function _i(n){await Is.writeFile(S.pidFile(),JSON.stringify(n)+`
|
|
136
136
|
`,{encoding:"utf8",mode:384})}W();import*as xt from"fs/promises";import*as an from"path";var Ct=n=>{process.stderr.write(n+`
|
|
137
137
|
`)};function Ss(n){Ct=n??(e=>process.stderr.write(e+`
|
|
138
|
-
`))}async function _i(n,e){let t=pe();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=an.join(S.agentsDir(),t),a;try{a=await xt.readdir(o,{withFileTypes:!0})}catch(d){let u=d;if(u.code==="ENOENT")return;Ct(`hydra-acp: prune: failed to read ${o}: ${u.message}`);return}for(let d of a){if(!d.isDirectory())continue;let u=d.name,c=r.get(u);if(c===void 0)continue;let f=i.get(u)??new Set,p=an.join(o,u),l;try{l=await xt.readdir(p,{withFileTypes:!0})}catch(g){Ct(`hydra-acp: prune: failed to read ${p}: ${g.message}`);continue}for(let g of l){if(!g.isDirectory())continue;let m=g.name;if(m===c||f.has(m)||m.includes(".partial-"))continue;let h=an.join(p,m);try{await xt.rm(h,{recursive:!0,force:!0}),Ct(`hydra-acp: pruned stale ${u} ${m} (${h})`)}catch(y){Ct(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function $i(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let c=await n.registry.load();for(let f of c.agents)await Ln(f)==="yes"&&a.push(f.id)}catch(c){return r("warn",`registry load failed: ${c.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let u=a[d];try{let{synced:c,skipped:f}=await n.manager.syncFromAgent(u);r("info",`${u}: synced ${c.length}, skipped ${f}`)}catch(c){r("warn",`${u}: ${c.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function ks(n){let e=n.maxDeletions??200,t=(l,g)=>{n.logger&&n.logger[l](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(l=>(t("warn",`manager.list failed: ${l.message}`),[])),o=[];for(let l of i){if(l.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(l.interactive!==!1)continue}else if(l.interactive===!0)continue;let m=Date.parse(l.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:l.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((l,g)=>l.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,u=0,c=0;for(let{sessionId:l}of a)try{await n.manager.deleteRecord(l,"expired")&&(u+=1)}catch(g){c+=1,t("warn",`delete ${l} failed: ${g.message}`)}let f=o.length-a.length;if(n.verbose||u>0||c>0){let l=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${u} ${l} session(s) older than ${Hc(n.maxAgeMs)}`+(c>0?`; ${c} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:o.length,deleted:u,failed:c,deferred:f};return d!==void 0&&(p.oldestLastUsedMs=d),p}function Fi(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await ks({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Hc(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 jc}from"crypto";function As(n){if(Array.isArray(n))return n.map(As);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=As(n[t]);return e}return n}function Oi(n){let{tui:e,...t}=n,s=JSON.stringify(As(t));return jc("sha256").update(s).digest("hex").slice(0,16)}W();Te();import*as ji from"path";import{createHash as Bc,randomBytes as Uc,timingSafeEqual as Dc}from"crypto";var Bi="hydra_session_",Lc=3600*24*30,Ni=12,qc=32,zc=50;function Jc(){return ji.join(S.home(),"session-tokens.json")}function Hi(n){return Bc("sha256").update(n).digest("hex")}function Ui(n){return Uc(n).toString("hex")}function Wc(){return Ui(Ni).slice(0,Ni*2)}function Qc(){return`${Bi}${Ui(qc)}`}var dn=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=Jc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(Vc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=Qc(),s=Hi(t),r=Wc(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Lc,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Bi))return;let t=Hi(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!Dc(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},zc))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ce(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 Vc(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 Di="Bearer ",cn=class{constructor(e){this.token=e}token;async validate(e){return Kc(e,this.token)?"service":void 0}},un=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},ln=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 Li(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Di)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Di.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function qi(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var fn=class{tokens=new Map;mint(e,t){let s=Rn();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 Kc(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 pn=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 Es from"fs";import*as po from"os";import*as mo from"path";import*as Ps from"readline";W();function Cs(n){return Math.floor(n/4)}function zi(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=Cs(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}W();import{posix as Gc}from"path";import Yc from"strip-ansi";function Mt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Xc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ae(n){return Yc(n).replace(Xc,"")}function V(n){return ae(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Qi(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 iu(t);case"agent_thought_chunk":case"agent_thought":return ou(t);case"user_message_chunk":return au(t);case"prompt_received":return du(t);case"tool_call":return cu(t,e);case"tool_call_update":return mu(t,e);case"plan":return yu(t);case"current_mode_update":return wu(t);case"current_model_update":return vu(t);case"turn_complete":return bu(t);case"usage_update":return ru(t);case"available_commands_update":return nu(t);case"available_modes_update":return su(t);case"session_info_update":return eu(t);case"config_option_update":return Zc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function Zc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function eu(n){let e=Q(n,"title"),t=e!==void 0?V(e):void 0,s=n._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(r=d),"pendingAgentSwap"in a){let u=a.pendingAgentSwap;typeof u=="string"?i=u:u===null&&(i=null)}}}if(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function tu(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:V(r)};typeof s.description=="string"&&(i.description=V(s.description)),e.push(i)}return e}function nu(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:tu(e)}:null}function su(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:V(r.id)};typeof r.name=="string"&&(i.name=V(r.name)),typeof r.description=="string"&&(i.description=V(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function ru(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 iu(n){let e=Rt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Mt(n)}}function ou(n){let e=typeof n.text=="string"?ae(n.text):Rt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Mt(n)}}function au(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=Rt(n.content);return t===null?null:{kind:"user-text",text:t}}function du(n){let e=Iu(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Vi(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Ji(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 mn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Ji(r.oldText),o=Ji(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Ki(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:ae(t)}function cu(n,e={}){let t=Q(n,"toolCallId")??Q(n,"id");if(!t)return null;let s=Q(n,"title")??Q(n,"name")??Q(n,"label")??"tool call",r=Q(n,"name")??Q(n,"title");if(Vi(r)){let g=Ki(n);if(g!==null){let m=Q(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=Xi(V(s),n,e),o=Q(n,"status"),a=Q(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let u=mn(n);u!==null&&(d.editDiff=u);let c=Yi(n);c!==void 0&&(d.detail=c);let f=xs(n);f!==void 0&&(d.detailFull=f);let p=Gi(n);p!==void 0&&(d.locations=p);let l=Mt(n);return l!==void 0&&(d.workerTaskId=l),d}function Gi(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Wi=64;function Yi(n){let e=xs(n);if(e===void 0)return;let t=V(e),s=n.rawInput;return s&&typeof s.command=="string"?fu(t,Wi):pu(t,Wi)}function xs(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 ae(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 Pe(V(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 Pe(V(s))}}}var uu=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function lu(n){for(let e of uu)if(n.startsWith(e))return!0;return!1}function Xi(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Pe(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Pe(o)}return lu(n)?Pe(`/${n}`):t.cwd&&t.cwd.length>0?Pe(Gc.resolve(t.cwd,n)):n}function fu(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function pu(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 mu(n,e={}){let t=Q(n,"toolCallId")??Q(n,"id");if(!t)return null;let s=Q(n,"title"),r=s!==void 0?Xi(V(s),n,e):void 0,i=Q(n,"status"),o=mn(n),a=Yi(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let u=Q(n,"name")??s;if(Vi(u)){let g={kind:"exit-plan-mode",toolCallId:t},m=Ki(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let c={kind:"tool-call-update",toolCallId:t};r!==void 0&&(c.title=r),a!==void 0&&(c.detail=a);let f=xs(n);f!==void 0&&(c.detailFull=f);let p=Gi(n);if(p!==void 0&&(c.locations=p),i!==void 0&&(c.status=i),o!==null&&(c.editDiff=o),i==="failed"){let g=gu(n);g!==null&&(c.errorText=g),hu(n,g)&&(c.upstreamInterrupted=!0)}let l=Mt(n);return l!==void 0&&(c.workerTaskId=l),c}function gu(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Rt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ae(s)}return null}function hu(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 yu(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?V(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function wu(n){let e=Q(n,"currentModeId")??Q(n,"currentMode")??Q(n,"mode");return e?{kind:"mode-changed",mode:V(e)}:null}function vu(n){let e=Q(n,"currentModel")??Q(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:V(e),...s&&s.length>0?{availableModels:s}:{}}}function bu(n){let e=Q(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 Rt(n){if(typeof n=="string")return ae(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ae(e.text):null}function Iu(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=Rt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Q(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Zi(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,u=ku(o);if(u.length===0)continue;let c=u;if(d!==void 0){let f=e.get(d)??[],p=[];for(let l of u)f.some(g=>g.path===l.path&&g.oldText===l.oldText&&g.newText===l.newText)||p.push(l);if(p.length===0)continue;e.set(d,[...f,...p]),c=p}for(let f of c)Su(t,f)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function eo(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Su(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 ku(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let u=d,c=typeof u.old_string=="string"?u.old_string:void 0,f=typeof u.new_string=="string"?u.new_string:void 0;c===void 0||f===void 0||e.push({path:o,oldText:c,newText:f})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",u=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:u})}if(e.length>0)return e}let r=mn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function no(n,e={}){let t=Au(n),s=Cu(t),r=[];xu(r,n),Mu(r,t,s,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let i=r.join(`
|
|
138
|
+
`))}async function $i(n,e){let t=pe();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=an.join(S.agentsDir(),t),a;try{a=await xt.readdir(o,{withFileTypes:!0})}catch(d){let u=d;if(u.code==="ENOENT")return;Ct(`hydra-acp: prune: failed to read ${o}: ${u.message}`);return}for(let d of a){if(!d.isDirectory())continue;let u=d.name,c=r.get(u);if(c===void 0)continue;let f=i.get(u)??new Set,p=an.join(o,u),l;try{l=await xt.readdir(p,{withFileTypes:!0})}catch(g){Ct(`hydra-acp: prune: failed to read ${p}: ${g.message}`);continue}for(let g of l){if(!g.isDirectory())continue;let m=g.name;if(m===c||f.has(m)||m.includes(".partial-"))continue;let h=an.join(p,m);try{await xt.rm(h,{recursive:!0,force:!0}),Ct(`hydra-acp: pruned stale ${u} ${m} (${h})`)}catch(y){Ct(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function Fi(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let c=await n.registry.load();for(let f of c.agents)await Ln(f)==="yes"&&a.push(f.id)}catch(c){return r("warn",`registry load failed: ${c.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let u=a[d];try{let{synced:c,skipped:f}=await n.manager.syncFromAgent(u);r("info",`${u}: synced ${c.length}, skipped ${f}`)}catch(c){r("warn",`${u}: ${c.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function ks(n){let e=n.maxDeletions??200,t=(l,g)=>{n.logger&&n.logger[l](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(l=>(t("warn",`manager.list failed: ${l.message}`),[])),o=[];for(let l of i){if(l.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(l.interactive!==!1)continue}else if(l.interactive===!0)continue;let m=Date.parse(l.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:l.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((l,g)=>l.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,u=0,c=0;for(let{sessionId:l}of a)try{await n.manager.deleteRecord(l,"expired")&&(u+=1)}catch(g){c+=1,t("warn",`delete ${l} failed: ${g.message}`)}let f=o.length-a.length;if(n.verbose||u>0||c>0){let l=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${u} ${l} session(s) older than ${jc(n.maxAgeMs)}`+(c>0?`; ${c} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:o.length,deleted:u,failed:c,deferred:f};return d!==void 0&&(p.oldestLastUsedMs=d),p}function Oi(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await ks({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function jc(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 Bc}from"crypto";function As(n){if(Array.isArray(n))return n.map(As);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=As(n[t]);return e}return n}function Ni(n){let{tui:e,...t}=n,s=JSON.stringify(As(t));return Bc("sha256").update(s).digest("hex").slice(0,16)}W();Te();import*as Bi from"path";import{createHash as Uc,randomBytes as Dc,timingSafeEqual as Lc}from"crypto";var Ui="hydra_session_",qc=3600*24*30,Hi=12,zc=32,Jc=50;function Wc(){return Bi.join(S.home(),"session-tokens.json")}function ji(n){return Uc("sha256").update(n).digest("hex")}function Di(n){return Dc(n).toString("hex")}function Qc(){return Di(Hi).slice(0,Hi*2)}function Vc(){return`${Ui}${Di(zc)}`}var dn=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=Wc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(Kc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=Vc(),s=ji(t),r=Qc(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:qc,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Ui))return;let t=ji(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!Lc(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},Jc))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ce(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 Kc(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 Li="Bearer ",cn=class{constructor(e){this.token=e}token;async validate(e){return Gc(e,this.token)?"service":void 0}},un=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},ln=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 qi(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Li)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Li.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function zi(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var fn=class{tokens=new Map;mint(e,t){let s=Rn();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 pn=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 Es from"fs";import*as mo from"os";import*as go from"path";import*as Ps from"readline";W();function Cs(n){return Math.floor(n/4)}function Ji(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=Cs(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}W();import{posix as Yc}from"path";import Xc from"strip-ansi";function Mt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Zc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ae(n){return Xc(n).replace(Zc,"")}function V(n){return ae(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Vi(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 ou(t);case"agent_thought_chunk":case"agent_thought":return au(t);case"user_message_chunk":return du(t);case"prompt_received":return cu(t);case"tool_call":return uu(t,e);case"tool_call_update":return gu(t,e);case"plan":return wu(t);case"current_mode_update":return vu(t);case"current_model_update":return bu(t);case"turn_complete":return Iu(t);case"usage_update":return iu(t);case"available_commands_update":return su(t);case"available_modes_update":return ru(t);case"session_info_update":return tu(t);case"config_option_update":return eu(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function eu(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function tu(n){let e=Q(n,"title"),t=e!==void 0?V(e):void 0,s=n._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(r=d),"pendingAgentSwap"in a){let u=a.pendingAgentSwap;typeof u=="string"?i=u:u===null&&(i=null)}}}if(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function nu(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:V(r)};typeof s.description=="string"&&(i.description=V(s.description)),e.push(i)}return e}function su(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:nu(e)}:null}function ru(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:V(r.id)};typeof r.name=="string"&&(i.name=V(r.name)),typeof r.description=="string"&&(i.description=V(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function iu(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 ou(n){let e=Rt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Mt(n)}}function au(n){let e=typeof n.text=="string"?ae(n.text):Rt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Mt(n)}}function du(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=Rt(n.content);return t===null?null:{kind:"user-text",text:t}}function cu(n){let e=Su(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Ki(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Wi(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 mn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Wi(r.oldText),o=Wi(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Gi(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:ae(t)}function uu(n,e={}){let t=Q(n,"toolCallId")??Q(n,"id");if(!t)return null;let s=Q(n,"title")??Q(n,"name")??Q(n,"label")??"tool call",r=Q(n,"name")??Q(n,"title");if(Ki(r)){let g=Gi(n);if(g!==null){let m=Q(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=Zi(V(s),n,e),o=Q(n,"status"),a=Q(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let u=mn(n);u!==null&&(d.editDiff=u);let c=Xi(n);c!==void 0&&(d.detail=c);let f=xs(n);f!==void 0&&(d.detailFull=f);let p=Yi(n);p!==void 0&&(d.locations=p);let l=Mt(n);return l!==void 0&&(d.workerTaskId=l),d}function Yi(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Qi=64;function Xi(n){let e=xs(n);if(e===void 0)return;let t=V(e),s=n.rawInput;return s&&typeof s.command=="string"?pu(t,Qi):mu(t,Qi)}function xs(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 ae(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 Pe(V(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 Pe(V(s))}}}var lu=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function fu(n){for(let e of lu)if(n.startsWith(e))return!0;return!1}function Zi(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Pe(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Pe(o)}return fu(n)?Pe(`/${n}`):t.cwd&&t.cwd.length>0?Pe(Yc.resolve(t.cwd,n)):n}function pu(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function mu(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 gu(n,e={}){let t=Q(n,"toolCallId")??Q(n,"id");if(!t)return null;let s=Q(n,"title"),r=s!==void 0?Zi(V(s),n,e):void 0,i=Q(n,"status"),o=mn(n),a=Xi(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let u=Q(n,"name")??s;if(Ki(u)){let g={kind:"exit-plan-mode",toolCallId:t},m=Gi(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let c={kind:"tool-call-update",toolCallId:t};r!==void 0&&(c.title=r),a!==void 0&&(c.detail=a);let f=xs(n);f!==void 0&&(c.detailFull=f);let p=Yi(n);if(p!==void 0&&(c.locations=p),i!==void 0&&(c.status=i),o!==null&&(c.editDiff=o),i==="failed"){let g=hu(n);g!==null&&(c.errorText=g),yu(n,g)&&(c.upstreamInterrupted=!0)}let l=Mt(n);return l!==void 0&&(c.workerTaskId=l),c}function hu(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Rt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ae(s)}return null}function yu(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 wu(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?V(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function vu(n){let e=Q(n,"currentModeId")??Q(n,"currentMode")??Q(n,"mode");return e?{kind:"mode-changed",mode:V(e)}:null}function bu(n){let e=Q(n,"currentModel")??Q(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:V(e),...s&&s.length>0?{availableModels:s}:{}}}function Iu(n){let e=Q(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 Rt(n){if(typeof n=="string")return ae(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ae(e.text):null}function Su(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=Rt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Q(n,e){let t=n[e];return typeof t=="string"?t:void 0}function eo(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,u=Au(o);if(u.length===0)continue;let c=u;if(d!==void 0){let f=e.get(d)??[],p=[];for(let l of u)f.some(g=>g.path===l.path&&g.oldText===l.oldText&&g.newText===l.newText)||p.push(l);if(p.length===0)continue;e.set(d,[...f,...p]),c=p}for(let f of c)ku(t,f)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function to(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function ku(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 Au(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let u=d,c=typeof u.old_string=="string"?u.old_string:void 0,f=typeof u.new_string=="string"?u.new_string:void 0;c===void 0||f===void 0||e.push({path:o,oldText:c,newText:f})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",u=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:u})}if(e.length>0)return e}let r=mn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function so(n,e={}){let t=Cu(n),s=xu(t),r=[];Mu(r,n),Ru(r,t,s,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let i=r.join(`
|
|
139
139
|
`);return i.endsWith(`
|
|
140
140
|
`)||(i+=`
|
|
141
|
-
`),i}function
|
|
142
|
-
`)),n.push("")}function
|
|
143
|
-
`);for(let a=0;a<o.length;a++){let d=o[a],u=st(d);n.push(a===0&&a===o.length-1?`${t}${u}${t}`:a===0?`${t}${u}`:a===o.length-1?`${u}${t}`:u)}r<s.length-1&&n.push("")}}function st(n){return n.replace(/</g,"<").replace(/>/g,">")}function Ms(n){return n.toLocaleString("en-US")}function so(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Tu(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let c of s){let f=c.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:d.push(c)}o?i="AND":a&&(i="OR");let u=d.map(c=>_u(c)).filter(c=>c.term.length>0);return{operator:i,terms:u}}function _u(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ro(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:ro(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ro(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function $u(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Fu=5,Ou=200,io=30;async function co(n,e,t={}){let s=Tu(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Fu,i=t.maxSessions??Ou,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(f=>o.has(f.sessionId)):a,u=[],c=!1;for(let f of d){if(u.length>=i){c=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),l=Nu(p,s,r);if(l.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:l.totalMatches,snippets:l.snippets};f.title!==void 0&&(g.title=f.title),u.push(g)}return{query:e,truncated:c,results:u}}function Nu(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Hu(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Hu(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=ju(a).filter(u=>$u(t,u.kind));for(let u of d){let c=u.text.toLowerCase(),f=c.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=c.indexOf(r,f+r.length);if(i+=p,o.length<s){let l=c.indexOf(r),g={kind:u.kind,text:qu(u.text,l,r.length),recordedAt:a.recordedAt};u.toolName!==void 0&&(g.toolName=u.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function ju(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=gn(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ae(s.text):gn(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Du(s))return[];let i=gn(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Lu(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Bu(s);default:return[]}}function Bu(n){let e=oo(n,"name"),t=oo(n,"title"),s=[];if(t!==void 0){let a=V(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=V(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=ao(r);if(a.length>0){let d={kind:"tool-input",text:V(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=ao(i);if(a.length>0){let d={kind:"tool-input",text:V(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=Uu(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Uu(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=V(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=V(s);if(r.length>0)return r}}return null}function Du(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 gn(n){if(typeof n=="string")return ae(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ae(e.text):""}function Lu(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=gn(t);s.length>0&&e.push(s)}return e.join("")}function oo(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ao(n){try{return JSON.stringify(n)}catch{return""}}function qu(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-io),d=Math.min(s.length,o+i.length+io),u=a>0?"\u2026":"",c=d<s.length?"\u2026":"";return`${u}${s.slice(a,d)}${c}`}import{randomBytes as lo}from"crypto";function uo(n){let e=lo(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 Rs(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(uo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(uo({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=rt(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function rt(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=lo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var hn=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function fo(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!so(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function go(n,e,t,s={}){n.get("/v1/sessions",async u=>{let c=u.query,f=c?.includeNonInteractive==="1"||c?.includeNonInteractive==="true";return{sessions:await e.list({cwd:c?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.getOne(p);return l||(c.code(404).send({error:"session not found"}),c)}),n.post("/v1/sessions/search",async(u,c)=>{let f=u.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return c.code(400).send({error:"q is required"}),c;let l=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await co(e,p,{sessionIds:l})}),n.post("/v1/sessions",async(u,c)=>{let f=u.body??{},p=Z(f.cwd??t.cwd),l=f.agentId??t.agentId,g=rt(s),m=g!==void 0?[...f.mcpServers??[],...g.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:l,mcpServers:m});g!==void 0&&g.bindToSession(h),c.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),c.code(500).send({error:h.message})}}),n.post("/v1/sessions/collect",async(u,c)=>{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,g=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await ks({manager:e,maxAgeMs:p,maxDeletions:l,selection:g,verbose:!1});c.code(200).send(m)}catch(m){c.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){l.close({deleteRecord:!1}).catch(()=>{}),c.code(202).send();return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return c.code(404).send({error:"session not found"}),c;let g=u.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=>mo.join(po.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return l.openStream(m)}catch(h){return c.code(409).send({error:h.message}),c}}),n.post("/v1/sessions/:id/stdin",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return c.code(404).send({error:"session not found"}),c;let g=u.body??{},m=typeof g.chunk=="string"?g.chunk:"",h=g.eof===!0;try{return l.streamWrite(m,h)}catch(y){return c.code(409).send({error:y.message}),c}}),n.patch("/v1/sessions/:id",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{};if(l.priority!==void 0){let m=l.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{c.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,h)){c.code(404).send({error:"session not found"});return}c.code(204).send();return}if(l.regen===!0){if(!(e.get(p)!==void 0||await e.hasRecord(p))){c.code(404).send({error:"session not found"});return}e.scheduleSynopsis(p),c.code(202).send();return}if(typeof l.title!="string"||l.title.trim().length===0){c.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,l.title)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.delete("/v1/sessions/:id",async(u,c)=>{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),c.code(204).send();return}if(!await e.deleteRecord(p)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.get("/v1/sessions/:id/export",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.query?.tools,g=l==="references"?"references":mi(l),m=await e.exportBundle(p,g==="references"?{tools:"references"}:{});if(!m){c.code(404).send({error:"session not found"});return}let h=bt({record:m.record,history:g==="summary"?gi(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:Y,machine:pt(),hydraHost:fo(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");c.header("Content-Disposition",`attachment; filename="${p}-${y}.hydra"`),c.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){c.code(404).send({error:"session not found"});return}let g=u.query??{},m=g.fold==="true"||g.fold==="1",h=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,y=Zi(l.history);h&&(y=y.filter(v=>h.has(v.path))),m&&(y=y.map(v=>({...v,hunks:eo(v.hunks)}))),c.code(200).send(y)}),n.get("/v1/sessions/:id/tools/:hash",async(u,c)=>{let f=u.params,p=await e.resolveCanonicalId(f.id)??f.id,l=await e.loadToolBlob(p,f.hash);if(l===null){c.code(404).send({error:"tool blob not found"});return}c.header("Content-Type","text/plain; charset=utf-8"),c.code(200).send(l)}),n.get("/v1/sessions/:id/transcript",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){c.code(404).send({error:"session not found"});return}let g=bt({record:l.record,history:l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,hydraVersion:Y,machine:pt(),hydraHost:fo(t)}),m=u.query,h=y=>y==="1"||y==="true"||y==="yes";c.header("Content-Type","text/markdown; charset=utf-8"),c.code(200).send(no(g,{includeTools:h(m?.tools),includeThoughts:h(m?.thoughts)}))}),n.post("/v1/sessions/:id/fork",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{},g={};if(l.forkAt!==void 0){if(typeof l.forkAt!="string"||l.forkAt.length===0){c.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=l.forkAt}if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){c.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=Z(l.cwd)}if(l.agentId!==void 0){if(typeof l.agentId!="string"||l.agentId.length===0){c.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=l.agentId}if(l.title!==void 0){if(typeof l.title!="string"){c.code(400).send({error:"title must be a string"});return}g.title=l.title}if(l.mode!==void 0){if(l.mode!=="verbatim"&&l.mode!=="synthesis"){c.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=l.mode}if(l.model!==void 0){if(typeof l.model!="string"||l.model.length===0){c.code(400).send({error:"model must be a non-empty string"});return}g.model=l.model}try{let m=await e.forkSession(p,g);c.code(201).send(m)}catch(m){let h=m;if(h.code===k.SessionNotFound){c.code(404).send({error:h.message});return}if(h.code===k.InvalidParams||h.code===k.AgentNotInstalled){c.code(400).send({error:h.message});return}c.code(500).send({error:h.message})}}),n.post("/v1/sessions/import",async(u,c)=>{let f=u.body??{};if(f.bundle===void 0){c.code(400).send({error:"missing bundle"});return}let p;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){c.code(400).send({error:"cwd must be a non-empty string"});return}p=f.cwd}let l;try{l=ki(f.bundle)}catch(g){c.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(l,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});c.code(201).send(g)}catch(g){let m=g;if(m.code===k.BundleAlreadyImported){c.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}c.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p),g;if(l?g=l.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(p),g===void 0&&!await e.hasRecord(p))return c.code(404).send({error:"session not found"}),c;let m=await e.getCompactionState(p),h=await e.getRollbackBreadcrumb(p),y=!1,v,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=g??0,C=b.length,T=b.slice(A).reduce((P,B)=>P+JSON.stringify(B.params).length,0);v=Cs(T);let _=l?.currentModel,U=b.at(-1).recordedAt,$=l?.currentUsage;y=zi({summarizedThroughEntry:A,totalEntries:C,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(e.get(p)){e.scheduleCompaction(p),c.code(202).send({scheduled:!0});return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}e.scheduleCompaction(p),c.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}try{await e.performUncompact(p),c.code(202).send({rolledBack:!0})}catch(l){let g=l instanceof Error?l.message:String(l);c.code(409).send({error:g})}}),n.get("/v1/sessions/:id/history",async(u,c)=>{let f=u.params.id,p=u.query,l=p?.follow==="1"||p?.follow==="true",g=await e.resolveCanonicalId(f)??f,m=e.get(g),h,y,v=!1,w=1e4,b=[];if(m){l&&(y=m.onBroadcast(C=>{c.raw.writableEnded||(v?c.raw.write(JSON.stringify(C)+`
|
|
141
|
+
`),i}function Cu(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=Vi(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function xu(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 Mu(n,e){let t=e.session,s=Vr(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${st(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let u=a.size!==void 0?`${Ms(a.size)}`:void 0;d.push(u?`${Ms(a.used)} / ${u} tokens`:`${Ms(a.used)} tokens`)}if(a.costAmount!==void 0){let u=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${u}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
|
|
142
|
+
`)),n.push("")}function Ru(n,e,t,s){let{includeTools:r,includeThoughts:i}=s;if(!e.some(m=>Eu(m.event,i))){n.push("_No conversation history recorded._"),n.push("");return}let o=0,a="",d="",u=[],c=new Set,f=!1,p=()=>{if(u.length!==0){for(let m of u)n.push(m);n.push(""),u=[]}},l=()=>{p(),d.length>0&&(no(n,d.trimEnd(),"*"),n.push(""),d=""),a.length!==0&&(n.push(a.trimEnd()),n.push(""),a="")},g=()=>{f||(f=!0)};for(let{event:m}of e)switch(m.kind){case"user-text":{l(),n.push("---"),n.push(""),o+=1,no(n,m.text,"**"),n.push(""),f=!0;break}case"agent-text":g(),a+=m.text;break;case"agent-thought":{if(!i)break;g(),a.length>0&&(n.push(a.trimEnd()),n.push(""),a=""),d+=m.text;break}case"tool-call":{if(!r||(g(),(a.length>0||d.length>0)&&l(),c.has(m.toolCallId)))break;c.add(m.toolCallId);let h=t.get(m.toolCallId)??{title:m.title,status:m.status??"pending"};u.push(`- ${Tu(h.status)} ${Pu(h)}`);break}case"tool-call-update":break;case"plan":{g(),l(),n.push("**Plan:**"),n.push("");for(let h of m.entries){let y=h.status==="completed"?"[x]":"[ ]";n.push(`- ${y} ${st(h.content)}`)}n.push("");break}case"mode-changed":g(),l(),n.push(`_mode: ${st(m.mode)}_`),n.push("");break;case"model-changed":g(),l(),n.push(`_model: ${st(m.model)}_`),n.push("");break;case"turn-complete":l();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}l()}function Eu(n,e){switch(n.kind){case"agent-thought":return e;case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Pu(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${st(n.title)}${t}`}function Tu(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 no(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
|
|
143
|
+
`);for(let a=0;a<o.length;a++){let d=o[a],u=st(d);n.push(a===0&&a===o.length-1?`${t}${u}${t}`:a===0?`${t}${u}`:a===o.length-1?`${u}${t}`:u)}r<s.length-1&&n.push("")}}function st(n){return n.replace(/</g,"<").replace(/>/g,">")}function Ms(n){return n.toLocaleString("en-US")}function ro(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function _u(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let c of s){let f=c.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:d.push(c)}o?i="AND":a&&(i="OR");let u=d.map(c=>$u(c)).filter(c=>c.term.length>0);return{operator:i,terms:u}}function $u(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:io(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:io(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function io(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Fu(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Ou=5,Nu=200,oo=30;async function uo(n,e,t={}){let s=_u(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Ou,i=t.maxSessions??Nu,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(f=>o.has(f.sessionId)):a,u=[],c=!1;for(let f of d){if(u.length>=i){c=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),l=Hu(p,s,r);if(l.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:l.totalMatches,snippets:l.snippets};f.title!==void 0&&(g.title=f.title),u.push(g)}return{query:e,truncated:c,results:u}}function Hu(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=ju(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function ju(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Bu(a).filter(u=>Fu(t,u.kind));for(let u of d){let c=u.text.toLowerCase(),f=c.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=c.indexOf(r,f+r.length);if(i+=p,o.length<s){let l=c.indexOf(r),g={kind:u.kind,text:zu(u.text,l,r.length),recordedAt:a.recordedAt};u.toolName!==void 0&&(g.toolName=u.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function Bu(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=gn(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ae(s.text):gn(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Lu(s))return[];let i=gn(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=qu(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Uu(s);default:return[]}}function Uu(n){let e=ao(n,"name"),t=ao(n,"title"),s=[];if(t!==void 0){let a=V(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=V(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=co(r);if(a.length>0){let d={kind:"tool-input",text:V(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=co(i);if(a.length>0){let d={kind:"tool-input",text:V(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=Du(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Du(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=V(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=V(s);if(r.length>0)return r}}return null}function Lu(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 gn(n){if(typeof n=="string")return ae(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ae(e.text):""}function qu(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=gn(t);s.length>0&&e.push(s)}return e.join("")}function ao(n,e){let t=n[e];return typeof t=="string"?t:void 0}function co(n){try{return JSON.stringify(n)}catch{return""}}function zu(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-oo),d=Math.min(s.length,o+i.length+oo),u=a>0?"\u2026":"",c=d<s.length?"\u2026":"";return`${u}${s.slice(a,d)}${c}`}import{randomBytes as fo}from"crypto";function lo(n){let e=fo(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 Rs(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(lo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(lo({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=rt(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function rt(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=fo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var hn=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function po(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ro(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ho(n,e,t,s={}){n.get("/v1/sessions",async u=>{let c=u.query,f=c?.includeNonInteractive==="1"||c?.includeNonInteractive==="true";return{sessions:await e.list({cwd:c?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.getOne(p);return l||(c.code(404).send({error:"session not found"}),c)}),n.post("/v1/sessions/search",async(u,c)=>{let f=u.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return c.code(400).send({error:"q is required"}),c;let l=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await uo(e,p,{sessionIds:l})}),n.post("/v1/sessions",async(u,c)=>{let f=u.body??{},p=Z(f.cwd??t.cwd),l=f.agentId??t.agentId,g=rt(s),m=g!==void 0?[...f.mcpServers??[],...g.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:l,mcpServers:m});g!==void 0&&g.bindToSession(h),c.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),c.code(500).send({error:h.message})}}),n.post("/v1/sessions/collect",async(u,c)=>{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,g=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await ks({manager:e,maxAgeMs:p,maxDeletions:l,selection:g,verbose:!1});c.code(200).send(m)}catch(m){c.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){l.close({deleteRecord:!1}).catch(()=>{}),c.code(202).send();return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return c.code(404).send({error:"session not found"}),c;let g=u.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=>go.join(mo.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return l.openStream(m)}catch(h){return c.code(409).send({error:h.message}),c}}),n.post("/v1/sessions/:id/stdin",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return c.code(404).send({error:"session not found"}),c;let g=u.body??{},m=typeof g.chunk=="string"?g.chunk:"",h=g.eof===!0;try{return l.streamWrite(m,h)}catch(y){return c.code(409).send({error:y.message}),c}}),n.patch("/v1/sessions/:id",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{};if(l.priority!==void 0){let m=l.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{c.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,h)){c.code(404).send({error:"session not found"});return}c.code(204).send();return}if(l.regen===!0){if(!(e.get(p)!==void 0||await e.hasRecord(p))){c.code(404).send({error:"session not found"});return}e.scheduleSynopsis(p),c.code(202).send();return}if(typeof l.title!="string"||l.title.trim().length===0){c.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,l.title)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.delete("/v1/sessions/:id",async(u,c)=>{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),c.code(204).send();return}if(!await e.deleteRecord(p)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),n.get("/v1/sessions/:id/export",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.query?.tools,g=l==="references"?"references":gi(l),m=await e.exportBundle(p,g==="references"?{tools:"references"}:{});if(!m){c.code(404).send({error:"session not found"});return}let h=bt({record:m.record,history:g==="summary"?hi(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:Y,machine:pt(),hydraHost:po(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");c.header("Content-Disposition",`attachment; filename="${p}-${y}.hydra"`),c.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){c.code(404).send({error:"session not found"});return}let g=u.query??{},m=g.fold==="true"||g.fold==="1",h=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,y=eo(l.history);h&&(y=y.filter(v=>h.has(v.path))),m&&(y=y.map(v=>({...v,hunks:to(v.hunks)}))),c.code(200).send(y)}),n.get("/v1/sessions/:id/tools/:hash",async(u,c)=>{let f=u.params,p=await e.resolveCanonicalId(f.id)??f.id,l=await e.loadToolBlob(p,f.hash);if(l===null){c.code(404).send({error:"tool blob not found"});return}c.header("Content-Type","text/plain; charset=utf-8"),c.code(200).send(l)}),n.get("/v1/sessions/:id/transcript",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){c.code(404).send({error:"session not found"});return}let g=bt({record:l.record,history:l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,hydraVersion:Y,machine:pt(),hydraHost:po(t)}),m=u.query,h=y=>y==="1"||y==="true"||y==="yes";c.header("Content-Type","text/markdown; charset=utf-8"),c.code(200).send(so(g,{includeTools:h(m?.tools),includeThoughts:h(m?.thoughts)}))}),n.post("/v1/sessions/:id/fork",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{},g={};if(l.forkAt!==void 0){if(typeof l.forkAt!="string"||l.forkAt.length===0){c.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=l.forkAt}if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){c.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=Z(l.cwd)}if(l.agentId!==void 0){if(typeof l.agentId!="string"||l.agentId.length===0){c.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=l.agentId}if(l.title!==void 0){if(typeof l.title!="string"){c.code(400).send({error:"title must be a string"});return}g.title=l.title}if(l.mode!==void 0){if(l.mode!=="verbatim"&&l.mode!=="synthesis"){c.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=l.mode}if(l.model!==void 0){if(typeof l.model!="string"||l.model.length===0){c.code(400).send({error:"model must be a non-empty string"});return}g.model=l.model}try{let m=await e.forkSession(p,g);c.code(201).send(m)}catch(m){let h=m;if(h.code===k.SessionNotFound){c.code(404).send({error:h.message});return}if(h.code===k.InvalidParams||h.code===k.AgentNotInstalled){c.code(400).send({error:h.message});return}c.code(500).send({error:h.message})}}),n.post("/v1/sessions/import",async(u,c)=>{let f=u.body??{};if(f.bundle===void 0){c.code(400).send({error:"missing bundle"});return}let p;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){c.code(400).send({error:"cwd must be a non-empty string"});return}p=f.cwd}let l;try{l=Ai(f.bundle)}catch(g){c.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(l,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});c.code(201).send(g)}catch(g){let m=g;if(m.code===k.BundleAlreadyImported){c.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}c.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p),g;if(l?g=l.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(p),g===void 0&&!await e.hasRecord(p))return c.code(404).send({error:"session not found"}),c;let m=await e.getCompactionState(p),h=await e.getRollbackBreadcrumb(p),y=!1,v,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=g??0,C=b.length,T=b.slice(A).reduce((P,B)=>P+JSON.stringify(B.params).length,0);v=Cs(T);let _=l?.currentModel,U=b.at(-1).recordedAt,$=l?.currentUsage;y=Ji({summarizedThroughEntry:A,totalEntries:C,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(e.get(p)){e.scheduleCompaction(p),c.code(202).send({scheduled:!0});return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}e.scheduleCompaction(p),c.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}try{await e.performUncompact(p),c.code(202).send({rolledBack:!0})}catch(l){let g=l instanceof Error?l.message:String(l);c.code(409).send({error:g})}}),n.get("/v1/sessions/:id/history",async(u,c)=>{let f=u.params.id,p=u.query,l=p?.follow==="1"||p?.follow==="true",g=await e.resolveCanonicalId(f)??f,m=e.get(g),h,y,v=!1,w=1e4,b=[];if(m){l&&(y=m.onBroadcast(C=>{c.raw.writableEnded||(v?c.raw.write(JSON.stringify(C)+`
|
|
144
144
|
`):(b.push(C),b.length>w&&b.shift()))})),u.raw.on("close",()=>{y?.(),c.raw.writableEnded||c.raw.end()});try{h=await m.getHistorySnapshot()}catch(C){throw y?.(),C}}else{let C=await e.getHistory(g);if(C===void 0)return c.code(404).send({error:"session not found"}),c;h=C}c.raw.setHeader("Content-Type","application/x-ndjson"),c.raw.setHeader("Cache-Control","no-cache"),c.raw.statusCode=200;let A=new Set;for(let C of h??[]){c.raw.write(JSON.stringify(C)+`
|
|
145
145
|
`);let x=C;typeof x.recordedAt=="number"&&A.add(String(x.recordedAt))}for(;b.length>0;){let C=b.splice(0,b.length);for(let x of C){let T=x,_=typeof T.recordedAt=="number"?String(T.recordedAt):"";_&&A.has(_)||c.raw.write(JSON.stringify(x)+`
|
|
146
146
|
`)}}return v=!0,y||c.raw.end(),c});function r(u,c,f){let p=typeof u=="string"?u.trim():"";if(p.length===0)return null;let l;try{l=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!l||typeof l!="object"||Array.isArray(l))return console.debug("events endpoint: skipping non-object JSONL line"),null;let g=l;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 y=m.update.sessionUpdate;return typeof y!="string"||!c.has(y)?null:{recordedAt:g.recordedAt,entry:l}}function i(u,c,f){let l=c.params.update,g={sessionId:u,ts:new Date(c.recordedAt).toISOString(),kind:f,update:l};return l.messageId!==void 0&&l.messageId!==null&&(g.messageId=l.messageId),g}async function*o(u,c,f,p){for await(let l of c){let g=r(l,f,p);if(g){let m=g.entry.params.update.sessionUpdate;yield{ts:g.recordedAt,row:i(u,g.entry,m)}}}}async function a(u,c,f,p){let l=Ps.createInterface({input:Es.createReadStream(c),crlfDelay:1/0}),g=o(u,l,f,p),m=await g.next(),h=m.done?null:m.value;return{sessionId:u,rl:l,gen:g,current:h,exhausted:h===null}}async function d(u){let c=await u.gen.next();c.done?(u.exhausted=!0,u.current=null):u.current=c.value}n.get("/v1/sessions/events",async(u,c)=>{let f=u.query,p=f.kinds;if(!p||p.trim().length===0)return c.code(400).send({error:"kinds parameter is required"}),c;let l=p.split(",").map(w=>w.trim());if(l.length===0)return c.code(400).send({error:"kinds parameter is required"}),c;for(let w of l)if(!hn.has(w))return c.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...hn].join(", ")}`}),c;let g=new Set(l),m;if(f.since!==void 0&&f.since.trim().length>0){let w=new Date(f.since);if(isNaN(w.getTime()))return c.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),c;m=w.getTime()}let h=await e.list({includeNonInteractive:!0}),y=m!==void 0?h.filter(w=>new Date(w.updatedAt).getTime()>=m):h;c.raw.setHeader("content-type","application/x-ndjson"),c.raw.statusCode=200;let v=[];for(let w of y)try{let b=S.historyFile(w.sessionId),A=await a(w.sessionId,b,g,m);A.exhausted||v.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}u.raw.on("close",()=>{for(let w of v)try{w.rl.close()}catch{}c.raw.writableEnded||c.raw.end()});try{for(;v.length>0;){let w=-1,b=1/0;for(let C=0;C<v.length;C++){let x=v[C];x.current!==null&&x.current.ts<b&&(b=x.current.ts,w=C)}if(w===-1)break;let A=v[w];if(c.raw.write(JSON.stringify(A.current.row)+`
|
|
147
147
|
`),await d(A),A.exhausted){try{A.rl.close()}catch{}v.splice(w,1)}}}catch(w){for(let b of v)try{b.rl.close()}catch{}throw w}return c.raw.end(),c}),n.get("/v1/sessions/:id/events",async(u,c)=>{let f=u.params.id,p=u.query,l=await e.resolveCanonicalId(f)??f;if(!e.get(l)&&!await e.hasRecord(l))return c.code(404).send({error:"session not found"}),c;let m=p.kinds;if(!m||m.trim().length===0)return c.code(400).send({error:"kinds parameter is required"}),c;let h=m.split(",").map(C=>C.trim());if(h.length===0)return c.code(400).send({error:"kinds parameter is required"}),c;for(let C of h)if(!hn.has(C))return c.code(400).send({error:`kind "${C}" is not queryable; allowed kinds: ${[...hn].join(", ")}`}),c;let y=new Set(h),v;if(p.since!==void 0&&p.since.trim().length>0){let C=new Date(p.since);if(isNaN(C.getTime()))return c.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),c;v=C.getTime()}let w=S.historyFile(l),b=Es.createReadStream(w),A=Ps.createInterface({input:b,crlfDelay:1/0});c.raw.setHeader("content-type","application/x-ndjson"),c.raw.statusCode=200;try{for await(let C of A){let x=typeof C=="string"?C.trim():"";if(x.length===0)continue;let T;try{T=JSON.parse(x)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!T||typeof T!="object"||Array.isArray(T)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let _=T;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let U=_.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let $=U.update,P=$.sessionUpdate;if(typeof P!="string"||!y.has(P)||v!==void 0&&_.recordedAt<v)continue;let B={ts:new Date(_.recordedAt).toISOString(),kind:P,update:$};$.messageId!==void 0&&$.messageId!==null&&(B.messageId=$.messageId),c.raw.write(JSON.stringify(B)+`
|
|
148
|
-
`)}}catch(C){if(C.code==="ENOENT")return c.raw.end(),c;throw C}return c.raw.end(),c}),n.get("/v1/sessions/:id/attention",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);return!l&&!await e.hasRecord(p)?(c.code(404).send({error:"session not found"}),c):l?{flags:l.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(u,c)=>{let f=u.query;if(!f.source||f.source.trim().length===0)return c.code(400).send({error:"source query parameter is required"}),c;let p=await e.list({includeNonInteractive:!0}),l=[];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 y of h)y.source===f.source&&l.push({...y,sessionId:g.sessionId})}return{flags:l}}),n.post("/v1/sessions/:id/attention/clear",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,g=u.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)){c.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 y=e.get(p);if(y){if(m.length>0&&h.length>0)y.clearAttentionFlag(m,h);else{let C=Array.from(y.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of C)y.clearAttentionFlag(x.split("::")[0],x.split("::").slice(1).join("::"))}c.code(204).send();return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}let v=e.store,w=await v.read(p);if(!w){c.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(m.length>0&&h.length>0){let C=`${m}::${h}`;A=b.filter(x=>`${x.source}::${x.reason}`!==C)}else A=[];if(A.length===b.length&&A.every((C,x)=>C.source===b[x].source&&C.reason===b[x].reason)){c.code(204).send();return}await v.write({...w,attentionFlags:A}),c.code(204).send()})}function ho(n,e,t,s={}){n.get("/v1/agents",async()=>Ue(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await oe(a,[],{npmRegistry:s.npmRegistry}),u=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:u,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(u=>({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,agentId:u.agentId,cwd:u.cwd,title:u.title,updatedAt:u.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===k.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function yo(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var zu=/^[A-Za-z0-9._-]+$/;function yn(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=Ju(a);if("error"in d){o.code(400).send({error:d.error});return}try{let u=t.register(d.config);o.code(201).send(u)}catch(u){Et(o,u)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){Et(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){Et(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){Et(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){Et(o,d)}})}function Et(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 Ju(n){let e=n.name;if(typeof e!="string"||!zu.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function wo(n,e){yn(n,"extension",e)}function vo(n,e){yn(n,"transformer",e)}function bo(n,e){n.get("/v1/config",async()=>e)}import{z as ot}from"zod";W();import*as it from"fs/promises";import*as Io from"path";import{randomBytes as _h,scrypt as Wu,timingSafeEqual as Qu}from"crypto";import{promisify as Vu}from"util";var Ku=Vu(Wu);function So(){return Io.join(S.home(),"password-hash")}var Gu=128*1024*1024;async function ko(){try{return(await it.readFile(So(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ao(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await it.readFile(So(),"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),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await Ku(n,o,a.length,{N:s,r,p:i,maxmem:Gu});return d.length!==a.length?!1:Qu(d,a)}var Yu=ot.object({password:ot.string().min(1),label:ot.string().min(1).max(256).optional(),ttlSec:ot.number().int().positive().optional()}),Xu=ot.object({id:ot.string().optional()}).optional();function Co(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Zu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Yu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await ko())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Ao(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=Xu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Zu(n){return n.ip||"unknown"}import{nanoid as Ts}from"nanoid";function xo(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let u of e)u(d)}catch(d){for(let u of e)u({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,u=>{if(u){d(u);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as Ro}from"crypto";import*as Eo from"os";import*as Po from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function rl(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let u=d.content;typeof u.text=="string"&&(r+=u.text.length)}}return r}function re(n,e,t){let s=n.get(e);if(!s)throw E(k.SessionNotFound,t??`session ${e} not found`);return s}async function wn(n,e){let t=rt(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=Ro(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],d=Rs({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),u;try{u=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(c){throw t!==void 0&&t.abandon(c instanceof Error?c:void 0),r!==void 0&&r.abandon(c instanceof Error?c:void 0),c}if(t!==void 0&&t.bindToSession(u),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let c=s,f=n.mcpTokenRegistry;r.complete(u),u.onClose(()=>{f.unbind(c)})}return pl(u,n),_o(u.sessionId,n),u}function To(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=qi({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=xo(t),a=new Le(o),d={clientId:`hydra_client_${Ts(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let u=(f,p)=>{if(d.attached.get(f)?.readonly)throw E(k.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=pr.parse(f??{});p.clientInfo?.name&&(d.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let l=p.clientInfo?.version;return l&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,l):e.onTransformerVersion?.(i.name,l)),fl()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let l=p??{},g=Array.isArray(l.commands)?l.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return f.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let g=l??{},m=typeof g.instructions=="string"?g.instructions:void 0,h=Array.isArray(g.tools)?g.tools.map(y=>{if(!y||typeof y!="object")return;let v=y;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let w={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(w.outputSchema=v.outputSchema),w}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,h),{ok:!0,registered:h.length}});let p=l=>{let g=l??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(k.InvalidParams,"sessionId is required");return g.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(!e.manager)throw E(k.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(g,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async l=>{let g=p(l);if(!e.manager)throw E(k.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(g,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(m.value===void 0)throw E(k.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(k.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(g,i.name,m.key,m.value)}catch(h){throw E(k.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(!e.manager)throw E(k.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(g,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let l=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(k.InvalidParams,"refresh_session requires sessionId");return await l.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{f.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let l=p??{},g=Array.isArray(l.intercepts)?l.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,g),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let l=p??{},g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.method=="string"?l.method:void 0,h=l.envelope,y=l.route;if(!g)throw E(-32602,"emit_message requires sessionId");if(!m&&y!=="client_broadcast")throw E(-32602,"emit_message requires method");let v=re(e.manager,g),w=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(w)return v.dischargeClaim(w,h),{ok:!0};if(y==="chain")return{ok:!0,response:await v.emitToChain(i.name,m,h)};if(y==="queue"){if(m!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await v.emitToQueue(i.name,h)}}if(y==="daemon")return{ok:!0,response:await v.emitToChain(i.name,m,h)};if(y==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return v.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let l=p??{},g=typeof l.sessionId=="string"?l.sessionId:void 0;if(!g)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return re(e.manager,g).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async p=>dl(p,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let l=p??{},g=typeof l.agentId=="string"?l.agentId:e.defaultAgent,m=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,y=l._meta&&typeof l._meta=="object"?l._meta:void 0,v=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,w=v&&typeof v.title=="string"?v.title:void 0,b=v&&typeof v.model=="string"?v.model:void 0;if(!m&&h){let x=e.manager.get(h);x&&(m=x.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 l.interactive=="boolean"?l.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 l=p??{};if(typeof l.sessionId!="string")throw E(k.InvalidParams,"fork_session requires sessionId");let g=typeof l.forkAt=="string"?l.forkAt:void 0,m=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.agentId=="string"?l.agentId:void 0,y=typeof l.mode=="string"&&(l.mode==="verbatim"||l.mode==="synthesis")?l.mode:void 0,v=typeof l.model=="string"&&l.model.length>0?l.model:void 0;return await e.manager.forkSession(l.sessionId,{...g!==void 0?{forkAt:g}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{},...y!==void 0?{mode:y}:{},...v!==void 0?{model:v}:{}})}),a.onRequest("session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(k.InvalidParams,"session/fork requires sessionId");let g=typeof l.cwd=="string"?l.cwd:void 0;return{sessionId:(await e.manager.forkSession(l.sessionId,{...g!==void 0?{cwd:g}:{},mode:"verbatim"})).sessionId}});let f=async(p,l)=>{let g=p??{};if(typeof g.sessionId!="string")throw E(k.InvalidParams,`${l} 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 y=await e.manager.deleteRecord(m);return{id:m,existed:y}};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(k.InvalidParams,"session/close requires sessionId");u(l.sessionId,"session/close");let g=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=e.manager.get(g);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(g))return{};throw E(k.SessionNotFound,`session ${g} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:l,existed:g}=await f(p,"hydra-acp/session/delete");if(!g)throw E(k.SessionNotFound,`session ${l} not found`);return{deleted:!0,sessionId:l}}),a.onRequest("hydra-acp/child_session/await",async p=>{let l=p??{},g=typeof l.childSessionId=="string"?l.childSessionId:void 0,m=l.until==="idle"?"idle":"turn_complete",h=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!g)throw E(-32602,"await_child requires childSessionId");let y=re(e.manager,g,`child session ${g} not found`);return new Promise(v=>{let A=[],C=[],x=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(B),_?.(),U?.(),v(T?{entries:A,truncated:!0}:{entries:A}))};_=y.onBroadcast(J=>{let ie=rl(J);for(A.push(J),C.push(ie),x+=ie;A.length>0&&(A.length>1e3||x>1048576);)A.shift(),x-=C.shift()??0,T=!0;m==="turn_complete"&&J.params?.update?.sessionUpdate==="turn_complete"&&P()});let B=setTimeout(P,h);typeof B.unref=="function"&&B.unref(),U=y.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let l=p??{},g=typeof l.childSessionId=="string"?l.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=>cl(p,i.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>ul(p,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let l=p??{},g=typeof l.token=="string"?l.token:void 0,m=typeof l.sessionId=="string"?l.sessionId:void 0,h=typeof l.estimatedRemainingMs=="number"?l.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(k.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let l=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,g=await e.manager.loadToolBlob(l,p.hash);if(g===null)throw E(k.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async f=>il(f,e)),a.onRequest("logout",async f=>ol(f,e)),a.onRequest("session/new",async f=>{let p=mr.parse(f),l=ft(f?._meta),g=Array.isArray(l.transformers)&&l.transformers.every(P=>typeof P=="string")?l.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,v=p.mcpServers;if(l.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Ro(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let B={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};v=[...p.mcpServers??[],B]}let w,b,A=rt(e);A!==void 0&&(v=[...v??[],...A.descriptors]);let C=Rs({baselineMcpServers:p.mcpServers,stdinEnabled:l.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:p.cwd,agentId:l.agentId??e.defaultAgent,mcpServers:v,title:l.title,agentArgs:l.agentArgs,model:l.model,onInstallProgress:Mo(a),transformChain:m,originatingClient:d.clientInfo,...l.interactive!==void 0?{interactive:l.interactive}:{},...l.env!==void 0?{forwardedEnv:l.env}:{},...C?{mintMcpServersForSwap:C}:{}})}catch(P){throw y!==void 0&&y.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&&y!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,B=e.mcpTokenRegistry;y.complete(x),x.onClose(()=>{B.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,B=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{B.unbind(P)})}A!==void 0&&A.bindToSession(x),_o(x.sessionId,e);let T,_;try{Sn(d,x,x.sessionId),T=Pt(a,x,d),{entries:_}=await x.attach(T,"full")}catch(P){throw await x.close({deleteRecord:!1}).catch(()=>{}),P}d.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=vn(x),$=bn(x);return{sessionId:x.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:x.buildConfigOptions(),_meta:In(e.manager,x,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=hr.parse(f),l=p.clientInfo?.version;l&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,l):e.onTransformerVersion?.(i.name,l));let g=ft(p._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!m} readonly=${h}`);let v=m?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(v);if(!w&&h){let $=await e.manager.loadFromDisk(v);if(!$)throw E(k.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(v),B=p.clientId??`cli_${Ts(8)}`;d.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${P.length}`);for(let J of P)await a.notify(J.method,J.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:P.length,_meta:ll($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(v),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(k.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(k.SessionNotFound,`session ${p.sessionId} was deleted`);let B=P.originatingClient?P:{...P,originatingClient:d.clientInfo},J=y!==void 0?{...B,forwardedEnv:y}:B;w=await wn(e,{...J,onInstallProgress:Mo(a)})}Sn(d,w,w.sessionId);let A=Pt(a,w,d,p.clientInfo,p.clientId),C=g.replayMode==="drip",{entries:x,appliedPolicy:T}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:C,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${x.length} readonly=${h}${C?" replayMode=drip":""}`),C){let $=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,P=750;(async()=>{let B=null;for(let J of x){let ie=typeof J.recordedAt=="number"?J.recordedAt:null;if(B!==null&&ie!==null){let Oe=Math.min(P,Math.max(0,(ie-B)/$));Oe>0&&await new Promise(Tt=>setTimeout(Tt,Oe))}ie!==null&&(B=ie);try{await a.notify(J.method,J.params)}catch{return}}})()}else for(let $=0;$<x.length&&!a.isClosed();$++){let P=x[$],B=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await B}w.replayPendingPermissions(A);let _=vn(w),U=bn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:x.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:In(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=yr.parse(f),l=d.attached.get(p.sessionId);if(!l)throw E(k.SessionNotFound,"client not attached to that session");let g=e.manager.get(p.sessionId);return g?.detach(l.clientId),d.attached.delete(p.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[lt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=wr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Qt).map(vr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(k.InternalError,"agent registry unavailable");return Ue(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(k.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(p.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let p=br.parse(f);u(p.sessionId,"session/prompt");let l=d.attached.get(p.sessionId);if(!l)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),E(k.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(k.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),g=await wn(e,m);let h=Pt(a,g,d,void 0,l.clientId);await g.attach(h,"none")}return g.prompt(l.clientId,p)});let c=f=>{let p;try{p=jt.parse(f)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let l=d.attached.get(p.sessionId);if(!l)return;if(l.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let g=e.manager.get(p.sessionId);g&&g.cancel(l.clientId).catch(m=>{n.log.warn(`session/cancel for ${p.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",c),a.onRequest("session/cancel",async f=>{let p=jt.parse(f);return u(p.sessionId,"session/cancel"),c(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=Sr.parse(f);return u(p.sessionId,"hydra-acp/prompt/cancel"),re(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=jt.parse(f);return u(p.sessionId,"hydra-acp/session/force_cancel"),re(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=kr.parse(f);return u(p.sessionId,"hydra-acp/prompt/update"),re(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let p=Ar.parse(f);u(p.sessionId,"hydra-acp/prompt/amend");let l=d.attached.get(p.sessionId);if(!l)throw E(k.SessionNotFound,"not attached to session");return re(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(k.InvalidParams,"session/resume requires sessionId");let g=await e.manager.resolveCanonicalId(l)??l,m=e.manager.get(g);if(!m){let w=await e.manager.loadFromDisk(g);if(!w)throw E(k.SessionNotFound,`session ${l} not found in memory or on disk`);m=await wn(e,w)}Sn(d,m,m.sessionId);let h=Pt(a,m,d);await m.attach(h,"pending_only"),d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1}),m.replayPendingPermissions(h);let y=vn(m),v=bn(m);return{sessionId:m.sessionId,...y?{modes:y}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:In(e.manager,m,{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(k.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(l)??l,m=e.manager.get(g);if(!m){let b=await e.manager.loadFromDisk(g);if(!b)throw E(k.SessionNotFound,`session ${l} not found in memory or on disk`);m=await wn(e,b)}Sn(d,m,m.sessionId);let h=Pt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}m.replayPendingPermissions(h);let v=vn(m),w=bn(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...w?{models:w}:{},configOptions:m.buildConfigOptions(),_meta:In(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&u(p,"session/set_model");let l=al(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:g}=l,m=await l.session.forwardRequest("session/set_model",{...f,modelId:g});return l.session.applyModelChange(g),m}),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(k.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(k.InvalidParams,"session/set_mode requires string modeId");let g=re(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,l=y=>E(k.InvalidParams,y),g=p?.sessionId;if(typeof g=="string"&&u(g,"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 m=re(e.manager,p.sessionId),h=m.buildConfigOptions().find(y=>y.id===p.configId);if(!h)throw l(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(y=>y.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!==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 l(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let l=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"||l.has(p))throw E(k.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(k.MethodNotFound,`Method not found: ${p}`);return u(h,p),re(e.manager,h).forwardRequest(p,f)})})}async function il(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(k.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],u=d.find(l=>l.id===s);if(!u){let l=d.map(g=>g.id);throw E(k.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(g=>JSON.stringify(g)).join(", ")}]`)}let c=u._meta?.type,f=(()=>{let l=u._meta?.["terminal-auth"];if(l&&typeof l=="object"&&!Array.isArray(l))return l})();if((u.type??(c==="agent"||c==="terminal"?c:f!==void 0?"terminal":"agent"))==="terminal"){let l=(w,b)=>{if(!Array.isArray(w))throw E(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw E(k.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&&Po.isAbsolute(w)?w:g.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):[];m=g.command,h=[...g.args,...b]}let y={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(y[w]=b);Object.assign(y,g.env);let v=Eo.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:h,env:y,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Re(l,a)}}async function ol(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function Mo(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(Cr,t).catch(()=>{})}}function vn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function bn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function al(n,e){if(!n||typeof n!="object")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:k.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Qe(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:k.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function dl(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(k.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(k.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw E(k.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return re(t.manager,r).addTransformer(i),{ok:!0}}async function cl(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(k.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw E(k.InvalidParams,"hydra-acp/attention/set requires string reason");return re(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function ul(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(k.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw E(k.InvalidParams,"hydra-acp/attention/clear requires string reason");return re(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function ll(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{[lt]:Ht(e,t)}}function In(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 ut(e.agentMeta,Ht(s,r))}function fl(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Y},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:ut(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 pl(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 _o(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 Pt(n,e,t,s,r){return{clientId:r??`cli_${Ts(8)}`,connection:n,clientInfo:s}}function Sn(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var kn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as ml}from"crypto";import{McpServer as gl}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as hl}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as X}from"zod";function _s(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function te(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var $o="Bearer ";function at(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith($o))return;let t=e.slice($o.length).trim();return t.length>0?t:void 0}function yl(n){let e=new gl({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:X.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return te(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:X.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return te(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:X.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:X.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:X.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return te(i)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:X.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:X.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return te({outcome:r,writeCursor:i.writeCursor,closed:i.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:X.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:X.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:X.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:X.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:X.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:X.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:X.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:X.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:X.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 te(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 te(t)}),e}var wl=1e4;function Fo(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let u=yl(a),c=new hl({sessionIdGenerator:()=>ml()});await u.connect(c);let f={server:u,transport:c};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(o,a){let d=at(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(d);if(u===void 0){a.code(404).send({error:"unknown stdin token"});return}let c;if(u.session!==void 0)c=u.session;else{let p,l=new Promise(m=>{p=setTimeout(()=>m(void 0),wl)}),g=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),g===void 0){a.code(503).send({error:"session not ready"});return}c=g}let f=await s(d,c);a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}import{randomUUID as vl}from"crypto";import{McpServer as bl}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Il}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ee}from"zod";function Sl(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function kl(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function Al(n){let e=new bl({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:Ee.string().min(1).describe("Case-insensitive substring to search for."),limit:Ee.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ee.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 i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return te({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 o=[],a=t.toLowerCase();for await(let{entryId:u,entry:c}of i.iterRecallNewestFirst()){let f=_s(c);if(!f)continue;let{kind:p}=f;if(p==="tool_call"&&!r)continue;let l=Ve([c]),g=l.toLowerCase().indexOf(a);if(g<0)continue;let m=Sl(p),h=kl(l,g),y=typeof c.recordedAt=="number"?String(c.recordedAt):void 0;if(o.push({entryId:u,speaker:m,snippet:h,timestamp:y}),o.length>=s)break}o.sort((u,c)=>u.entryId-c.entryId);let d=o.length>=s;return te({matches:o,total_matched:o.length,truncated:d})}),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:Ee.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ee.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 te({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 i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getRecallTotalCount();if(o===0)return te({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),d=Math.min(s,o-1),u=a>t||d<s;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:u}};let c=await r.sliceRecallHistory(a,d),f=Ve(c);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:c.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:Ee.string().optional(),file_path:Ee.string().optional(),limit:Ee.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return te({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 o=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let d=new Map,u=Math.max(r*4,200);for await(let{entryId:l,entry:g}of i.iterRecallNewestFirst()){let m=_s(g);if(!m)continue;let{kind:h,update:y}=m;if(h!=="tool_call"&&h!=="tool_call_update")continue;let v=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${l}`,w=d.get(v);w||(w={entryId:l,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,w)),l<w.entryId&&(w.entryId=l),typeof y.name=="string"&&y.name.length>0?w.toolName=y.name:w.toolName==="(unnamed)"&&typeof y.title=="string"&&y.title.length>0&&(w.toolName=y.title);let b=y.rawInput;if(b&&typeof b=="object"&&!Array.isArray(b)&&Object.keys(b).length>0)for(let[A,C]of Object.entries(b))w.rawInput[A]===void 0&&(w.rawInput[A]=C);if(Array.isArray(y.locations))for(let A of y.locations){let C=A?.path;typeof C=="string"&&C.length>0&&!w.locations.includes(C)&&w.locations.push(C)}if(typeof y.status=="string"&&w.status==="in_progress"&&(w.status=y.status),g.recordedAt!==void 0&&w.timestamp===void 0&&(w.timestamp=String(g.recordedAt)),d.size>=u)break}let c=[...d.keys()].sort((l,g)=>d.get(l).entryId-d.get(g).entryId),f=[];for(let l of c){let g=d.get(l);if(t!==void 0&&g.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),y=["file_path","filePath","path"],v=!1;for(let w of y){let b=g.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){v=!0;break}}if(!v){for(let w of g.locations)if(w.toLowerCase().includes(h)){v=!0;break}}if(!v)continue}let m={};for(let[h,y]of Object.entries(g.rawInput))typeof y=="string"?m[h]=y.length>500?y.slice(0,497)+"\u2026":y:(typeof y=="number"||typeof y=="boolean")&&(m[h]=y);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 te({calls:f,truncated:p})}),e}var Cl=1e4;function Oo(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let u=Al(a),c=new Il({sessionIdGenerator:()=>vl()});await u.connect(c);let f={server:u,transport:c};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(o,a){let d=at(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(d);if(u===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(d,async()=>{if(u.session!==void 0)return u.session;let p,l=new Promise(m=>{p=setTimeout(()=>m(void 0),Cl)}),g=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),g===void 0)throw new Error("recall: session not ready");return g});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var An=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 $l}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Fl}from"crypto";import{Server as xl}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Ml,ListToolsRequestSchema as Rl}from"@modelcontextprotocol/sdk/types.js";function No(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new xl({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(Rl,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let d=await s.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(Ml,async(a,d)=>{let u=a.params.name,c=d._meta?.progressToken??d.requestId,f=Pl(c,d.sendNotification);try{let p=await r(),l=await Tl(e.connection,n,u,a.params.arguments??{},p);return _l(l,u)}catch(p){return $s(p instanceof Error?p.message:String(p))}finally{f()}}),i}var El=15e3;function Pl(n,e,t=El){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 Tl(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function _l(n,e){if(n===null||typeof n!="object")return $s(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:$s(`extension ${e} omitted content array`)}function $s(n){return{content:[{type:"text",text:n}],isError:!0}}var Ol=1e4;function Ho(n,e,t){let s=new Map;async function r(c){try{await c.transport.close()}catch{}try{await c.server.close()}catch{}}function i(c){for(let f of s.values()){let p=f.get(c);p!==void 0&&(f.delete(c),r(p))}}async function o(c,f){for(let[p,l]of s){if(e.lookup(p)?.session?.sessionId!==c)continue;let m=l.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(c=>{i(c)});async function a(c,f){let p=s.get(c);p===void 0&&(p=new Map,s.set(c,p),e.addDisposer(c,async()=>{let b=s.get(c);if(b!==void 0){s.delete(c);for(let A of b.values())await r(A)}}));let l=p.get(f);if(l!==void 0)return l.transport;let g=t.lookup(f);if(g===void 0)return;let v=No(f,g,async()=>{let b=e.lookup(c);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,C=new Promise(T=>{A=setTimeout(()=>T(void 0),Ol)}),x=await Promise.race([b.sessionReady.catch(()=>{}),C]);if(A!==void 0&&clearTimeout(A),x===void 0)throw new Error("session not ready");return x.sessionId},{peekSessionId:()=>e.lookup(c)?.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 C=A.tools;if(!Array.isArray(C))return;let x=[];for(let T of C){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),x.push(U)}return x}}),w=new $l({sessionIdGenerator:()=>Fl()});return await v.connect(w),p.set(f,{server:v,transport:w}),w}async function d(c,f){let p=at(c);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=c.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(c.raw,f.raw,c.body)}let u={config:{skipAuth:!0}};return n.post("/mcp/:name",u,async(c,f)=>{await d(c,f)}),n.get("/mcp/:name",u,async(c,f)=>{await d(c,f)}),n.delete("/mcp/:name",u,async(c,f)=>{await d(c,f)}),{notifyToolListChanged:o}}async function qo(n,e){Ll(n);let t=n.daemon.tls?await we.readFile(Z(n.daemon.tls.key)):void 0,s=n.daemon.tls?await we.readFile(Z(n.daemon.tls.cert)):void 0;await we.mkdir(S.home(),{recursive:!0});let{stream:r,fileStream:i}=await Ul(n.daemon.logLevel),o=Nl({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(Hl,{options:{handleProtocols:Vs}}),Hn(O=>{o.log.info(O)}),Un(O=>{o.log.info(O)});let a=await dn.load(),d=new pn,u=new fn,c=new ln([new cn(e),new un(a),u]),f=Li({validator:c});o.addHook("onRequest",async(O,fe)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,fe)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let l=setInterval(()=>{d.sweepExpired()},300*1e3);l.unref();let g=new Ot(n,{onFetched:()=>{_i(g,v)}});Ss(O=>o.log.info(O));let m={info:O=>o.log.info(O),warn:O=>o.log.warn(O)},h=O=>xe.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Xs(n.compressToolContent);let y=new on,v=new Xt(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,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:n.npmRegistry,extensionCommands:y,defaultCwd:n.defaultCwd}),w=new sn(zs(n),void 0,{tokenRegistry:u}),b=new rn(Js(n),void 0,{tokenRegistry:u});yo(o,Y,Oi(n));let A=new kn,C=new An,x,T=()=>{if(x!==void 0)return x;let O=o.server.address();return x=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,x};go(o,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:C,mcpTokenRegistry:A,getDaemonOrigin:T}),ho(o,g,v,{npmRegistry:n.npmRegistry}),wo(o,w),vo(o,b),bo(o,{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]}),Co(o,{store:a,rateLimiter:d}),Fo(o,A),Oo(o,A);let _=Ho(o,A,C);To(o,{validator:c,manager:v,defaultAgent:n.defaultAgent,processRegistry:u,onExtensionVersion:(O,fe)=>w.reportVersion(O,fe),onTransformerVersion:(O,fe)=>b.reportVersion(O,fe),transformers:b,extensionCommands:y,mcpTokenRegistry:A,extensionMcp:C,extensionMcpControls:_,getDaemonOrigin:T,registry:g});let U=!!n.daemon.tls;await o.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=o.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,B,J=n.daemon.host,ie=P;if(U&&t&&s){B=Dl({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:o.log});let O=B.address();O&&typeof O=="object"&&(ie=O.port)}await we.mkdir(S.home(),{recursive:!0}),await Ti({pid:process.pid,host:J,port:ie,loopbackPort:P,startedAt:new Date().toISOString()});let Oe={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(Oe),b.setContext(Oe),await w.start(),await b.start();try{await v.reconcilePermissionFlags()}catch(O){o.log.warn(`permission flag reconcile failed: ${O.message}`)}v.resurrectPendingQueues().catch(O=>{o.log.warn(`queue replay scan failed: ${O.message}`)}),v.resumePendingCompactions().catch(O=>{o.log.warn(`compaction resume scan failed: ${O.message}`)}),v.resumePendingAgentSwaps().catch(O=>{o.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Tt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ns=Tt>0?$i({registry:g,manager:v,intervalMs:Tt,logger:m}):void 0,Hs=n.daemon.sessionGcIntervalMinutes*60*1e3,ea=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,js=Hs>0?Fi({manager:v,intervalMs:Hs,maxAgeMs:ea,logger:m}):void 0;return{app:o,manager:v,registry:g,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:C,processRegistry:u,shutdown:async()=>{js&&js(),Ns&&Ns(),clearInterval(p),clearInterval(l);let O=async(fe,ta)=>{try{await ta()}catch(xn){o.log.warn(`shutdown step ${fe} failed: ${xn instanceof Error?xn.message:String(xn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>v.closeAll()),await O("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>v.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Hn(null),Un(null),Ss(null),B&&await O("tlsTerminator.close",()=>new Promise(fe=>B.close(()=>fe()))),await O("app.close",()=>o.close());try{Uo.unlinkSync(S.pidFile())}catch{}await O("fileStream.flushSync",()=>i.flushSync())}}}var Bo=20;async function Bl(n,e){let t=dt.dirname(n),s=dt.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await we.readdir(t)}catch{return}let o=[];for(let d of i){let u=d.match(r);u&&o.push({name:d,n:Number(u[1])})}if(o.length<=e)return;o.sort((d,u)=>d.n-u.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(d=>we.unlink(dt.join(t,d.name))))}async function Ul(n){await Bl(S.logFile(),Bo);let e=await jl({file:S.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Bo,removeOtherLogFiles:!0}}),t=jo.destination(2);return{stream:jo.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Dl(n){let e=Lo.createServer(n.tlsOptions,t=>{let s=Do.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),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 Ll(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.`)}async function sf(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(Zo(),Xo));n();let e=await Tn(),t=await Bs(),s=await qo(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
148
|
+
`)}}catch(C){if(C.code==="ENOENT")return c.raw.end(),c;throw C}return c.raw.end(),c}),n.get("/v1/sessions/:id/attention",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);return!l&&!await e.hasRecord(p)?(c.code(404).send({error:"session not found"}),c):l?{flags:l.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(u,c)=>{let f=u.query;if(!f.source||f.source.trim().length===0)return c.code(400).send({error:"source query parameter is required"}),c;let p=await e.list({includeNonInteractive:!0}),l=[];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 y of h)y.source===f.source&&l.push({...y,sessionId:g.sessionId})}return{flags:l}}),n.post("/v1/sessions/:id/attention/clear",async(u,c)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,g=u.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)){c.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 y=e.get(p);if(y){if(m.length>0&&h.length>0)y.clearAttentionFlag(m,h);else{let C=Array.from(y.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of C)y.clearAttentionFlag(x.split("::")[0],x.split("::").slice(1).join("::"))}c.code(204).send();return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}let v=e.store,w=await v.read(p);if(!w){c.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(m.length>0&&h.length>0){let C=`${m}::${h}`;A=b.filter(x=>`${x.source}::${x.reason}`!==C)}else A=[];if(A.length===b.length&&A.every((C,x)=>C.source===b[x].source&&C.reason===b[x].reason)){c.code(204).send();return}await v.write({...w,attentionFlags:A}),c.code(204).send()})}function yo(n,e,t,s={}){n.get("/v1/agents",async()=>Ue(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await oe(a,[],{npmRegistry:s.npmRegistry}),u=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:u,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(u=>({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,agentId:u.agentId,cwd:u.cwd,title:u.title,updatedAt:u.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===k.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function wo(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Ju=/^[A-Za-z0-9._-]+$/;function yn(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=Wu(a);if("error"in d){o.code(400).send({error:d.error});return}try{let u=t.register(d.config);o.code(201).send(u)}catch(u){Et(o,u)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){Et(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){Et(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){Et(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){Et(o,d)}})}function Et(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 Wu(n){let e=n.name;if(typeof e!="string"||!Ju.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function vo(n,e){yn(n,"extension",e)}function bo(n,e){yn(n,"transformer",e)}function Io(n,e){n.get("/v1/config",async()=>e)}import{z as ot}from"zod";W();import*as it from"fs/promises";import*as So from"path";import{randomBytes as $h,scrypt as Qu,timingSafeEqual as Vu}from"crypto";import{promisify as Ku}from"util";var Gu=Ku(Qu);function ko(){return So.join(S.home(),"password-hash")}var Yu=128*1024*1024;async function Ao(){try{return(await it.readFile(ko(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Co(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await it.readFile(ko(),"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),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await Gu(n,o,a.length,{N:s,r,p:i,maxmem:Yu});return d.length!==a.length?!1:Vu(d,a)}var Xu=ot.object({password:ot.string().min(1),label:ot.string().min(1).max(256).optional(),ttlSec:ot.number().int().positive().optional()}),Zu=ot.object({id:ot.string().optional()}).optional();function xo(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=el(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Xu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ao())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Co(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=Zu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function el(n){return n.ip||"unknown"}import{nanoid as Ts}from"nanoid";function Mo(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let u of e)u(d)}catch(d){for(let u of e)u({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,u=>{if(u){d(u);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as Eo}from"crypto";import*as Po from"os";import*as To from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function il(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let u=d.content;typeof u.text=="string"&&(r+=u.text.length)}}return r}function re(n,e,t){let s=n.get(e);if(!s)throw E(k.SessionNotFound,t??`session ${e} not found`);return s}async function wn(n,e){let t=rt(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=Eo(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],d=Rs({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),u;try{u=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(c){throw t!==void 0&&t.abandon(c instanceof Error?c:void 0),r!==void 0&&r.abandon(c instanceof Error?c:void 0),c}if(t!==void 0&&t.bindToSession(u),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let c=s,f=n.mcpTokenRegistry;r.complete(u),u.onClose(()=>{f.unbind(c)})}return ml(u,n),$o(u.sessionId,n),u}function _o(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=zi({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Mo(t),a=new Le(o),d={clientId:`hydra_client_${Ts(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let u=(f,p)=>{if(d.attached.get(f)?.readonly)throw E(k.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=pr.parse(f??{});p.clientInfo?.name&&(d.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let l=p.clientInfo?.version;return l&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,l):e.onTransformerVersion?.(i.name,l)),pl()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let l=p??{},g=Array.isArray(l.commands)?l.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return f.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let g=l??{},m=typeof g.instructions=="string"?g.instructions:void 0,h=Array.isArray(g.tools)?g.tools.map(y=>{if(!y||typeof y!="object")return;let v=y;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let w={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(w.outputSchema=v.outputSchema),w}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,h),{ok:!0,registered:h.length}});let p=l=>{let g=l??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(k.InvalidParams,"sessionId is required");return g.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(!e.manager)throw E(k.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(g,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async l=>{let g=p(l);if(!e.manager)throw E(k.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(g,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(m.value===void 0)throw E(k.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(k.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(g,i.name,m.key,m.value)}catch(h){throw E(k.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async l=>{let g=p(l),m=l??{};if(typeof m.key!="string"||m.key.length===0)throw E(k.InvalidParams,"key is required");if(!e.manager)throw E(k.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(g,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let l=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(k.InvalidParams,"refresh_session requires sessionId");return await l.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{f.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let l=p??{},g=Array.isArray(l.intercepts)?l.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,g),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let l=p??{},g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.method=="string"?l.method:void 0,h=l.envelope,y=l.route;if(!g)throw E(-32602,"emit_message requires sessionId");if(!m&&y!=="client_broadcast")throw E(-32602,"emit_message requires method");let v=re(e.manager,g),w=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(w)return v.dischargeClaim(w,h),{ok:!0};if(y==="chain")return{ok:!0,response:await v.emitToChain(i.name,m,h)};if(y==="queue"){if(m!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await v.emitToQueue(i.name,h)}}if(y==="daemon")return{ok:!0,response:await v.emitToChain(i.name,m,h)};if(y==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return v.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let l=p??{},g=typeof l.sessionId=="string"?l.sessionId:void 0;if(!g)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return re(e.manager,g).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async p=>cl(p,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let l=p??{},g=typeof l.agentId=="string"?l.agentId:e.defaultAgent,m=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,y=l._meta&&typeof l._meta=="object"?l._meta:void 0,v=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,w=v&&typeof v.title=="string"?v.title:void 0,b=v&&typeof v.model=="string"?v.model:void 0;if(!m&&h){let x=e.manager.get(h);x&&(m=x.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 l.interactive=="boolean"?l.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 l=p??{};if(typeof l.sessionId!="string")throw E(k.InvalidParams,"fork_session requires sessionId");let g=typeof l.forkAt=="string"?l.forkAt:void 0,m=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.agentId=="string"?l.agentId:void 0,y=typeof l.mode=="string"&&(l.mode==="verbatim"||l.mode==="synthesis")?l.mode:void 0,v=typeof l.model=="string"&&l.model.length>0?l.model:void 0;return await e.manager.forkSession(l.sessionId,{...g!==void 0?{forkAt:g}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{},...y!==void 0?{mode:y}:{},...v!==void 0?{model:v}:{}})}),a.onRequest("session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(k.InvalidParams,"session/fork requires sessionId");let g=typeof l.cwd=="string"?l.cwd:void 0;return{sessionId:(await e.manager.forkSession(l.sessionId,{...g!==void 0?{cwd:g}:{},mode:"verbatim"})).sessionId}});let f=async(p,l)=>{let g=p??{};if(typeof g.sessionId!="string")throw E(k.InvalidParams,`${l} 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 y=await e.manager.deleteRecord(m);return{id:m,existed:y}};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(k.InvalidParams,"session/close requires sessionId");u(l.sessionId,"session/close");let g=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=e.manager.get(g);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(g))return{};throw E(k.SessionNotFound,`session ${g} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:l,existed:g}=await f(p,"hydra-acp/session/delete");if(!g)throw E(k.SessionNotFound,`session ${l} not found`);return{deleted:!0,sessionId:l}}),a.onRequest("hydra-acp/child_session/await",async p=>{let l=p??{},g=typeof l.childSessionId=="string"?l.childSessionId:void 0,m=l.until==="idle"?"idle":"turn_complete",h=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!g)throw E(-32602,"await_child requires childSessionId");let y=re(e.manager,g,`child session ${g} not found`);return new Promise(v=>{let A=[],C=[],x=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(B),_?.(),U?.(),v(T?{entries:A,truncated:!0}:{entries:A}))};_=y.onBroadcast(J=>{let ie=il(J);for(A.push(J),C.push(ie),x+=ie;A.length>0&&(A.length>1e3||x>1048576);)A.shift(),x-=C.shift()??0,T=!0;m==="turn_complete"&&J.params?.update?.sessionUpdate==="turn_complete"&&P()});let B=setTimeout(P,h);typeof B.unref=="function"&&B.unref(),U=y.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let l=p??{},g=typeof l.childSessionId=="string"?l.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=>ul(p,i.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>ll(p,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let l=p??{},g=typeof l.token=="string"?l.token:void 0,m=typeof l.sessionId=="string"?l.sessionId:void 0,h=typeof l.estimatedRemainingMs=="number"?l.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(k.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let l=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,g=await e.manager.loadToolBlob(l,p.hash);if(g===null)throw E(k.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async f=>ol(f,e)),a.onRequest("logout",async f=>al(f,e)),a.onRequest("session/new",async f=>{let p=mr.parse(f),l=ft(f?._meta),g=Array.isArray(l.transformers)&&l.transformers.every(P=>typeof P=="string")?l.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,v=p.mcpServers;if(l.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Eo(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let B={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};v=[...p.mcpServers??[],B]}let w,b,A=rt(e);A!==void 0&&(v=[...v??[],...A.descriptors]);let C=Rs({baselineMcpServers:p.mcpServers,stdinEnabled:l.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:p.cwd,agentId:l.agentId??e.defaultAgent,mcpServers:v,title:l.title,agentArgs:l.agentArgs,model:l.model,onInstallProgress:Ro(a),transformChain:m,originatingClient:d.clientInfo,...l.interactive!==void 0?{interactive:l.interactive}:{},...l.env!==void 0?{forwardedEnv:l.env}:{},...C?{mintMcpServersForSwap:C}:{}})}catch(P){throw y!==void 0&&y.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&&y!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,B=e.mcpTokenRegistry;y.complete(x),x.onClose(()=>{B.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,B=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{B.unbind(P)})}A!==void 0&&A.bindToSession(x),$o(x.sessionId,e);let T,_;try{Sn(d,x,x.sessionId),T=Pt(a,x,d),{entries:_}=await x.attach(T,"full")}catch(P){throw await x.close({deleteRecord:!1}).catch(()=>{}),P}d.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=vn(x),$=bn(x);return{sessionId:x.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:x.buildConfigOptions(),_meta:In(e.manager,x,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=hr.parse(f),l=p.clientInfo?.version;l&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,l):e.onTransformerVersion?.(i.name,l));let g=ft(p._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!m} readonly=${h}`);let v=m?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(v);if(!w&&h){let $=await e.manager.loadFromDisk(v);if(!$)throw E(k.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(v),B=p.clientId??`cli_${Ts(8)}`;d.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${P.length}`);for(let J of P)await a.notify(J.method,J.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:P.length,_meta:fl($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(v),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(k.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(k.SessionNotFound,`session ${p.sessionId} was deleted`);let B=P.originatingClient?P:{...P,originatingClient:d.clientInfo},J=y!==void 0?{...B,forwardedEnv:y}:B;w=await wn(e,{...J,onInstallProgress:Ro(a)})}Sn(d,w,w.sessionId);let A=Pt(a,w,d,p.clientInfo,p.clientId),C=g.replayMode==="drip",{entries:x,appliedPolicy:T}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:C,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${x.length} readonly=${h}${C?" replayMode=drip":""}`),C){let $=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,P=750;(async()=>{let B=null;for(let J of x){let ie=typeof J.recordedAt=="number"?J.recordedAt:null;if(B!==null&&ie!==null){let Oe=Math.min(P,Math.max(0,(ie-B)/$));Oe>0&&await new Promise(Tt=>setTimeout(Tt,Oe))}ie!==null&&(B=ie);try{await a.notify(J.method,J.params)}catch{return}}})()}else for(let $=0;$<x.length&&!a.isClosed();$++){let P=x[$],B=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await B}w.replayPendingPermissions(A);let _=vn(w),U=bn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:x.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:In(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=yr.parse(f),l=d.attached.get(p.sessionId);if(!l)throw E(k.SessionNotFound,"client not attached to that session");let g=e.manager.get(p.sessionId);return g?.detach(l.clientId),d.attached.delete(p.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[lt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=wr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Qt).map(vr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(k.InternalError,"agent registry unavailable");return Ue(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(k.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(p.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let p=br.parse(f);u(p.sessionId,"session/prompt");let l=d.attached.get(p.sessionId);if(!l)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),E(k.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(k.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),g=await wn(e,m);let h=Pt(a,g,d,void 0,l.clientId);await g.attach(h,"none")}return g.prompt(l.clientId,p)});let c=f=>{let p;try{p=jt.parse(f)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let l=d.attached.get(p.sessionId);if(!l)return;if(l.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let g=e.manager.get(p.sessionId);g&&g.cancel(l.clientId).catch(m=>{n.log.warn(`session/cancel for ${p.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",c),a.onRequest("session/cancel",async f=>{let p=jt.parse(f);return u(p.sessionId,"session/cancel"),c(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=Sr.parse(f);return u(p.sessionId,"hydra-acp/prompt/cancel"),re(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=jt.parse(f);return u(p.sessionId,"hydra-acp/session/force_cancel"),re(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=kr.parse(f);return u(p.sessionId,"hydra-acp/prompt/update"),re(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let p=Ar.parse(f);u(p.sessionId,"hydra-acp/prompt/amend");let l=d.attached.get(p.sessionId);if(!l)throw E(k.SessionNotFound,"not attached to session");return re(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(k.InvalidParams,"session/resume requires sessionId");let g=await e.manager.resolveCanonicalId(l)??l,m=e.manager.get(g);if(!m){let w=await e.manager.loadFromDisk(g);if(!w)throw E(k.SessionNotFound,`session ${l} not found in memory or on disk`);m=await wn(e,w)}Sn(d,m,m.sessionId);let h=Pt(a,m,d);await m.attach(h,"pending_only"),d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1}),m.replayPendingPermissions(h);let y=vn(m),v=bn(m);return{sessionId:m.sessionId,...y?{modes:y}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:In(e.manager,m,{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(k.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(l)??l,m=e.manager.get(g);if(!m){let b=await e.manager.loadFromDisk(g);if(!b)throw E(k.SessionNotFound,`session ${l} not found in memory or on disk`);m=await wn(e,b)}Sn(d,m,m.sessionId);let h=Pt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}m.replayPendingPermissions(h);let v=vn(m),w=bn(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...w?{models:w}:{},configOptions:m.buildConfigOptions(),_meta:In(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&u(p,"session/set_model");let l=dl(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:g}=l,m=await l.session.forwardRequest("session/set_model",{...f,modelId:g});return l.session.applyModelChange(g),m}),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(k.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(k.InvalidParams,"session/set_mode requires string modeId");let g=re(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,l=y=>E(k.InvalidParams,y),g=p?.sessionId;if(typeof g=="string"&&u(g,"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 m=re(e.manager,p.sessionId),h=m.buildConfigOptions().find(y=>y.id===p.configId);if(!h)throw l(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(y=>y.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!==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 l(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let l=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"||l.has(p))throw E(k.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(k.MethodNotFound,`Method not found: ${p}`);return u(h,p),re(e.manager,h).forwardRequest(p,f)})})}async function ol(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(k.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],u=d.find(l=>l.id===s);if(!u){let l=d.map(g=>g.id);throw E(k.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(g=>JSON.stringify(g)).join(", ")}]`)}let c=u._meta?.type,f=(()=>{let l=u._meta?.["terminal-auth"];if(l&&typeof l=="object"&&!Array.isArray(l))return l})();if((u.type??(c==="agent"||c==="terminal"?c:f!==void 0?"terminal":"agent"))==="terminal"){let l=(w,b)=>{if(!Array.isArray(w))throw E(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw E(k.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&&To.isAbsolute(w)?w:g.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):[];m=g.command,h=[...g.args,...b]}let y={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(y[w]=b);Object.assign(y,g.env);let v=Po.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:h,env:y,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Re(l,a)}}async function al(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function Ro(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(Cr,t).catch(()=>{})}}function vn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function bn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function dl(n,e){if(!n||typeof n!="object")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:k.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Qe(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:k.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function cl(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(k.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(k.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw E(k.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return re(t.manager,r).addTransformer(i),{ok:!0}}async function ul(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(k.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw E(k.InvalidParams,"hydra-acp/attention/set requires string reason");return re(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function ll(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(k.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw E(k.InvalidParams,"hydra-acp/attention/clear requires string reason");return re(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function fl(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{[lt]:Ht(e,t)}}function In(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 ut(e.agentMeta,Ht(s,r))}function pl(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Y},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:ut(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 ml(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 $o(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 Pt(n,e,t,s,r){return{clientId:r??`cli_${Ts(8)}`,connection:n,clientInfo:s}}function Sn(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var kn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as gl}from"crypto";import{McpServer as hl}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as yl}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as X}from"zod";function _s(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function te(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var Fo="Bearer ";function at(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Fo))return;let t=e.slice(Fo.length).trim();return t.length>0?t:void 0}function wl(n){let e=new hl({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:X.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return te(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:X.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return te(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:X.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:X.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:X.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return te(i)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:X.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:X.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return te({outcome:r,writeCursor:i.writeCursor,closed:i.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:X.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:X.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:X.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:X.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:X.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:X.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:X.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:X.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:X.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 te(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 te(t)}),e}var vl=1e4;function Oo(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let u=wl(a),c=new yl({sessionIdGenerator:()=>gl()});await u.connect(c);let f={server:u,transport:c};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(o,a){let d=at(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(d);if(u===void 0){a.code(404).send({error:"unknown stdin token"});return}let c;if(u.session!==void 0)c=u.session;else{let p,l=new Promise(m=>{p=setTimeout(()=>m(void 0),vl)}),g=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),g===void 0){a.code(503).send({error:"session not ready"});return}c=g}let f=await s(d,c);a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}import{randomUUID as bl}from"crypto";import{McpServer as Il}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Sl}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ee}from"zod";function kl(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Al(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function Cl(n){let e=new Il({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:Ee.string().min(1).describe("Case-insensitive substring to search for."),limit:Ee.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ee.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 i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return te({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 o=[],a=t.toLowerCase();for await(let{entryId:u,entry:c}of i.iterRecallNewestFirst()){let f=_s(c);if(!f)continue;let{kind:p}=f;if(p==="tool_call"&&!r)continue;let l=Ve([c]),g=l.toLowerCase().indexOf(a);if(g<0)continue;let m=kl(p),h=Al(l,g),y=typeof c.recordedAt=="number"?String(c.recordedAt):void 0;if(o.push({entryId:u,speaker:m,snippet:h,timestamp:y}),o.length>=s)break}o.sort((u,c)=>u.entryId-c.entryId);let d=o.length>=s;return te({matches:o,total_matched:o.length,truncated:d})}),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:Ee.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ee.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 te({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 i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getRecallTotalCount();if(o===0)return te({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),d=Math.min(s,o-1),u=a>t||d<s;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:u}};let c=await r.sliceRecallHistory(a,d),f=Ve(c);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:c.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:Ee.string().optional(),file_path:Ee.string().optional(),limit:Ee.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return te({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 o=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let d=new Map,u=Math.max(r*4,200);for await(let{entryId:l,entry:g}of i.iterRecallNewestFirst()){let m=_s(g);if(!m)continue;let{kind:h,update:y}=m;if(h!=="tool_call"&&h!=="tool_call_update")continue;let v=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${l}`,w=d.get(v);w||(w={entryId:l,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,w)),l<w.entryId&&(w.entryId=l),typeof y.name=="string"&&y.name.length>0?w.toolName=y.name:w.toolName==="(unnamed)"&&typeof y.title=="string"&&y.title.length>0&&(w.toolName=y.title);let b=y.rawInput;if(b&&typeof b=="object"&&!Array.isArray(b)&&Object.keys(b).length>0)for(let[A,C]of Object.entries(b))w.rawInput[A]===void 0&&(w.rawInput[A]=C);if(Array.isArray(y.locations))for(let A of y.locations){let C=A?.path;typeof C=="string"&&C.length>0&&!w.locations.includes(C)&&w.locations.push(C)}if(typeof y.status=="string"&&w.status==="in_progress"&&(w.status=y.status),g.recordedAt!==void 0&&w.timestamp===void 0&&(w.timestamp=String(g.recordedAt)),d.size>=u)break}let c=[...d.keys()].sort((l,g)=>d.get(l).entryId-d.get(g).entryId),f=[];for(let l of c){let g=d.get(l);if(t!==void 0&&g.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),y=["file_path","filePath","path"],v=!1;for(let w of y){let b=g.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){v=!0;break}}if(!v){for(let w of g.locations)if(w.toLowerCase().includes(h)){v=!0;break}}if(!v)continue}let m={};for(let[h,y]of Object.entries(g.rawInput))typeof y=="string"?m[h]=y.length>500?y.slice(0,497)+"\u2026":y:(typeof y=="number"||typeof y=="boolean")&&(m[h]=y);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 te({calls:f,truncated:p})}),e}var xl=1e4;function No(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let u=Cl(a),c=new Sl({sessionIdGenerator:()=>bl()});await u.connect(c);let f={server:u,transport:c};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(o,a){let d=at(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(d);if(u===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(d,async()=>{if(u.session!==void 0)return u.session;let p,l=new Promise(m=>{p=setTimeout(()=>m(void 0),xl)}),g=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),g===void 0)throw new Error("recall: session not ready");return g});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var An=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 Fl}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Ol}from"crypto";import{Server as Ml}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Rl,ListToolsRequestSchema as El}from"@modelcontextprotocol/sdk/types.js";function Ho(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new Ml({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(El,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let d=await s.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(Rl,async(a,d)=>{let u=a.params.name,c=d._meta?.progressToken??d.requestId,f=Tl(c,d.sendNotification);try{let p=await r(),l=await _l(e.connection,n,u,a.params.arguments??{},p);return $l(l,u)}catch(p){return $s(p instanceof Error?p.message:String(p))}finally{f()}}),i}var Pl=15e3;function Tl(n,e,t=Pl){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 _l(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function $l(n,e){if(n===null||typeof n!="object")return $s(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:$s(`extension ${e} omitted content array`)}function $s(n){return{content:[{type:"text",text:n}],isError:!0}}var Nl=1e4;function jo(n,e,t){let s=new Map;async function r(c){try{await c.transport.close()}catch{}try{await c.server.close()}catch{}}function i(c){for(let f of s.values()){let p=f.get(c);p!==void 0&&(f.delete(c),r(p))}}async function o(c,f){for(let[p,l]of s){if(e.lookup(p)?.session?.sessionId!==c)continue;let m=l.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(c=>{i(c)});async function a(c,f){let p=s.get(c);p===void 0&&(p=new Map,s.set(c,p),e.addDisposer(c,async()=>{let b=s.get(c);if(b!==void 0){s.delete(c);for(let A of b.values())await r(A)}}));let l=p.get(f);if(l!==void 0)return l.transport;let g=t.lookup(f);if(g===void 0)return;let v=Ho(f,g,async()=>{let b=e.lookup(c);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,C=new Promise(T=>{A=setTimeout(()=>T(void 0),Nl)}),x=await Promise.race([b.sessionReady.catch(()=>{}),C]);if(A!==void 0&&clearTimeout(A),x===void 0)throw new Error("session not ready");return x.sessionId},{peekSessionId:()=>e.lookup(c)?.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 C=A.tools;if(!Array.isArray(C))return;let x=[];for(let T of C){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),x.push(U)}return x}}),w=new Fl({sessionIdGenerator:()=>Ol()});return await v.connect(w),p.set(f,{server:v,transport:w}),w}async function d(c,f){let p=at(c);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=c.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(c.raw,f.raw,c.body)}let u={config:{skipAuth:!0}};return n.post("/mcp/:name",u,async(c,f)=>{await d(c,f)}),n.get("/mcp/:name",u,async(c,f)=>{await d(c,f)}),n.delete("/mcp/:name",u,async(c,f)=>{await d(c,f)}),{notifyToolListChanged:o}}async function zo(n,e){ql(n);let t=n.daemon.tls?await we.readFile(Z(n.daemon.tls.key)):void 0,s=n.daemon.tls?await we.readFile(Z(n.daemon.tls.cert)):void 0;await we.mkdir(S.home(),{recursive:!0});let{stream:r,fileStream:i}=await Dl(n.daemon.logLevel),o=Hl({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(jl,{options:{handleProtocols:Vs}}),Hn(O=>{o.log.info(O)}),Un(O=>{o.log.info(O)});let a=await dn.load(),d=new pn,u=new fn,c=new ln([new cn(e),new un(a),u]),f=qi({validator:c});o.addHook("onRequest",async(O,fe)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,fe)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let l=setInterval(()=>{d.sweepExpired()},300*1e3);l.unref();let g=new Ot(n,{onFetched:()=>{$i(g,v)}});Ss(O=>o.log.info(O));let m={info:O=>o.log.info(O),warn:O=>o.log.warn(O)},h=O=>xe.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Xs(n.compressToolContent);let y=new on,v=new Xt(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,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:n.npmRegistry,extensionCommands:y,defaultCwd:n.defaultCwd}),w=new sn(zs(n),void 0,{tokenRegistry:u}),b=new rn(Js(n),void 0,{tokenRegistry:u});wo(o,Y,Ni(n));let A=new kn,C=new An,x,T=()=>{if(x!==void 0)return x;let O=o.server.address();return x=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,x};ho(o,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:C,mcpTokenRegistry:A,getDaemonOrigin:T}),yo(o,g,v,{npmRegistry:n.npmRegistry}),vo(o,w),bo(o,b),Io(o,{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]}),xo(o,{store:a,rateLimiter:d}),Oo(o,A),No(o,A);let _=jo(o,A,C);_o(o,{validator:c,manager:v,defaultAgent:n.defaultAgent,processRegistry:u,onExtensionVersion:(O,fe)=>w.reportVersion(O,fe),onTransformerVersion:(O,fe)=>b.reportVersion(O,fe),transformers:b,extensionCommands:y,mcpTokenRegistry:A,extensionMcp:C,extensionMcpControls:_,getDaemonOrigin:T,registry:g});let U=!!n.daemon.tls;await o.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=o.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,B,J=n.daemon.host,ie=P;if(U&&t&&s){B=Ll({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:o.log});let O=B.address();O&&typeof O=="object"&&(ie=O.port)}await we.mkdir(S.home(),{recursive:!0}),await _i({pid:process.pid,host:J,port:ie,loopbackPort:P,startedAt:new Date().toISOString()});let Oe={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(Oe),b.setContext(Oe),await w.start(),await b.start();try{await v.reconcilePermissionFlags()}catch(O){o.log.warn(`permission flag reconcile failed: ${O.message}`)}v.resurrectPendingQueues().catch(O=>{o.log.warn(`queue replay scan failed: ${O.message}`)}),v.resumePendingCompactions().catch(O=>{o.log.warn(`compaction resume scan failed: ${O.message}`)}),v.resumePendingAgentSwaps().catch(O=>{o.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Tt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ns=Tt>0?Fi({registry:g,manager:v,intervalMs:Tt,logger:m}):void 0,Hs=n.daemon.sessionGcIntervalMinutes*60*1e3,ta=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,js=Hs>0?Oi({manager:v,intervalMs:Hs,maxAgeMs:ta,logger:m}):void 0;return{app:o,manager:v,registry:g,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:C,processRegistry:u,shutdown:async()=>{js&&js(),Ns&&Ns(),clearInterval(p),clearInterval(l);let O=async(fe,na)=>{try{await na()}catch(xn){o.log.warn(`shutdown step ${fe} failed: ${xn instanceof Error?xn.message:String(xn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>v.closeAll()),await O("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>v.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Hn(null),Un(null),Ss(null),B&&await O("tlsTerminator.close",()=>new Promise(fe=>B.close(()=>fe()))),await O("app.close",()=>o.close());try{Do.unlinkSync(S.pidFile())}catch{}await O("fileStream.flushSync",()=>i.flushSync())}}}var Uo=20;async function Ul(n,e){let t=dt.dirname(n),s=dt.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await we.readdir(t)}catch{return}let o=[];for(let d of i){let u=d.match(r);u&&o.push({name:d,n:Number(u[1])})}if(o.length<=e)return;o.sort((d,u)=>d.n-u.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(d=>we.unlink(dt.join(t,d.name))))}async function Dl(n){await Ul(S.logFile(),Uo);let e=await Bl({file:S.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Uo,removeOtherLogFiles:!0}}),t=Bo.destination(2);return{stream:Bo.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Ll(n){let e=qo.createServer(n.tlsOptions,t=>{let s=Lo.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),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 ql(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.`)}async function rf(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(ea(),Zo));n();let e=await Tn(),t=await Bs(),s=await zo(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
149
149
|
`);let r=1e4,i=!1,o=async()=>{i&&(process.stderr.write(`Second signal received; exiting immediately.
|
|
150
150
|
`),process.exit(1)),i=!0,process.stdout.write(`Shutting down...
|
|
151
151
|
`);let a=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${r}ms; forcing exit.
|
|
152
152
|
`),process.exit(1)},r);a.unref();try{await s.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
|
|
153
|
-
`)}clearTimeout(a),process.exit(0)};process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),process.on("SIGHUP",()=>{})}
|
|
153
|
+
`)}clearTimeout(a),process.exit(0)};process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),process.on("SIGHUP",()=>{})}rf().catch(n=>{process.stderr.write(`hydra-acp-daemon: ${n instanceof Error?n.message:String(n)}
|
|
154
154
|
`),process.exit(1)});
|