@hydra-acp/cli 0.1.154 → 0.1.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +352 -350
  2. package/dist/daemon.js +118 -116
  3. package/package.json +1 -1
package/dist/daemon.js CHANGED
@@ -1,44 +1,46 @@
1
1
  #!/usr/bin/env node
2
- var Yd=Object.defineProperty;var on=(s,e)=>()=>(s&&(e=s(s=0)),e);var Xd=(s,e)=>{for(var t in e)Yd(s,t,{get:e[t],enumerable:!0})};import*as L from"path";import*as ms from"os";function P(s){let e=ms.homedir();return e?s===e?"~":s.startsWith(e+"/")?"~"+s.slice(e.length):s:s}function ec(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function B(){let s=process.env[Zd];if(s&&s.length>0)return L.resolve(s);let e=ec();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 L.join(ms.homedir(),".hydra-acp")}var Zd,A,K=on(()=>{"use strict";Zd="HYDRA_ACP_HOME";A={home:B,config:()=>L.join(B(),"config.json"),authToken:()=>L.join(B(),"auth-token"),remotes:()=>L.join(B(),"remotes.json"),pidFile:()=>L.join(B(),"daemon.pid"),logFile:()=>L.join(B(),"daemon.log"),currentLogFile:()=>L.join(B(),"current.log"),registryCache:()=>L.join(B(),"registry.json"),themesDir:()=>L.join(B(),"themes"),ttySessionDir:()=>L.join(B(),"tty"),ttySessionFile:s=>L.join(B(),"tty",s),agentsDir:()=>L.join(B(),"agents"),agentLogFile:s=>L.join(B(),"agents","logs",`${s}.log`),agentInstallDir:(s,e,t)=>L.join(B(),"agents",e,s,t),agentNpmInstallDir:(s,e,t)=>L.join(B(),"agents",e,s,t,`node${process.versions.modules}`),sessionsDir:()=>L.join(B(),"sessions"),sessionDir:s=>L.join(B(),"sessions",s),sessionFile:s=>L.join(B(),"sessions",s,"meta.json"),historyFile:s=>L.join(B(),"sessions",s,"history.jsonl"),historyArchiveFile:(s,e)=>L.join(B(),"sessions",s,`history.jsonl.${e}`),toolsDir:s=>L.join(B(),"sessions",s,"tools"),toolBlobFile:(s,e)=>L.join(B(),"sessions",s,"tools",e),queueFile:s=>L.join(B(),"sessions",s,"queue.ndjson"),tombstonesDir:()=>L.join(B(),"sessions",".tombstones"),tombstoneAgentDir:s=>L.join(B(),"sessions",".tombstones",encodeURIComponent(s)),tombstoneFile:(s,e)=>L.join(B(),"sessions",".tombstones",encodeURIComponent(s),encodeURIComponent(e)),extensionsDir:()=>L.join(B(),"extensions"),extensionLogDir:s=>L.join(B(),"extensions",s),extensionLogFile:s=>L.join(B(),"extensions",s,"current.log"),extensionPidFile:s=>L.join(B(),"extensions",s,"extension.pid"),transformersDir:()=>L.join(B(),"transformers"),transformerLogDir:s=>L.join(B(),"transformers",s),transformerLogFile:s=>L.join(B(),"transformers",s,"current.log"),transformerPidFile:s=>L.join(B(),"transformers",s,"transformer.pid"),transformerState:(s,e)=>L.join(B(),"sessions",s,"transformer-state",e),tuiHistoryFile:s=>L.join(B(),"sessions",s,"prompt-history"),globalTuiHistoryFile:()=>L.join(B(),"prompt-history"),tuiLogFile:()=>L.join(B(),"tui.log"),shimWireLogFile:()=>L.join(B(),"shim-wire.log")}});import*as ne from"fs/promises";import*as Kr from"fs";import*as ke from"path";import{randomBytes as nc}from"crypto";async function fe(s,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
3
- `;await sc(s,r,t)}async function sc(s,e,t={}){let n=await rc(s),r=oc(n);await ne.mkdir(r,{recursive:!0});let o=`${n}.tmp-${process.pid}-${ic()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await ne.writeFile(o,e,i),await ne.rename(o,n)}catch(i){throw await ne.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{Kr.chmodSync(n,t.mode)}catch{}}async function rc(s){let e;try{e=await ne.lstat(s)}catch(r){if(r.code==="ENOENT")return s;throw r}if(!e.isSymbolicLink())return s;let t=await ne.readlink(s),n=ke.isAbsolute(t)?t:ke.resolve(ke.dirname(s),t);try{let r=await ne.realpath(ke.dirname(n));return ke.join(r,ke.basename(n))}catch(r){if(r.code==="ENOENT")return n;throw r}}async function ee(s){let e;try{e=await ne.readFile(s,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function oc(s){let e=s.lastIndexOf("/");return e<=0?".":s.slice(0,e)}function ic(){return nc(4).toString("hex")}var Oe=on(()=>{"use strict"});function gs(s,e){return`${s}:${e}`}var Dd=on(()=>{"use strict";K();Oe()});var Vd={};Xd(Vd,{_resetForTests:()=>eh,clearPin:()=>Vg,fetchPeerFingerprint:()=>Kg,formatFingerprint:()=>Ud,getPin:()=>Qg,installGlobalTlsTrust:()=>Yg,loadPinsFromStore:()=>Gg,setPin:()=>Bd,sha256Hex:()=>zr,wsTlsOptions:()=>Zg});import{createHash as Bg}from"crypto";import*as Ld from"tls";import{Agent as Ug,Dispatcher as Wg,buildConnector as qg,getGlobalDispatcher as zg,setGlobalDispatcher as Jg}from"undici";function Bd(s,e,t){Ze.set(gs(s,e),Wd(t))}function Vg(s,e){Ze.delete(gs(s,e))}function Qg(s,e){return Ze.get(gs(s,e))}function Gg(s){Ze.clear();for(let e of s.list())e.entry.pinnedFingerprint&&Bd(e.host,e.port,e.entry.pinnedFingerprint)}async function Kg(s,e,t={}){let n=t.timeoutMs??1e4;return new Promise((r,o)=>{let i=Ld.connect({host:s,port:e,servername:s,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(c,l)=>{if(!a){a=!0,clearTimeout(u);try{i.destroy()}catch{}c?o(c):l&&r(l)}},u=setTimeout(()=>{d(new Error(`TLS connect to ${s}:${e} timed out`))},n);i.once("secureConnect",()=>{let c=i.getPeerCertificate(!1);if(!c||!c.raw){d(new Error(`${s}:${e} did not present a TLS certificate`));return}d(null,zr(c.raw))}),i.once("error",c=>d(c))})}function zr(s){return Bg("sha256").update(s).digest("hex")}function Ud(s){let e=Wd(s),t=e.match(/.{2}/g);return t?t.join(":"):e}function Wd(s){return s.replace(/:/g,"").toLowerCase()}function Yg(){if(qr)return;qr=!0;let s=zg(),e=new Ug({connect:qg({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(n,r)=>zd(n,r)})}),t=new Wg;t.dispatch=(n,r)=>{let o=Xg(n.origin);return(o&&qd(o)?e:s).dispatch(n,r)},t.close=(()=>Promise.all([e.close(),s.close()]).then(()=>{})),t.destroy=(n=>Promise.all([e.destroy(n??null),s.destroy(n??null)]).then(()=>{})),Jg(t)}function Xg(s){if(!s)return null;try{return new URL(String(s)).hostname}catch{return null}}function qd(s){for(let e of Ze.keys())if(Jd(e)?.host===s)return!0;return!1}function zd(s,e){if(!e||!e.raw)return new Error(`TLS peer ${s} did not present a certificate`);let t=zr(e.raw);for(let[n,r]of Ze.entries()){let o=Jd(n);if(o&&o.host===s&&r===t)return}return new Error(`TLS pin mismatch for ${s} (cert sha256 ${Ud(t)})`)}function Jd(s){let e=s.lastIndexOf(":");if(e<0)return null;let t=s.slice(0,e),n=Number(s.slice(e+1));return Number.isInteger(n)?{host:t,port:n}:null}function Zg(s){return qd(s)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>zd(e,t)}:{autoSelectFamily:!0}}function eh(){Ze.clear(),qr=!1}var Ze,qr,Qd=on(()=>{"use strict";Dd();Ze=new Map,qr=!1});K();import*as Be from"fs/promises";import{homedir as ks}from"os";import{z as I}from"zod";K();import*as tt from"fs/promises";function ys(){let s=new Uint8Array(32);crypto.getRandomValues(s);let e="";for(let t of s)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function tc(){try{let e=(await tt.readFile(A.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(s){if(s.code==="ENOENT")return;throw s}}async function ws(s){await tt.mkdir(A.home(),{recursive:!0}),await tt.writeFile(A.authToken(),s+`
4
- `,{encoding:"utf8",mode:384})}async function Gr(){let s=await tc();if(s)return s;let e=ys();return await ws(e),process.stderr.write(`hydra-acp: initialized ${A.authToken()} with a fresh service token.
5
- `),e}Oe();var Zr="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",ac=I.object({cert:I.string(),key:I.string()}),eo=55514,dc=I.object({host:I.string().default("127.0.0.1"),port:I.number().int().positive().default(eo),logLevel:I.enum(["debug","info","warn","error"]).default("info"),tls:ac.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),scrubEnv:I.array(I.string()).default([]),sessionGcIntervalMinutes:I.number().nonnegative().default(60),sessionGcMaxAgeDays:I.number().positive().default(2)}),cc=I.object({url:I.string().url().default(Zr),ttlHours:I.number().positive().default(24),pinned:I.boolean().default(!1)}),uc=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()}),lc=I.object({packageSpec:I.string().optional()}),fc=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"]),pc=I.union([I.string(),I.object({field:I.string().optional(),text:I.string().optional(),maxWidth:I.number().int().positive().optional(),minWidth:I.number().int().nonnegative().optional(),priority:I.number().optional(),prefix:I.string().optional(),suffix:I.string().optional(),separator:I.string().optional(),style:I.string().optional(),onClick:I.string().optional(),onDoubleClick:I.string().optional()}).strict()]),Yr=I.array(pc);function bs(s,e){return I.object({left:Yr.default(s),right:Yr.default(e)}).default({})}var gc=["status",{field:"elapsed",separator:" "},"sessionId","queued","scroll"],hc=["usage"],mc=[],yc=["helpHint"],wc=["cwd","title"],kc=["agentModel"],bc=I.object({composer:I.object({top:bs(gc,hc),bottom:bs(mc,yc),hintTurns:I.number().int().nonnegative().nullable().default(3)}).default({}),sessionbar:bs(wc,kc),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(),openFileInTerminal:I.boolean().optional(),logMaxBytes:I.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:I.number().int().positive().default(32),progressIndicator:I.boolean().default(!0),launcherModeWhenHosted:I.boolean().default(!1),skipPermissions:I.boolean().default(!1),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","sessions","context","queue","todo","files","git","resources","info","tools"])}).default({}),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(fc,I.object({command:I.union([I.string(),I.array(I.string())])})).default({}),theme:I.union([I.string(),I.record(I.string(),I.unknown())]).optional(),themeBackground:I.string().optional()}),Xr=I.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),vc=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)}),Sc=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)}),Ic=I.object({daemon:dc.default({}),registry:cc.default({url:Zr,ttlHours:24,pinned:!1}),agents:I.record(I.string(),uc).default({}),agentOverrides:I.record(I.string(),lc).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(2e5),idleBeforePromptMs:I.number().int().nonnegative().default(3e5),modelContextWindows:I.record(I.string(),I.number().int().positive()).default({})}).default({}),defaultCwd:I.string().default("~"),disableWorkspaceSnapshots:I.boolean().optional(),compressToolContent:I.boolean().default(!0),sessionListColdLimit:I.number().int().nonnegative().default(20),extensions:I.record(Xr,vc).default({}),transformers:I.record(Xr,Sc).default({}),defaultTransformers:I.array(I.string()).default([]),npmRegistry:I.string().url().optional(),tui:bc.default({})});function to(s){return Object.entries(s.extensions).map(([e,t])=>({name:e,...t}))}function no(s){return Object.entries(s.transformers).map(([e,t])=>({name:e,...t}))}async function so(){return await Ac(),await ee(A.config())??{}}async function Ac(){let s;try{s=await Be.lstat(A.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(s.isSymbolicLink())try{await Be.stat(A.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Be.readlink(A.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${A.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 Cc(){let s=await so(),e=s.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let n=!1;try{await Be.access(A.authToken()),n=!0}catch(r){if(r.code!=="ENOENT")throw r}if(n)throw new Error(`Auth token present in both ${A.authToken()} and ${A.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await ws(t),delete e.authToken,Object.keys(e).length===0&&delete s.daemon,await fe(A.config(),s,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${A.config()} to ${A.authToken()}.
6
- `)}async function vs(){return await Cc(),Ic.parse(await so())}function de(s){return s==="~"||s==="$HOME"?ks():s.startsWith("~/")?ks()+s.slice(1):s.startsWith("$HOME/")?ks()+s.slice(5):s}import*as Nd from"fs";import*as Ne from"fs/promises";import*as Od from"net";import*as Mt from"path";import*as Hd from"tls";import Fg from"fastify";import Ng from"@fastify/websocket";var ro="acp.v1";function oo(s,e){return s.has(ro)?ro:!1}import $d from"pino";import Og from"pino-roll";var xc={herdr:["HERDR_PANE_ID","HERDR_TAB_ID","HERDR_WORKSPACE_ID","HERDR_STARTUP_CWD"],tmux:["TMUX_PANE"],zellij:["ZELLIJ_PANE_ID","ZELLIJ_SESSION_NAME"],wezterm:["WEZTERM_PANE"],kitty:["KITTY_WINDOW_ID"],screen:["STY"],iterm2:["ITERM_SESSION_ID"],hydra:["HYDRA_TAB_LABEL"]},io="HYDRA_ACP_SESSION",Rc=[io],Ec=[...Object.values(xc).flat(),...Rc];function an(s,e){return s?{...e??{},[io]:s}:e}var ao=[];function co(s){ao=s?[...s]:[]}function Pc(s,e){return e.endsWith("*")?s.startsWith(e.slice(0,-1)):s===e}function Mc(){return[...Ec,...ao]}function dn(s=process.env){let e=Mc(),t={};for(let[n,r]of Object.entries(s))r!==void 0&&(e.some(o=>Pc(n,o))||(t[n]=r));return t}K();import*as se from"fs/promises";import{createHash as Tc}from"crypto";import{gzip as _c,gunzip as $c}from"zlib";import{promisify as uo}from"util";var lo=uo(_c),Fc=uo($c),fo=/^[A-Za-z0-9_-]+$/,Nc=/^[a-f0-9]{64}$/,Ss=!0;function po(s){Ss=s}function cn(s,e){return fo.test(s)?e===void 0||Nc.test(e):!1}function un(s,e){return`${A.toolBlobFile(s,e)}.gz`}async function Is(s,e){if(!cn(s))return null;let t=Tc("sha256").update(e,"utf8").digest("hex"),n=un(s,t),r=A.toolBlobFile(s,t);for(let a of[n,r])try{return await se.access(a),t}catch{}await se.mkdir(A.toolsDir(s),{recursive:!0});let o=Ss?n:r,i=Ss?await lo(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await se.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function Tt(s,e){if(!cn(s,e))return null;try{let t=await se.readFile(un(s,e));return(await Fc(t)).toString("utf8")}catch{}try{return await se.readFile(A.toolBlobFile(s,e),"utf8")}catch{return null}}async function go(s,e){if(!cn(s,e))return null;try{return await se.readFile(un(s,e))}catch{}try{let t=await se.readFile(A.toolBlobFile(s,e));return await lo(t)}catch{return null}}async function ho(s,e,t){if(!cn(s,e))return;let n=un(s,e);try{await se.access(n);return}catch{}await se.mkdir(A.toolsDir(s),{recursive:!0}),await se.writeFile(n,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function mo(s){fo.test(s)&&await se.rm(A.toolsDir(s),{recursive:!0,force:!0}).catch(()=>{})}K();import*as Ro from"fs/promises";import*as fn from"path";import{z as j}from"zod";Oe();K();import*as wo from"fs";import*as ce from"fs/promises";import*as Ue from"path";import{spawn as ko}from"child_process";import{Readable as Oc}from"stream";function Ce(){let s=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(!(!s||!e))return`${s}-${e}`}function xs(s,e=Ce()){if(e)return s[e]}var nt=s=>{process.stderr.write(s+`
7
- `)};function Rs(s){nt=s??(e=>process.stderr.write(e+`
8
- `))}async function bo(s){if(!s.target.archive)throw new Error(`Agent ${s.agentId} has no archive URL for ${Ce()??"this platform"}`);if(!s.target.cmd)throw new Error(`Agent ${s.agentId} has no cmd in its binary target`);let e=Ce();if(!e)throw new Error(`Agent ${s.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=A.agentInstallDir(s.agentId,e,s.version),n=Ue.resolve(t,s.target.cmd);if(await Cs(n))return n;if(await Hc({agentId:s.agentId,version:s.version,archiveUrl:s.target.archive,installDir:t,onProgress:s.onProgress}),!await Cs(n))throw new Error(`Agent ${s.agentId}: extracted archive did not contain ${s.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await ce.chmod(n,493).catch(()=>{}),n}async function Hc(s){await ce.mkdir(Ue.dirname(s.installDir),{recursive:!0});let e=await ce.mkdtemp(`${s.installDir}.partial-`);try{nt(`hydra-acp: downloading ${s.agentId} from ${s.archiveUrl}`);let t=await jc({url:s.archiveUrl,dir:e,agentId:s.agentId,version:s.version,onProgress:s.onProgress});nt(`hydra-acp: extracting ${s.agentId}`),st(s.onProgress,{phase:"extract",agentId:s.agentId,version:s.version}),await Lc(t,e),await ce.unlink(t).catch(()=>{});try{await ce.rename(e,s.installDir)}catch(n){let r=n;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Cs(s.installDir)){await ce.rm(e,{recursive:!0,force:!0}).catch(()=>{}),st(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version});return}throw n}nt(`hydra-acp: installed ${s.agentId} to ${s.installDir}`),st(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version})}catch(t){throw await ce.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function st(s,e){if(s)try{s(e)}catch{}}async function jc(s){let e=Dc(s.url),t=Ue.join(s.dir,e),n=await fetch(s.url,{redirect:"follow"});if(!n.ok||!n.body)throw new Error(`Failed to download ${s.url}: HTTP ${n.status} ${n.statusText}`);let r=Number(n.headers.get("content-length")??"0"),o=wo.createWriteStream(t),i=Oc.fromWeb(n.body);st(s.onProgress,{phase:"download_start",agentId:s.agentId,version:s.version,totalBytes:r});let a=0,d=Date.now(),u=0,c=2e3,l=150;return i.on("data",p=>{a+=p.length;let f=Date.now();f-u>=l&&(u=f,st(s.onProgress,{phase:"download_progress",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r})),f-d>=c&&(d=f,nt(yo(s.agentId,a,r)))}),await new Promise((p,f)=>{i.on("error",f),o.on("error",f),o.on("finish",()=>p()),i.pipe(o)}),nt(yo(s.agentId,a,r,!0)),st(s.onProgress,{phase:"download_done",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r}),t}function yo(s,e,t,n=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${n?"downloaded":"downloading"} ${s} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${n?"downloaded":"downloading"} ${s} ${r} MB`}function Dc(s){let e=new URL(s);return Ue.posix.basename(e.pathname)||"archive"}async function Lc(s,e){let t=s.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await As("tar",["-xf",s,"-C",e]);return}if(t.endsWith(".zip")){if(await Bc("unzip")){await As("unzip",["-q",s,"-d",e]);return}await As("tar",["-xf",s,"-C",e]);return}throw new Error(`Unsupported archive format: ${s}`)}function As(s,e){return new Promise((t,n)=>{let r=ko(s,e,{stdio:["ignore","ignore","inherit"]});r.on("error",n),r.on("exit",(o,i)=>{if(o===0){t();return}n(new Error(`${s} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function Bc(s){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",n=ko(t,[s],{stdio:"ignore"});n.on("error",()=>e(!1)),n.on("exit",r=>e(r===0))})}async function Cs(s){try{return await ce.access(s),!0}catch{return!1}}K();import*as pe from"fs/promises";import*as xe from"path";import{spawn as Uc}from"child_process";var Ps=s=>{process.stderr.write(s+`
2
+ var Zd=Object.defineProperty;var on=(s,e)=>()=>(s&&(e=s(s=0)),e);var ec=(s,e)=>{for(var t in e)Zd(s,t,{get:e[t],enumerable:!0})};import*as D from"path";import*as hs from"os";function T(s){let e=hs.homedir();return e?s===e?"~":s.startsWith(e+"/")?"~"+s.slice(e.length):s:s}function nc(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function B(){let s=process.env[tc];if(s&&s.length>0)return D.resolve(s);let e=nc();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 D.join(hs.homedir(),".hydra-acp")}var tc,C,K=on(()=>{"use strict";tc="HYDRA_ACP_HOME";C={home:B,config:()=>D.join(B(),"config.json"),authToken:()=>D.join(B(),"auth-token"),remotes:()=>D.join(B(),"remotes.json"),pidFile:()=>D.join(B(),"daemon.pid"),logFile:()=>D.join(B(),"daemon.log"),currentLogFile:()=>D.join(B(),"current.log"),registryCache:()=>D.join(B(),"registry.json"),themesDir:()=>D.join(B(),"themes"),ttySessionDir:()=>D.join(B(),"tty"),ttySessionFile:s=>D.join(B(),"tty",s),agentsDir:()=>D.join(B(),"agents"),agentLogFile:s=>D.join(B(),"agents","logs",`${s}.log`),agentInstallDir:(s,e,t)=>D.join(B(),"agents",e,s,t),agentNpmInstallDir:(s,e,t)=>D.join(B(),"agents",e,s,t,`node${process.versions.modules}`),sessionsDir:()=>D.join(B(),"sessions"),sessionDir:s=>D.join(B(),"sessions",s),sessionFile:s=>D.join(B(),"sessions",s,"meta.json"),historyFile:s=>D.join(B(),"sessions",s,"history.jsonl"),historyArchiveFile:(s,e)=>D.join(B(),"sessions",s,`history.jsonl.${e}`),toolsDir:s=>D.join(B(),"sessions",s,"tools"),toolBlobFile:(s,e)=>D.join(B(),"sessions",s,"tools",e),queueFile:s=>D.join(B(),"sessions",s,"queue.ndjson"),tombstonesDir:()=>D.join(B(),"sessions",".tombstones"),tombstoneAgentDir:s=>D.join(B(),"sessions",".tombstones",encodeURIComponent(s)),tombstoneFile:(s,e)=>D.join(B(),"sessions",".tombstones",encodeURIComponent(s),encodeURIComponent(e)),extensionsDir:()=>D.join(B(),"extensions"),extensionLogDir:s=>D.join(B(),"extensions",s),extensionLogFile:s=>D.join(B(),"extensions",s,"current.log"),extensionPidFile:s=>D.join(B(),"extensions",s,"extension.pid"),transformersDir:()=>D.join(B(),"transformers"),transformerLogDir:s=>D.join(B(),"transformers",s),transformerLogFile:s=>D.join(B(),"transformers",s,"current.log"),transformerPidFile:s=>D.join(B(),"transformers",s,"transformer.pid"),transformerState:(s,e)=>D.join(B(),"sessions",s,"transformer-state",e),tuiHistoryFile:s=>D.join(B(),"sessions",s,"prompt-history"),globalTuiHistoryFile:()=>D.join(B(),"prompt-history"),tuiLogFile:()=>D.join(B(),"tui.log"),shimWireLogFile:()=>D.join(B(),"shim-wire.log")}});import*as ne from"fs/promises";import*as Yr from"fs";import*as be from"path";import{randomBytes as rc}from"crypto";async function fe(s,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
3
+ `;await oc(s,r,t)}async function oc(s,e,t={}){let n=await ic(s),r=ac(n);await ne.mkdir(r,{recursive:!0});let o=`${n}.tmp-${process.pid}-${dc()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await ne.writeFile(o,e,i),await ne.rename(o,n)}catch(i){throw await ne.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{Yr.chmodSync(n,t.mode)}catch{}}async function ic(s){let e;try{e=await ne.lstat(s)}catch(r){if(r.code==="ENOENT")return s;throw r}if(!e.isSymbolicLink())return s;let t=await ne.readlink(s),n=be.isAbsolute(t)?t:be.resolve(be.dirname(s),t);try{let r=await ne.realpath(be.dirname(n));return be.join(r,be.basename(n))}catch(r){if(r.code==="ENOENT")return n;throw r}}async function ee(s){let e;try{e=await ne.readFile(s,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function ac(s){let e=s.lastIndexOf("/");return e<=0?".":s.slice(0,e)}function dc(){return rc(4).toString("hex")}var Oe=on(()=>{"use strict"});function gs(s,e){return`${s}:${e}`}var Bd=on(()=>{"use strict";K();Oe()});var Qd={};ec(Qd,{_resetForTests:()=>am,clearPin:()=>em,fetchPeerFingerprint:()=>sm,formatFingerprint:()=>qd,getPin:()=>tm,installGlobalTlsTrust:()=>rm,loadPinsFromStore:()=>nm,setPin:()=>Wd,sha256Hex:()=>Jr,wsTlsOptions:()=>im});import{createHash as Gg}from"crypto";import*as Ld from"tls";import{Agent as Qg,Dispatcher as Kg,buildConnector as Yg,getGlobalDispatcher as Xg,setGlobalDispatcher as Zg}from"undici";function Wd(s,e,t){et.set(gs(s,e),zd(t))}function em(s,e){et.delete(gs(s,e))}function tm(s,e){return et.get(gs(s,e))}function nm(s){et.clear();for(let e of s.list())e.entry.pinnedFingerprint&&Wd(e.host,e.port,e.entry.pinnedFingerprint)}async function sm(s,e,t={}){let n=t.timeoutMs??1e4;return new Promise((r,o)=>{let i=Ld.connect({host:s,port:e,servername:s,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(u,l)=>{if(!a){a=!0,clearTimeout(c);try{i.destroy()}catch{}u?o(u):l&&r(l)}},c=setTimeout(()=>{d(new Error(`TLS connect to ${s}:${e} timed out`))},n);i.once("secureConnect",()=>{let u=i.getPeerCertificate(!1);if(!u||!u.raw){d(new Error(`${s}:${e} did not present a TLS certificate`));return}d(null,Jr(u.raw))}),i.once("error",u=>d(u))})}function Jr(s){return Gg("sha256").update(s).digest("hex")}function qd(s){let e=zd(s),t=e.match(/.{2}/g);return t?t.join(":"):e}function zd(s){return s.replace(/:/g,"").toLowerCase()}function rm(){if(zr)return;zr=!0;let s=Xg(),e=new Qg({connect:Yg({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(n,r)=>Vd(n,r)})}),t=new Kg;t.dispatch=(n,r)=>{let o=om(n.origin);return(o&&Jd(o)?e:s).dispatch(n,r)},t.close=(()=>Promise.all([e.close(),s.close()]).then(()=>{})),t.destroy=(n=>Promise.all([e.destroy(n??null),s.destroy(n??null)]).then(()=>{})),Zg(t)}function om(s){if(!s)return null;try{return new URL(String(s)).hostname}catch{return null}}function Jd(s){for(let e of et.keys())if(Gd(e)?.host===s)return!0;return!1}function Vd(s,e){if(!e||!e.raw)return new Error(`TLS peer ${s} did not present a certificate`);let t=Jr(e.raw);for(let[n,r]of et.entries()){let o=Gd(n);if(o&&o.host===s&&r===t)return}return new Error(`TLS pin mismatch for ${s} (cert sha256 ${qd(t)})`)}function Gd(s){let e=s.lastIndexOf(":");if(e<0)return null;let t=s.slice(0,e),n=Number(s.slice(e+1));return Number.isInteger(n)?{host:t,port:n}:null}function im(s){return Jd(s)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>Vd(e,t)}:{autoSelectFamily:!0}}function am(){et.clear(),zr=!1}var et,zr,Kd=on(()=>{"use strict";Bd();et=new Map,zr=!1});K();import*as Be from"fs/promises";import{homedir as ks}from"os";import{z as v}from"zod";K();import*as nt from"fs/promises";function ys(){let s=new Uint8Array(32);crypto.getRandomValues(s);let e="";for(let t of s)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function sc(){try{let e=(await nt.readFile(C.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(s){if(s.code==="ENOENT")return;throw s}}async function ws(s){await nt.mkdir(C.home(),{recursive:!0}),await nt.writeFile(C.authToken(),s+`
4
+ `,{encoding:"utf8",mode:384})}async function Kr(){let s=await sc();if(s)return s;let e=ys();return await ws(e),process.stderr.write(`hydra-acp: initialized ${C.authToken()} with a fresh service token.
5
+ `),e}Oe();var eo="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",cc=v.object({cert:v.string(),key:v.string()}),to=55514,uc=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(to),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:cc.optional(),sessionIdleTimeoutSeconds:v.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:v.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:v.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:v.number().int().positive().default(10),agentStderrTailBytes:v.number().int().positive().default(4096),publicHost:v.string().optional(),agentSyncIntervalMinutes:v.number().nonnegative().default(60),scrubEnv:v.array(v.string()).default([]),sessionGcIntervalMinutes:v.number().nonnegative().default(60),sessionGcMaxAgeDays:v.number().positive().default(2)}),lc=v.object({url:v.string().url().default(eo),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),pc=v.object({name:v.string().optional(),description:v.string().optional(),command:v.string().optional(),args:v.array(v.string()).optional(),env:v.record(v.string()).optional()}),fc=v.object({packageSpec:v.string().optional()}),gc=v.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"]),mc=v.union([v.string(),v.object({field:v.string().optional(),text:v.string().optional(),maxWidth:v.number().int().positive().optional(),minWidth:v.number().int().nonnegative().optional(),priority:v.number().optional(),prefix:v.string().optional(),suffix:v.string().optional(),separator:v.string().optional(),style:v.string().optional(),onClick:v.string().optional(),onDoubleClick:v.string().optional()}).strict()]),Xr=v.array(mc);function bs(s,e){return v.object({left:Xr.default(s),right:Xr.default(e)}).default({})}var hc=["status",{field:"elapsed",separator:" "},"sessionId","queued","scroll"],yc=["usage"],wc=[],kc=["helpHint"],bc=["cwd","title"],vc=["agentModel"],Sc=v.object({composer:v.object({top:bs(hc,yc),bottom:bs(wc,kc),hintTurns:v.number().int().nonnegative().nullable().default(3)}).default({}),sessionbar:bs(bc,vc),repaintThrottleMs:v.number().int().nonnegative().default(1e3),maxScrollbackLines:v.number().int().positive().default(1e4),mouse:v.boolean().default(!0),inAppSelection:v.boolean().optional(),selectionClipboard:v.enum(["primary","clipboard","both"]).default("both"),openFileCommand:v.union([v.string(),v.array(v.string())]).optional(),openFileInTerminal:v.boolean().optional(),logMaxBytes:v.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:v.number().int().positive().default(32),progressIndicator:v.boolean().default(!0),launcherModeWhenHosted:v.boolean().default(!1),skipPermissions:v.boolean().default(!1),defaultEnterAction:v.enum(["enqueue","amend"]).default("amend"),showThoughts:v.boolean().default(!0),ambiguousWidth:v.enum(["auto","narrow","wide"]).default("auto"),toolContent:v.enum(["inline","references"]).default("references"),diffContextLines:v.number().int().min(0).default(3),promptHistoryMaxEntries:v.number().int().positive().default(2e3),maxToolItems:v.number().int().nonnegative().default(5),maxPlanItems:v.number().int().nonnegative().default(5),sidebar:v.object({enabled:v.boolean().default(!1),width:v.number().int().positive().optional(),border:v.enum(["none","rule","frame"]).default("frame"),gadgets:v.array(v.string()).default(["activity","sessions","context","queue","todo","files","git","resources","info","tools"])}).default({}),showFileUpdates:v.enum(["none","edit","diff"]).default("edit"),sessionColumns:v.array(v.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:v.record(gc,v.object({command:v.union([v.string(),v.array(v.string())])})).default({}),theme:v.union([v.string(),v.record(v.string(),v.unknown())]).optional(),themeBackground:v.string().optional()}),Zr=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Ic=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),Ac=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),Cc=v.object({daemon:uc.default({}),registry:lc.default({url:eo,ttlHours:24,pinned:!1}),agents:v.record(v.string(),pc).default({}),agentOverrides:v.record(v.string(),fc).default({}),defaultAgent:v.string().default("opencode"),defaultModels:v.record(v.string(),v.string()).default({}),synopsisAgent:v.string().optional(),synopsisModel:v.string().optional(),compaction:v.object({agent:v.string().optional(),model:v.string().optional(),tailK:v.number().int().nonnegative().default(20),maxIterations:v.number().int().positive().default(3),contextFraction:v.number().min(0).max(1).default(.5),hardCeilingFraction:v.number().min(0).max(1).default(.85),absoluteFallback:v.number().int().positive().default(2e5),idleBeforePromptMs:v.number().int().nonnegative().default(3e5),modelContextWindows:v.record(v.string(),v.number().int().positive()).default({})}).default({}),defaultCwd:v.string().default("~"),disableWorkspaceSnapshots:v.boolean().optional(),compressToolContent:v.boolean().default(!0),sessionListColdLimit:v.number().int().nonnegative().default(20),extensions:v.record(Zr,Ic).default({}),transformers:v.record(Zr,Ac).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Sc.default({})});function no(s){return Object.entries(s.extensions).map(([e,t])=>({name:e,...t}))}function so(s){return Object.entries(s.transformers).map(([e,t])=>({name:e,...t}))}async function ro(){return await xc(),await ee(C.config())??{}}async function xc(){let s;try{s=await Be.lstat(C.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(s.isSymbolicLink())try{await Be.stat(C.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Be.readlink(C.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${C.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 Rc(){let s=await ro(),e=s.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let n=!1;try{await Be.access(C.authToken()),n=!0}catch(r){if(r.code!=="ENOENT")throw r}if(n)throw new Error(`Auth token present in both ${C.authToken()} and ${C.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await ws(t),delete e.authToken,Object.keys(e).length===0&&delete s.daemon,await fe(C.config(),s,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${C.config()} to ${C.authToken()}.
6
+ `)}async function vs(){return await Rc(),Cc.parse(await ro())}function de(s){return s==="~"||s==="$HOME"?ks():s.startsWith("~/")?ks()+s.slice(1):s.startsWith("$HOME/")?ks()+s.slice(5):s}import*as Hd from"fs";import*as Ne from"fs/promises";import*as jd from"net";import*as Mt from"path";import*as Ud from"tls";import Bg from"fastify";import Lg from"@fastify/websocket";var oo="acp.v1";function io(s,e){return s.has(oo)?oo:!1}import Nd from"pino";import Wg from"pino-roll";var Ec={herdr:["HERDR_PANE_ID","HERDR_TAB_ID","HERDR_WORKSPACE_ID","HERDR_STARTUP_CWD"],tmux:["TMUX_PANE"],zellij:["ZELLIJ_PANE_ID","ZELLIJ_SESSION_NAME"],wezterm:["WEZTERM_PANE"],kitty:["KITTY_WINDOW_ID"],screen:["STY"],iterm2:["ITERM_SESSION_ID"],hydra:["HYDRA_TAB_LABEL"]},ao="HYDRA_ACP_SESSION",Pc=[ao],Mc=[...Object.values(Ec).flat(),...Pc];function an(s,e){return s?{...e??{},[ao]:s}:e}var co=[];function uo(s){co=s?[...s]:[]}function Tc(s,e){return e.endsWith("*")?s.startsWith(e.slice(0,-1)):s===e}function _c(){return[...Mc,...co]}function dn(s=process.env){let e=_c(),t={};for(let[n,r]of Object.entries(s))r!==void 0&&(e.some(o=>Tc(n,o))||(t[n]=r));return t}K();import*as se from"fs/promises";import{createHash as $c}from"crypto";import{gzip as Fc,gunzip as Nc}from"zlib";import{promisify as lo}from"util";var po=lo(Fc),Oc=lo(Nc),fo=/^[A-Za-z0-9_-]+$/,Hc=/^[a-f0-9]{64}$/,Ss=!0;function go(s){Ss=s}function cn(s,e){return fo.test(s)?e===void 0||Hc.test(e):!1}function un(s,e){return`${C.toolBlobFile(s,e)}.gz`}async function Is(s,e){if(!cn(s))return null;let t=$c("sha256").update(e,"utf8").digest("hex"),n=un(s,t),r=C.toolBlobFile(s,t);for(let a of[n,r])try{return await se.access(a),t}catch{}await se.mkdir(C.toolsDir(s),{recursive:!0});let o=Ss?n:r,i=Ss?await po(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await se.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function Tt(s,e){if(!cn(s,e))return null;try{let t=await se.readFile(un(s,e));return(await Oc(t)).toString("utf8")}catch{}try{return await se.readFile(C.toolBlobFile(s,e),"utf8")}catch{return null}}async function mo(s,e){if(!cn(s,e))return null;try{return await se.readFile(un(s,e))}catch{}try{let t=await se.readFile(C.toolBlobFile(s,e));return await po(t)}catch{return null}}async function ho(s,e,t){if(!cn(s,e))return;let n=un(s,e);try{await se.access(n);return}catch{}await se.mkdir(C.toolsDir(s),{recursive:!0}),await se.writeFile(n,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function yo(s){fo.test(s)&&await se.rm(C.toolsDir(s),{recursive:!0,force:!0}).catch(()=>{})}K();import*as Eo from"fs/promises";import*as pn from"path";import{z as j}from"zod";Oe();K();import*as ko from"fs";import*as ce from"fs/promises";import*as Le from"path";import{spawn as bo}from"child_process";import{Readable as jc}from"stream";function Ce(){let s=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(!(!s||!e))return`${s}-${e}`}function xs(s,e=Ce()){if(e)return s[e]}var st=s=>{process.stderr.write(s+`
7
+ `)};function Rs(s){st=s??(e=>process.stderr.write(e+`
8
+ `))}async function vo(s){if(!s.target.archive)throw new Error(`Agent ${s.agentId} has no archive URL for ${Ce()??"this platform"}`);if(!s.target.cmd)throw new Error(`Agent ${s.agentId} has no cmd in its binary target`);let e=Ce();if(!e)throw new Error(`Agent ${s.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=C.agentInstallDir(s.agentId,e,s.version),n=Le.resolve(t,s.target.cmd);if(await Cs(n))return n;if(await Uc({agentId:s.agentId,version:s.version,archiveUrl:s.target.archive,installDir:t,onProgress:s.onProgress}),!await Cs(n))throw new Error(`Agent ${s.agentId}: extracted archive did not contain ${s.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await ce.chmod(n,493).catch(()=>{}),n}async function Uc(s){await ce.mkdir(Le.dirname(s.installDir),{recursive:!0});let e=await ce.mkdtemp(`${s.installDir}.partial-`);try{st(`hydra-acp: downloading ${s.agentId} from ${s.archiveUrl}`);let t=await Dc({url:s.archiveUrl,dir:e,agentId:s.agentId,version:s.version,onProgress:s.onProgress});st(`hydra-acp: extracting ${s.agentId}`),rt(s.onProgress,{phase:"extract",agentId:s.agentId,version:s.version}),await Lc(t,e),await ce.unlink(t).catch(()=>{});try{await ce.rename(e,s.installDir)}catch(n){let r=n;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Cs(s.installDir)){await ce.rm(e,{recursive:!0,force:!0}).catch(()=>{}),rt(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version});return}throw n}st(`hydra-acp: installed ${s.agentId} to ${s.installDir}`),rt(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version})}catch(t){throw await ce.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function rt(s,e){if(s)try{s(e)}catch{}}async function Dc(s){let e=Bc(s.url),t=Le.join(s.dir,e),n=await fetch(s.url,{redirect:"follow"});if(!n.ok||!n.body)throw new Error(`Failed to download ${s.url}: HTTP ${n.status} ${n.statusText}`);let r=Number(n.headers.get("content-length")??"0"),o=ko.createWriteStream(t),i=jc.fromWeb(n.body);rt(s.onProgress,{phase:"download_start",agentId:s.agentId,version:s.version,totalBytes:r});let a=0,d=Date.now(),c=0,u=2e3,l=150;return i.on("data",f=>{a+=f.length;let p=Date.now();p-c>=l&&(c=p,rt(s.onProgress,{phase:"download_progress",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r})),p-d>=u&&(d=p,st(wo(s.agentId,a,r)))}),await new Promise((f,p)=>{i.on("error",p),o.on("error",p),o.on("finish",()=>f()),i.pipe(o)}),st(wo(s.agentId,a,r,!0)),rt(s.onProgress,{phase:"download_done",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r}),t}function wo(s,e,t,n=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${n?"downloaded":"downloading"} ${s} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${n?"downloaded":"downloading"} ${s} ${r} MB`}function Bc(s){let e=new URL(s);return Le.posix.basename(e.pathname)||"archive"}async function Lc(s,e){let t=s.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await As("tar",["-xf",s,"-C",e]);return}if(t.endsWith(".zip")){if(await Wc("unzip")){await As("unzip",["-q",s,"-d",e]);return}await As("tar",["-xf",s,"-C",e]);return}throw new Error(`Unsupported archive format: ${s}`)}function As(s,e){return new Promise((t,n)=>{let r=bo(s,e,{stdio:["ignore","ignore","inherit"]});r.on("error",n),r.on("exit",(o,i)=>{if(o===0){t();return}n(new Error(`${s} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function Wc(s){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",n=bo(t,[s],{stdio:"ignore"});n.on("error",()=>e(!1)),n.on("exit",r=>e(r===0))})}async function Cs(s){try{return await ce.access(s),!0}catch{return!1}}K();import*as ge from"fs/promises";import*as xe from"path";import{spawn as qc}from"child_process";var Ps=s=>{process.stderr.write(s+`
9
9
  `)};function Ms(s){Ps=s??(e=>process.stderr.write(e+`
10
- `))}async function So(s){let e=Ce();if(!e)throw new Error(`Agent ${s.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=A.agentNpmInstallDir(s.agentId,e,s.version),n=Vc(s.packageSpec),r=Qc(n),o={installDir:t,packageName:n,hint:s.bin,basename:r},i=xe.join(t,"node_modules",".bin",s.bin);if(await Qe(i))return i;if(await Qe(t)){let l=await vo(o);if(l)return l.binPath}await Wc({agentId:s.agentId,version:s.version,packageSpec:s.packageSpec,installDir:t,registry:s.registry,onProgress:s.onProgress});let a=await vo(o);if(a)return a.binPath;let d=await Ao(t,n),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 ${s.agentId}: npm install of ${s.packageSpec} did not produce bin ${s.bin} (looked in ${t}/node_modules/.bin/)${c}`)}async function Wc(s){await pe.mkdir(xe.dirname(s.installDir),{recursive:!0});let e=await pe.mkdtemp(`${s.installDir}.partial-`);try{Ps(`hydra-acp: installing ${s.packageSpec} for ${s.agentId} into ${e}`),Es(s.onProgress,{phase:"install_start",agentId:s.agentId,version:s.version,packageSpec:s.packageSpec}),await Jc({packageSpec:s.packageSpec,cwd:e,registry:s.registry});try{await pe.rename(e,s.installDir)}catch(t){let n=t;if((n.code==="EEXIST"||n.code==="ENOTEMPTY")&&await Qe(s.installDir)){await pe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Es(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version});return}throw t}Ps(`hydra-acp: installed ${s.agentId} to ${s.installDir}`),Es(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version})}catch(t){throw await pe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Es(s,e){if(s)try{s(e)}catch{}}var qc=5,zc=25;function Jc(s){return Io(s,0)}async function Io(s,e){try{await new Promise((t,n)=>{let r=s.registry?["--registry",s.registry]:[],o;try{o=Uc("npm",["install","--no-audit","--no-fund","--silent",...r,s.packageSpec],{cwd:s.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){n(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.on("error",a=>{if(a.code==="ENOENT"){n(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}n(a)}),o.on("exit",(a,d)=>{if(a===0){t();return}let u=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,c=i.trim();n(new Error(c?`npm install ${s.packageSpec} failed (${u})
11
- stderr: ${c}`:`npm install ${s.packageSpec} failed (${u})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<qc)return await new Promise(r=>setTimeout(r,zc*(e+1))),Io(s,e+1);throw t}}function Vc(s){if(s.startsWith("@")){let t=s.indexOf("/");if(t===-1)return s;let r=s.slice(t+1).indexOf("@");return r===-1?s:s.slice(0,t+1+r)}let e=s.indexOf("@");return e<=0?s:s.slice(0,e)}function Qc(s){let e=s.lastIndexOf("/");return e===-1?s:s.slice(e+1)}async function Ao(s,e){let t=xe.join(s,"node_modules",e,"package.json");try{let n=await pe.readFile(t,"utf8"),r=JSON.parse(n);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function vo(s){let e=xe.join(s.installDir,"node_modules",".bin"),t=xe.join(e,s.hint);if(await Qe(t))return{binName:s.hint,binPath:t};let n=await Ao(s.installDir,s.packageName);if(typeof n=="object"&&n!==null){let r=Object.keys(n);if(r.length===1){let o=r[0],i=xe.join(e,o);if(await Qe(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[s.hint,s.basename])if(r.includes(o)){let i=xe.join(e,o);if(await Qe(i))return{binName:o,binPath:i}}}}if(s.basename!==s.hint){let r=xe.join(e,s.basename);if(await Qe(r))return{binName:s.basename,binPath:r}}}async function Qe(s){try{return await pe.access(s),!0}catch{return!1}}var Gc=j.object({package:j.string(),bin:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),rt=j.object({archive:j.string().url().optional(),cmd:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Kc=j.object({"darwin-aarch64":rt.optional(),"darwin-x86_64":rt.optional(),"linux-aarch64":rt.optional(),"linux-x86_64":rt.optional(),"windows-x86_64":rt.optional(),"windows-aarch64":rt.optional()}),Yc=j.object({package:j.string(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Xc=j.object({command:j.string(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Zc=j.object({command:j.string().optional(),url:j.string().optional(),description:j.string().optional()}),eu=j.object({npx:Gc.optional(),binary:Kc.optional(),uvx:Yc.optional(),exec:Xc.optional()}),tu=j.object({id:j.string(),name:j.string(),version:j.string().optional(),description:j.string().optional(),authors:j.array(j.string()).optional(),license:j.string().optional(),icon:j.string().optional(),repository:j.string().optional(),website:j.string().optional(),distribution:eu,onboarding:Zc.optional(),requiredEnv:j.array(j.string().min(1)).optional()}),Co=j.object({version:j.string(),agents:j.array(tu),extensions:j.array(j.unknown()).optional()}),ln=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(),n=t.find(u=>u.id===e)??t.find(u=>u.id.toLowerCase()===`${e.toLowerCase()}-acp`);if(n)return n;let r=await this.load(),o=r.agents.find(u=>u.id===e);if(o)return this.applyOverride(o);let i=r.agents.find(u=>Ts(u)===e);if(i)return this.applyOverride(i);let a=e.toLowerCase(),d=r.agents.find(u=>u.id.toLowerCase()===`${a}-acp`);if(d)return this.applyOverride(d);if(a.length>0){let u=r.agents.filter(c=>c.id.toLowerCase().startsWith(a));if(u.length===1)return this.applyOverride(u[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:de(t.command??e),args:t.args?.map(de),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:nu(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,n=this.config.registry.ttlHours*60*60*1e3;return t<n}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(),n=Co.parse(t),r={fetchedAt:Date.now(),raw:t,data:n},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(n)).catch(()=>{}),r}async readDiskCache(){let e=await ee(A.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Co.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await fe(A.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function nu(s){let e=s.lastIndexOf("@"),n=(e>0?s.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return n.length>0?`pin-${n}`:"pinned"}function Ts(s){let e=s.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),n=t===-1?e:e.slice(t+1),r=n.lastIndexOf("@");return r<=0?n:n.slice(0,r)}async function ot(s){let e=typeof s.localAgents=="function"?s.localAgents():[],t;try{t=await s.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let n=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!n.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await _s(i),source:n.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:s.lastFetchedAt(),agents:o}}async function _s(s){let e=Ce();if(!e)return"no";let t=s.version??"current";if(s.distribution.exec)return"yes";if(s.distribution.binary){let n=xs(s.distribution.binary,e);if(n?.cmd){let r=fn.resolve(A.agentInstallDir(s.id,e,t),n.cmd);if(await xo(r))return"yes"}}if(s.distribution.npx){let n=s.distribution.npx,r=n.bin??Ts(s)??n.package,o=A.agentNpmInstallDir(s.id,e,t),i=fn.join(o,"node_modules",".bin",r);if(await xo(i))return"yes"}return!s.distribution.npx&&!s.distribution.binary&&s.distribution.uvx?"lazy":"no"}async function xo(s){try{return await Ro.access(s),!0}catch{return!1}}async function ye(s,e=[],t={}){let n=s.version??"current";if(s.distribution.npx){let r=s.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:n};let i=r.bin??Ts(s)??r.package,a=t.onInstallProgress;return{command:await So({agentId:s.id,version:n,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?u=>a({source:"npm",...u}):void 0}),args:o,env:r.env??{},version:n}}if(s.distribution.binary){let r=xs(s.distribution.binary);if(!r)throw new Error(`Agent ${s.id} has no binary distribution for ${Ce()??"this platform"}.`);let o=t.onInstallProgress,i=await bo({agentId:s.id,version:n,target:r,onProgress:o?d=>o({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:n}}if(s.distribution.uvx){let r=s.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:n}}if(s.distribution.exec){let r=s.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:n}}throw new Error(`Agent ${s.id} has no usable distribution method.`)}import{spawn as au}from"child_process";import*as hn from"fs";import*as Wo from"path";var C={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 J}from"zod";var Eo=J.object({protocolVersion:J.number().optional(),clientCapabilities:J.record(J.unknown()).optional(),clientInfo:J.object({name:J.string(),version:J.string().optional()}).optional()}),su=J.enum(["full","pending_only","none","after_message"]),Po=J.object({cwd:J.string(),mcpServers:J.array(J.unknown()).optional(),_meta:J.record(J.unknown()).optional()}),Mo=J.object({upstreamSessionId:J.string(),agentId:J.string(),cwd:J.string(),title:J.string().optional(),agentArgs:J.array(J.string()).optional()}),To=J.object({sessionId:J.string(),historyPolicy:su.default("full"),afterMessageId:J.string().optional(),clientId:J.string().optional(),clientInfo:J.object({name:J.string(),version:J.string().optional()}).optional(),_meta:J.record(J.unknown()).optional()});import{z as F}from"zod";var _o=F.object({sessionId:F.string()}),$o=F.object({cwd:F.string().optional(),cursor:F.string().optional()}),$s=F.object({used:F.number().optional(),size:F.number().optional(),costAmount:F.number().optional(),costCurrency:F.string().optional()}),Uh=F.object({sessionId:F.string(),upstreamSessionId:F.string().optional(),cwd:F.string(),workspace:F.object({path:F.string(),sourceCwd:F.string(),label:F.string(),provider:F.string(),snapshot:F.string().optional(),vcs:F.record(F.string(),F.string()).optional()}).optional(),workspaceError:F.string().optional(),title:F.string().optional(),agentId:F.string().optional(),currentModel:F.string().optional(),currentUsage:$s.optional(),importedFromMachine:F.string().optional(),importedFromUpstreamSessionId:F.string().optional(),parentSessionId:F.string().optional(),forkedFromSessionId:F.string().optional(),forkedFromMessageId:F.string().optional(),originatingClient:F.object({name:F.string(),version:F.string().optional()}).optional(),interactive:F.boolean().optional(),priority:F.number().int().nonnegative().optional(),updatedAt:F.string(),attachedClients:F.number().int().nonnegative(),status:F.enum(["warm","cold"]).default("warm"),busy:F.boolean().default(!1),awaitingInput:F.boolean().default(!1),armedTasks:F.number().int().nonnegative().optional(),armedSince:F.number().int().positive().optional(),compactionState:F.any().optional(),agentPid:F.number().int().positive().optional(),forkSynthesisState:F.enum(["running","failed"]).optional(),_meta:F.record(F.unknown()).optional()}),ru=F.object({sessionId:F.string(),cwd:F.string(),title:F.string().optional(),updatedAt:F.string().optional(),_meta:F.record(F.unknown()).optional()}),Wh=F.object({sessions:F.array(ru),nextCursor:F.string().optional()});function pn(s,e){let t={attachedClients:s.attachedClients,status:s.status,busy:s.busy,awaitingInput:s.awaitingInput};return s.cwd!==void 0&&(t.cwd=s.cwd),s.workspace!==void 0&&(t.workspaceInfo=s.workspace),s.workspaceError!==void 0&&(t.workspaceError=s.workspaceError),s.title!==void 0&&(t.title=s.title),s.agentId!==void 0&&(t.agentId=s.agentId),s.upstreamSessionId!==void 0&&(t.upstreamSessionId=s.upstreamSessionId),s.currentModel!==void 0&&(t.currentModel=s.currentModel),s.currentUsage!==void 0&&(t.currentUsage=s.currentUsage),s.importedFromMachine!==void 0&&(t.importedFromMachine=s.importedFromMachine),s.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=s.importedFromUpstreamSessionId),s.parentSessionId!==void 0&&(t.parentSessionId=s.parentSessionId),s.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=s.forkedFromSessionId),s.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=s.forkedFromMessageId),s.originatingClient!==void 0&&(t.originatingClient=s.originatingClient),s.interactive!==void 0&&(t.interactive=s.interactive),s.priority!==void 0&&s.priority>0&&(t.priority=s.priority),s.armedTasks!==void 0&&(t.armedTasks=s.armedTasks),s.armedSince!==void 0&&(t.armedSince=s.armedSince),s.compactionState!==void 0&&(t.compactionState=s.compactionState),s.forkSynthesisState!==void 0&&(t.forkSynthesisState=s.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 Fo(s){let e={sessionId:s.sessionId,cwd:s.cwd,updatedAt:s.updatedAt,_meta:_t(s._meta,pn(s))};return s.title!==void 0&&(e.title=s.title),e}var be="hydra-acp";function ou(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e={};for(let[t,n]of Object.entries(s)){if(typeof t!="string"||t.length===0||typeof n!="string")return;e[t]=n}return e}function it(s){if(!s)return{};let e=s[be];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};if(typeof t.upstreamSessionId=="string"&&(n.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(n.agentId=t.agentId),typeof t.cwd=="string"&&(n.cwd=t.cwd),t.workspace!==null&&typeof t.workspace=="object"&&!Array.isArray(t.workspace)){let r=t.workspace,o={};typeof r.label=="string"&&(o.label=r.label),typeof r.from=="string"&&(o.from=r.from),r.required===!0&&(o.required=!0),typeof r.provider=="string"&&(o.provider=r.provider),n.workspace=o}if(t.workspaceInfo!==null&&typeof t.workspaceInfo=="object"&&!Array.isArray(t.workspaceInfo)){let r=t.workspaceInfo;if(typeof r.path=="string"&&typeof r.sourceCwd=="string"&&typeof r.label=="string"&&typeof r.provider=="string"){let o={path:r.path,sourceCwd:r.sourceCwd,label:r.label,provider:r.provider};if(typeof r.snapshot=="string"&&(o.snapshot=r.snapshot),r.vcs!==null&&typeof r.vcs=="object"&&!Array.isArray(r.vcs)){let i={};for(let[a,d]of Object.entries(r.vcs))typeof d=="string"&&(i[a]=d);o.vcs=i}n.workspaceInfo=o}}if(typeof t.workspaceError=="string"&&(n.workspaceError=t.workspaceError),typeof t.clientId=="string"&&(n.clientId=t.clientId),typeof t.readonly=="boolean"&&(n.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(n.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(n.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(n.toolContent=t.toolContent),t.detachStatus==="detached"&&(n.detachStatus=t.detachStatus),typeof t.title=="string"&&(n.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(n.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(n.transformers=t.transformers),t.resume){let r=Mo.safeParse(t.resume);r.success&&(n.resume=r.data)}if(typeof t.model=="string"&&(n.model=t.model),typeof t.currentModel=="string"&&(n.currentModel=t.currentModel),typeof t.currentMode=="string"&&(n.currentMode=t.currentMode),t.currentUsage){let r=$s.safeParse(t.currentUsage);r.success&&(n.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(n.turnStartedAt=t.turnStartedAt),typeof t.armedTasks=="number"&&t.armedTasks>=0&&(n.armedTasks=t.armedTasks),typeof t.armedSince=="number"&&t.armedSince>0&&(n.armedSince=t.armedSince),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),n.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),n.agents=o}if(typeof t.mcpStdin=="boolean"&&(n.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(n.interactive=t.interactive),typeof t.ancillary=="boolean"&&(n.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(n.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(n.status=t.status),typeof t.busy=="boolean"&&(n.busy=t.busy),typeof t.awaitingInput=="boolean"&&(n.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(n.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(n.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(n.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(n.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(n.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;n.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(n.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=ou(t.env);r!==void 0&&(n.env=r)}return n}function We(s,e){if(typeof e!="number"||!Number.isFinite(e)||!s||typeof s!="object"||Array.isArray(s))return s;let t=s,n=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},r=n[be],o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return typeof o.recordedAt=="number"?s:{...t,_meta:{...n,[be]:{...o,recordedAt:e}}}}function _t(s,e){return{...s??{},[be]:e}}import{z as _}from"zod";var No=_.object({sessionId:_.string(),prompt:_.array(_.unknown()),_meta:_.record(_.unknown()).optional()}),gn=_.object({sessionId:_.string()}),Oo=_.object({clientId:_.string(),name:_.string().optional(),version:_.string().optional()}),Gh=_.object({sessionId:_.string(),messageId:_.string(),originator:Oo,prompt:_.array(_.unknown()),position:_.number().int().nonnegative(),queueDepth:_.number().int().positive(),enqueuedAt:_.number()}),Kh=_.object({sessionId:_.string(),messageId:_.string(),prompt:_.array(_.unknown())}),Yh=_.object({sessionId:_.string(),messageId:_.string(),reason:_.enum(["started","cancelled","abandoned"])}),Ho=_.object({sessionId:_.string(),messageId:_.string()}),Xh=_.object({cancelled:_.boolean(),reason:_.enum(["ok","not_found","already_running"])}),jo=_.object({sessionId:_.string(),messageId:_.string(),prompt:_.array(_.unknown())}),Zh=_.object({updated:_.boolean(),reason:_.enum(["ok","not_found","already_running"])}),Do=_.object({sessionId:_.string(),targetMessageId:_.string(),prompt:_.array(_.unknown()),replaceQueue:_.boolean().optional(),onTargetCompleted:_.enum(["reject","send_anyway"]).optional()}),em=_.object({amended:_.boolean(),reason:_.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:_.string().optional()}),tm=_.object({sessionId:_.string(),cancelledMessageId:_.string(),newMessageId:_.string(),prompt:_.array(_.unknown()),originator:Oo,amendedAt:_.number()});import{z as qe}from"zod";var rm=qe.object({agentId:qe.string(),version:qe.string(),source:qe.enum(["binary","npm"]),phase:qe.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:qe.number().optional(),totalBytes:qe.number().optional(),packageSpec:qe.string().optional()}),Lo="hydra-acp/agents/install_progress",at={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function Bo(s,e){let t="",n=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let d of r)d(a)}};return s.setEncoding("utf8"),s.on("data",a=>{t+=a;let d=t.indexOf(`
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 l of n)l(c)}catch(c){for(let l of n)l({jsonrpc:"2.0",id:null,error:{code:C.ParseError,message:`Failed to parse ndjson line: ${c.message}`}})}d=t.indexOf(`
10
+ `))}async function Io(s){let e=Ce();if(!e)throw new Error(`Agent ${s.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=C.agentNpmInstallDir(s.agentId,e,s.version),n=Qc(s.packageSpec),r=Kc(n),o={installDir:t,packageName:n,hint:s.bin,basename:r},i=xe.join(t,"node_modules",".bin",s.bin);if(await Ge(i))return i;if(await Ge(t)){let l=await So(o);if(l)return l.binPath}await zc({agentId:s.agentId,version:s.version,packageSpec:s.packageSpec,installDir:t,registry:s.registry,onProgress:s.onProgress});let a=await So(o);if(a)return a.binPath;let d=await Co(t,n),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],u=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${s.agentId}: npm install of ${s.packageSpec} did not produce bin ${s.bin} (looked in ${t}/node_modules/.bin/)${u}`)}async function zc(s){await ge.mkdir(xe.dirname(s.installDir),{recursive:!0});let e=await ge.mkdtemp(`${s.installDir}.partial-`);try{Ps(`hydra-acp: installing ${s.packageSpec} for ${s.agentId} into ${e}`),Es(s.onProgress,{phase:"install_start",agentId:s.agentId,version:s.version,packageSpec:s.packageSpec}),await Gc({packageSpec:s.packageSpec,cwd:e,registry:s.registry});try{await ge.rename(e,s.installDir)}catch(t){let n=t;if((n.code==="EEXIST"||n.code==="ENOTEMPTY")&&await Ge(s.installDir)){await ge.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Es(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version});return}throw t}Ps(`hydra-acp: installed ${s.agentId} to ${s.installDir}`),Es(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version})}catch(t){throw await ge.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Es(s,e){if(s)try{s(e)}catch{}}var Jc=5,Vc=25;function Gc(s){return Ao(s,0)}async function Ao(s,e){try{await new Promise((t,n)=>{let r=s.registry?["--registry",s.registry]:[],o;try{o=qc("npm",["install","--no-audit","--no-fund","--silent",...r,s.packageSpec],{cwd:s.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){n(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.on("error",a=>{if(a.code==="ENOENT"){n(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}n(a)}),o.on("exit",(a,d)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,u=i.trim();n(new Error(u?`npm install ${s.packageSpec} failed (${c})
11
+ stderr: ${u}`:`npm install ${s.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<Jc)return await new Promise(r=>setTimeout(r,Vc*(e+1))),Ao(s,e+1);throw t}}function Qc(s){if(s.startsWith("@")){let t=s.indexOf("/");if(t===-1)return s;let r=s.slice(t+1).indexOf("@");return r===-1?s:s.slice(0,t+1+r)}let e=s.indexOf("@");return e<=0?s:s.slice(0,e)}function Kc(s){let e=s.lastIndexOf("/");return e===-1?s:s.slice(e+1)}async function Co(s,e){let t=xe.join(s,"node_modules",e,"package.json");try{let n=await ge.readFile(t,"utf8"),r=JSON.parse(n);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function So(s){let e=xe.join(s.installDir,"node_modules",".bin"),t=xe.join(e,s.hint);if(await Ge(t))return{binName:s.hint,binPath:t};let n=await Co(s.installDir,s.packageName);if(typeof n=="object"&&n!==null){let r=Object.keys(n);if(r.length===1){let o=r[0],i=xe.join(e,o);if(await Ge(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[s.hint,s.basename])if(r.includes(o)){let i=xe.join(e,o);if(await Ge(i))return{binName:o,binPath:i}}}}if(s.basename!==s.hint){let r=xe.join(e,s.basename);if(await Ge(r))return{binName:s.basename,binPath:r}}}async function Ge(s){try{return await ge.access(s),!0}catch{return!1}}var Yc=j.object({package:j.string(),bin:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),ot=j.object({archive:j.string().url().optional(),cmd:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Xc=j.object({"darwin-aarch64":ot.optional(),"darwin-x86_64":ot.optional(),"linux-aarch64":ot.optional(),"linux-x86_64":ot.optional(),"windows-x86_64":ot.optional(),"windows-aarch64":ot.optional()}),Zc=j.object({package:j.string(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),eu=j.object({command:j.string(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),tu=j.object({command:j.string().optional(),url:j.string().optional(),description:j.string().optional()}),nu=j.object({npx:Yc.optional(),binary:Xc.optional(),uvx:Zc.optional(),exec:eu.optional()}),su=j.object({id:j.string(),name:j.string(),version:j.string().optional(),description:j.string().optional(),authors:j.array(j.string()).optional(),license:j.string().optional(),icon:j.string().optional(),repository:j.string().optional(),website:j.string().optional(),distribution:nu,onboarding:tu.optional(),requiredEnv:j.array(j.string().min(1)).optional()}),xo=j.object({version:j.string(),agents:j.array(su),extensions:j.array(j.unknown()).optional()}),ln=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(),n=t.find(c=>c.id===e)??t.find(c=>c.id.toLowerCase()===`${e.toLowerCase()}-acp`);if(n)return n;let r=await this.load(),o=r.agents.find(c=>c.id===e);if(o)return this.applyOverride(o);let i=r.agents.find(c=>Ts(c)===e);if(i)return this.applyOverride(i);let a=e.toLowerCase(),d=r.agents.find(c=>c.id.toLowerCase()===`${a}-acp`);if(d)return this.applyOverride(d);if(a.length>0){let c=r.agents.filter(u=>u.id.toLowerCase().startsWith(a));if(c.length===1)return this.applyOverride(c[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:de(t.command??e),args:t.args?.map(de),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:ru(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,n=this.config.registry.ttlHours*60*60*1e3;return t<n}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(),n=xo.parse(t),r={fetchedAt:Date.now(),raw:t,data:n},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(n)).catch(()=>{}),r}async readDiskCache(){let e=await ee(C.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=xo.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await fe(C.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function ru(s){let e=s.lastIndexOf("@"),n=(e>0?s.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return n.length>0?`pin-${n}`:"pinned"}function Ts(s){let e=s.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),n=t===-1?e:e.slice(t+1),r=n.lastIndexOf("@");return r<=0?n:n.slice(0,r)}async function it(s){let e=typeof s.localAgents=="function"?s.localAgents():[],t;try{t=await s.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let n=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!n.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await _s(i),source:n.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:s.lastFetchedAt(),agents:o}}async function _s(s){let e=Ce();if(!e)return"no";let t=s.version??"current";if(s.distribution.exec)return"yes";if(s.distribution.binary){let n=xs(s.distribution.binary,e);if(n?.cmd){let r=pn.resolve(C.agentInstallDir(s.id,e,t),n.cmd);if(await Ro(r))return"yes"}}if(s.distribution.npx){let n=s.distribution.npx,r=n.bin??Ts(s)??n.package,o=C.agentNpmInstallDir(s.id,e,t),i=pn.join(o,"node_modules",".bin",r);if(await Ro(i))return"yes"}return!s.distribution.npx&&!s.distribution.binary&&s.distribution.uvx?"lazy":"no"}async function Ro(s){try{return await Eo.access(s),!0}catch{return!1}}async function we(s,e=[],t={}){let n=s.version??"current";if(s.distribution.npx){let r=s.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:n};let i=r.bin??Ts(s)??r.package,a=t.onInstallProgress;return{command:await Io({agentId:s.id,version:n,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:o,env:r.env??{},version:n}}if(s.distribution.binary){let r=xs(s.distribution.binary);if(!r)throw new Error(`Agent ${s.id} has no binary distribution for ${Ce()??"this platform"}.`);let o=t.onInstallProgress,i=await vo({agentId:s.id,version:n,target:r,onProgress:o?d=>o({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:n}}if(s.distribution.uvx){let r=s.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:n}}if(s.distribution.exec){let r=s.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:n}}throw new Error(`Agent ${s.id} has no usable distribution method.`)}import{spawn as cu}from"child_process";import*as mn from"fs";import*as qo from"path";var x={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 V}from"zod";var Po=V.object({protocolVersion:V.number().optional(),clientCapabilities:V.record(V.unknown()).optional(),clientInfo:V.object({name:V.string(),version:V.string().optional()}).optional()}),ou=V.enum(["full","pending_only","none","after_message"]),Mo=V.object({cwd:V.string(),mcpServers:V.array(V.unknown()).optional(),_meta:V.record(V.unknown()).optional()}),To=V.object({upstreamSessionId:V.string(),agentId:V.string(),cwd:V.string(),title:V.string().optional(),agentArgs:V.array(V.string()).optional()}),_o=V.object({sessionId:V.string(),historyPolicy:ou.default("full"),afterMessageId:V.string().optional(),clientId:V.string().optional(),clientInfo:V.object({name:V.string(),version:V.string().optional()}).optional(),_meta:V.record(V.unknown()).optional()});import{z as O}from"zod";var $o=O.object({sessionId:O.string()}),Fo=O.object({cwd:O.string().optional(),cursor:O.string().optional()}),$s=O.object({used:O.number().optional(),size:O.number().optional(),costAmount:O.number().optional(),costCurrency:O.string().optional()}),Qm=O.object({sessionId:O.string(),upstreamSessionId:O.string().optional(),cwd:O.string(),workspace:O.object({path:O.string(),sourceCwd:O.string(),label:O.string(),provider:O.string(),snapshot:O.string().optional(),vcs:O.record(O.string(),O.string()).optional()}).optional(),workspaceError:O.string().optional(),title:O.string().optional(),agentId:O.string().optional(),currentModel:O.string().optional(),currentUsage:$s.optional(),importedFromMachine:O.string().optional(),importedFromUpstreamSessionId:O.string().optional(),parentSessionId:O.string().optional(),forkedFromSessionId:O.string().optional(),forkedFromMessageId:O.string().optional(),originatingClient:O.object({name:O.string(),version:O.string().optional()}).optional(),interactive:O.boolean().optional(),priority:O.number().int().nonnegative().optional(),updatedAt:O.string(),attachedClients:O.number().int().nonnegative(),status:O.enum(["warm","cold"]).default("warm"),busy:O.boolean().default(!1),awaitingInput:O.boolean().default(!1),armedTasks:O.number().int().nonnegative().optional(),armedSince:O.number().int().positive().optional(),compactionState:O.any().optional(),agentPid:O.number().int().positive().optional(),forkSynthesisState:O.enum(["running","failed"]).optional(),_meta:O.record(O.unknown()).optional()}),iu=O.object({sessionId:O.string(),cwd:O.string(),title:O.string().optional(),updatedAt:O.string().optional(),_meta:O.record(O.unknown()).optional()}),Km=O.object({sessions:O.array(iu),nextCursor:O.string().optional()});function fn(s,e){let t={attachedClients:s.attachedClients,status:s.status,busy:s.busy,awaitingInput:s.awaitingInput};return s.cwd!==void 0&&(t.cwd=s.cwd),s.workspace!==void 0&&(t.workspaceInfo=s.workspace),s.workspaceError!==void 0&&(t.workspaceError=s.workspaceError),s.title!==void 0&&(t.title=s.title),s.agentId!==void 0&&(t.agentId=s.agentId),s.upstreamSessionId!==void 0&&(t.upstreamSessionId=s.upstreamSessionId),s.currentModel!==void 0&&(t.currentModel=s.currentModel),s.currentUsage!==void 0&&(t.currentUsage=s.currentUsage),s.importedFromMachine!==void 0&&(t.importedFromMachine=s.importedFromMachine),s.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=s.importedFromUpstreamSessionId),s.parentSessionId!==void 0&&(t.parentSessionId=s.parentSessionId),s.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=s.forkedFromSessionId),s.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=s.forkedFromMessageId),s.originatingClient!==void 0&&(t.originatingClient=s.originatingClient),s.interactive!==void 0&&(t.interactive=s.interactive),s.priority!==void 0&&s.priority>0&&(t.priority=s.priority),s.armedTasks!==void 0&&(t.armedTasks=s.armedTasks),s.armedSince!==void 0&&(t.armedSince=s.armedSince),s.compactionState!==void 0&&(t.compactionState=s.compactionState),s.forkSynthesisState!==void 0&&(t.forkSynthesisState=s.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 No(s){let e={sessionId:s.sessionId,cwd:s.cwd,updatedAt:s.updatedAt,_meta:_t(s._meta,fn(s))};return s.title!==void 0&&(e.title=s.title),e}var ue="hydra-acp";function au(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e={};for(let[t,n]of Object.entries(s)){if(typeof t!="string"||t.length===0||typeof n!="string")return;e[t]=n}return e}function Qe(s){if(!s)return{};let e=s[ue];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};if(typeof t.upstreamSessionId=="string"&&(n.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(n.agentId=t.agentId),typeof t.cwd=="string"&&(n.cwd=t.cwd),t.workspace!==null&&typeof t.workspace=="object"&&!Array.isArray(t.workspace)){let r=t.workspace,o={};typeof r.label=="string"&&(o.label=r.label),typeof r.from=="string"&&(o.from=r.from),r.required===!0&&(o.required=!0),typeof r.provider=="string"&&(o.provider=r.provider),n.workspace=o}if(t.workspaceInfo!==null&&typeof t.workspaceInfo=="object"&&!Array.isArray(t.workspaceInfo)){let r=t.workspaceInfo;if(typeof r.path=="string"&&typeof r.sourceCwd=="string"&&typeof r.label=="string"&&typeof r.provider=="string"){let o={path:r.path,sourceCwd:r.sourceCwd,label:r.label,provider:r.provider};if(typeof r.snapshot=="string"&&(o.snapshot=r.snapshot),r.vcs!==null&&typeof r.vcs=="object"&&!Array.isArray(r.vcs)){let i={};for(let[a,d]of Object.entries(r.vcs))typeof d=="string"&&(i[a]=d);o.vcs=i}n.workspaceInfo=o}}if(typeof t.workspaceError=="string"&&(n.workspaceError=t.workspaceError),typeof t.clientId=="string"&&(n.clientId=t.clientId),typeof t.readonly=="boolean"&&(n.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(n.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(n.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(n.toolContent=t.toolContent),t.detachStatus==="detached"&&(n.detachStatus=t.detachStatus),typeof t.title=="string"&&(n.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(n.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(n.transformers=t.transformers),t.resume){let r=To.safeParse(t.resume);r.success&&(n.resume=r.data)}if(typeof t.model=="string"&&(n.model=t.model),typeof t.currentModel=="string"&&(n.currentModel=t.currentModel),typeof t.currentMode=="string"&&(n.currentMode=t.currentMode),t.currentUsage){let r=$s.safeParse(t.currentUsage);r.success&&(n.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(n.turnStartedAt=t.turnStartedAt),typeof t.armedTasks=="number"&&t.armedTasks>=0&&(n.armedTasks=t.armedTasks),typeof t.armedSince=="number"&&t.armedSince>0&&(n.armedSince=t.armedSince),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),n.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),n.agents=o}if(typeof t.mcpStdin=="boolean"&&(n.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(n.interactive=t.interactive),typeof t.ancillary=="boolean"&&(n.ancillary=t.ancillary),t.salvaged&&typeof t.salvaged=="object"&&!Array.isArray(t.salvaged)){let r=t.salvaged;typeof r.reason=="string"&&typeof r.supersededMessageId=="string"&&(n.salvaged={reason:r.reason,supersededMessageId:r.supersededMessageId})}if(Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(n.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(n.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(n.status=t.status),typeof t.busy=="boolean"&&(n.busy=t.busy),typeof t.awaitingInput=="boolean"&&(n.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(n.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(n.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(n.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(n.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(n.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;n.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(n.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=au(t.env);r!==void 0&&(n.env=r)}return n}function We(s,e){if(typeof e!="number"||!Number.isFinite(e)||!s||typeof s!="object"||Array.isArray(s))return s;let t=s,n=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},r=n[ue],o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return typeof o.recordedAt=="number"?s:{...t,_meta:{...n,[ue]:{...o,recordedAt:e}}}}function _t(s,e){return{...s??{},[ue]:e}}import{z as N}from"zod";var Oo=N.object({sessionId:N.string(),prompt:N.array(N.unknown()),_meta:N.record(N.unknown()).optional()}),gn=N.object({sessionId:N.string()}),Ho=N.object({clientId:N.string(),name:N.string().optional(),version:N.string().optional()}),nh=N.object({sessionId:N.string(),messageId:N.string(),originator:Ho,prompt:N.array(N.unknown()),position:N.number().int().nonnegative(),queueDepth:N.number().int().positive(),enqueuedAt:N.number()}),sh=N.object({sessionId:N.string(),messageId:N.string(),prompt:N.array(N.unknown())}),rh=N.object({sessionId:N.string(),messageId:N.string(),reason:N.enum(["started","cancelled","abandoned"])}),jo=N.object({sessionId:N.string(),messageId:N.string()}),oh=N.object({cancelled:N.boolean(),reason:N.enum(["ok","not_found","already_running"])}),Uo=N.object({sessionId:N.string(),messageId:N.string(),prompt:N.array(N.unknown())}),ih=N.object({updated:N.boolean(),reason:N.enum(["ok","not_found","already_running"])}),Do=N.object({sessionId:N.string(),targetMessageId:N.string(),prompt:N.array(N.unknown()),replaceQueue:N.boolean().optional(),onTargetCompleted:N.enum(["reject","send_anyway"]).optional()}),ah=N.object({amended:N.boolean(),reason:N.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:N.string().optional()}),dh=N.object({sessionId:N.string(),cancelledMessageId:N.string(),newMessageId:N.string(),prompt:N.array(N.unknown()),originator:Ho,amendedAt:N.number()});import{z as qe}from"zod";var lh=qe.object({agentId:qe.string(),version:qe.string(),source:qe.enum(["binary","npm"]),phase:qe.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:qe.number().optional(),totalBytes:qe.number().optional(),packageSpec:qe.string().optional()}),Bo="hydra-acp/agents/install_progress",at={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function Lo(s,e){let t="",n=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let d of r)d(a)}};return s.setEncoding("utf8"),s.on("data",a=>{t+=a;let d=t.indexOf(`
12
+ `);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let u=JSON.parse(c);for(let l of n)l(u)}catch(u){for(let l of n)l({jsonrpc:"2.0",id:null,error:{code:x.ParseError,message:`Failed to parse ndjson line: ${u.message}`}})}d=t.indexOf(`
13
13
  `)}}),s.on("end",()=>i()),s.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let d=JSON.stringify(a)+`
14
- `;await new Promise((u,c)=>{e.write(d,l=>{if(l){c(l);return}u()})})},onMessage(a){n.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as iu}from"nanoid";var Fs=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},dt=class s{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 n=this.bufferedNotifications.get(e);if(n){this.bufferedNotifications.delete(e);for(let r of n)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let n=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),n}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 Fs;let n=iu(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(n,{resolve:d=>i(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(n),a(d)})});return{id:n,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let n={jsonrpc:"2.0",method:e,params:t};return this.stream.send(n)}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:C.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let n=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:n};await this.stream.send(r).catch(()=>{})}catch(n){let r=n;await this.sendError(e.id,{code:r.code??C.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 n=this.bufferedNotifications.get(e.method);if(!n){if(this.bufferedNotifications.size>=s.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}n=[],this.bufferedNotifications.set(e.method,n)}n.push(e),n.length>s.MAX_BUFFERED_PER_METHOD&&n.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let n of this.orphanErrorHandlers)try{n({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let n=new Error(e.error.message);n.code=e.error.code,n.data=e.error.data,t.reject(n)}else t.resolve(e.result)}async sendError(e,t){let n={jsonrpc:"2.0",id:e,error:t};await this.stream.send(n)}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)}}};K();var du=4096,ze=class s{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??du,this.killEscalationMs=e.killEscalationMs??cu,this.logger=e.logger,this.fileLog=uu(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
- `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let n=Bo(t.stdout,t.stdin);this.connection=new dt(n),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
14
+ `;await new Promise((c,u)=>{e.write(d,l=>{if(l){u(l);return}c()})})},onMessage(a){n.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as du}from"nanoid";var Fs=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},dt=class s{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 n=this.bufferedNotifications.get(e);if(n){this.bufferedNotifications.delete(e);for(let r of n)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let n=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),n}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 Fs;let n=du(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(n,{resolve:d=>i(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(n),a(d)})});return{id:n,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let n={jsonrpc:"2.0",method:e,params:t};return this.stream.send(n)}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:x.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let n=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:n};await this.stream.send(r).catch(()=>{})}catch(n){let r=n;await this.sendError(e.id,{code:r.code??x.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 n=this.bufferedNotifications.get(e.method);if(!n){if(this.bufferedNotifications.size>=s.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}n=[],this.bufferedNotifications.set(e.method,n)}n.push(e),n.length>s.MAX_BUFFERED_PER_METHOD&&n.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let n of this.orphanErrorHandlers)try{n({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let n=new Error(e.error.message);n.code=e.error.code,n.data=e.error.data,t.reject(n)}else t.resolve(e.result)}async sendError(e,t){let n={jsonrpc:"2.0",id:e,error:t};await this.stream.send(n)}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)}}};K();var uu=4096,ze=class s{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??uu,this.killEscalationMs=e.killEscalationMs??lu,this.logger=e.logger,this.fileLog=pu(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
+ `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let n=Lo(t.stdout,t.stdin);this.connection=new dt(n),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
16
16
  `),this.connection.fail(new Error(o))}),t.on("exit",(r,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
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=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${r} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${o}`)}for(let i of this.exitHandlers)i(r,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
18
- stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...dn(),...e.plan.env,...e.extraEnv??{}},n=au(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return n.unref(),new s(e,n)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
18
+ stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...dn(),...e.plan.env,...e.extraEnv??{}},n=cu(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return n.unref(),new s(e,n)}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(Uo),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${Uo}ms after SIGKILL; giving up on the reap`)))}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 n=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(n),t()};this.child.once("exit",r)})}},cu=2e3,Uo=5e3;function uu(s){try{let e=A.agentLogFile(s);hn.mkdirSync(Wo.dirname(e),{recursive:!0});let t=hn.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Ye from"fs/promises";import*as ga from"os";import*as qo from"os";function $t(){return qo.hostname()}import*as Qt from"path";import{customAlphabet as df}from"nanoid";var Re="session/set_model",Os="session/set_config_option",Vo="model";function Ns(s){return!s||typeof s!="object"||Array.isArray(s)?!1:Array.isArray(s.availableModels)}function Qo(s){return Array.isArray(s)&&s.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===Vo)}function ct(s){if(!s)return;if(Ns(s)||Ns(s.models))return Re;let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))if(t!=="hydra-acp"&&Ns(n))return Re}if(Qo(s.configOptions))return Os}function Go(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.sessionUpdate;if(e==="current_model_update")return Re;if(e==="config_option_update"&&Qo(s.configOptions))return Os}function zo(s){return typeof s=="object"&&s!==null&&s.code===C.MethodNotFound}function Jo(s,e,t,n){let r={...n??{}};return delete r.sessionId,delete r.modelId,delete r.configId,delete r.value,s===Re?{...r,sessionId:e,modelId:t}:{...r,sessionId:e,configId:Vo,value:t}}function lu(s){return s===Re?Os:Re}async function Je(s){let{request:e,sessionId:t,modelId:n,extraParams:r,logger:o}=s,i=s.verb??Re;try{let a=await e(i,Jo(i,t,n,r));return{verb:i,result:a}}catch(a){if(!zo(a))throw a;let d=lu(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(n)}`);try{let u=await e(d,Jo(d,t,n,r));return{verb:d,result:u}}catch(u){throw zo(u)?a:u}}}async function ut(s){let{agent:e,upstreamSessionId:t,persistedMode:n,agentReportedMode:r,advertisedModes:o,logger:i}=s;if(!n)return r;if(n===r)return n;if(o&&o.length>0&&!o.some(a=>a.id===n)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(n)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:n}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(n)}`),n}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(n)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function lt(s){let{agent:e,upstreamSessionId:t,persistedModel:n,agentReportedModel:r,modelVerb:o,logger:i}=s;if(!n)return r;if(n===r)return n;try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`);let{verb:a}=await Je({request:(d,u)=>e.connection.request(d,u),sessionId:t,modelId:n,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(n)}`),n}catch(a){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(n)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as wi}from"nanoid";var Ko="edit",mn=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 Yo(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(t===null||typeof t!="object")continue;let n=t.path;typeof n=="string"&&n.length>0&&e.push(n)}return e}import*as Zo from"fs/promises";var fu=64*1024*1024,pu=1*1024*1024,ft=64*1024,gu=6e4,hu=100,mu=1e3,yu=64*1024,wu=256*1024,Xo=20;function ku(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yn=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??fu,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(pu,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 n=Math.max(0,Math.min(t,ft));if(n===0){let l={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(l.eof=!0),l}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let l={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(l.gap=o),this.closed&&(l.eof=!0),l}let d=Math.min(a,n),c={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return o>0&&(c.gap=o),this.closed&&r+d>=this.writeCursor&&(c.eof=!0),c}tail(e){let t=Math.max(0,Math.min(e,ft)),n=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(n,r),i=r<n;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,ft)),n=this.oldestAvailable,r=n>0,o=n,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let n=Math.max(0,Math.min(t,gu));return n===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},n)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,n=e.cursor,r=n??t,o=0;n!==void 0&&n<t&&(o=t-n,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",u=a?new RegExp(e.pattern,d):new RegExp(ku(e.pattern),d),c=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??hu,mu)),p=Math.max(1,Math.min(e.maxBytes??yu,wu)),f=Math.max(0,Math.min(e.contextBefore??0,Xo)),h=Math.max(0,Math.min(e.contextAfter??0,Xo)),g=[],m=[],y=[],k=0,w=!1,b=0,v=0,S=(M,H)=>{for(let G of y)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:M,line:H}),G.remaining--,k+=H.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(u.test(H)!==c&&g.length<l){let G={cursor:M,line:H};if(f>0&&m.length>0){G.before=m.slice();for(let le of G.before)k+=le.line.length}k+=H.length,g.push(G),h>0&&y.push({match:G,remaining:h})}if(f>0)for(m.push({cursor:M,line:H});m.length>f;)m.shift();let O=g.length>=l&&y.length===0,W=k>=p;return O||W};for(let M=0;M<i.length;M++){if(i[M]!==10)continue;let H=i.subarray(b,M).toString("utf8"),$=r+b;if(b=M+1,v=b,S($,H)){w=!0;break}}if(!w&&b<i.length&&this.closed){let M=i.subarray(b).toString("utf8"),H=r+b;S(H,M)&&(w=!0),v=i.length}let x=Math.min(r+v,this.writeCursor),R={matches:g,truncated:w,nextCursor:x,scannedBytes:v};return o>0&&(R.gap=o),this.closed&&x>=this.writeCursor&&(R.eof=!0),R}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let n of t)n.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let n=this.currentCapacityBytes;for(;n<t&&n<this.maxCapacityBytes;)n=Math.min(this.maxCapacityBytes,n*2);if(n===this.currentCapacityBytes)return;let r=Buffer.alloc(n);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=n}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let n=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-n;t<=r?e.copy(this.storage,n,0,t):(e.copy(this.storage,n,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let n=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(n,0,r,r+o),o<t&&this.storage.copy(n,o,0,t-o),n}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let n=this.fileCapBytes-this.fileBytesWritten;if(n<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=n?e:e.subarray(0,n);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Zo.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var pt=[{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:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{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."}],Tm=new Map(pt.map(s=>[s.verb,s]));function ei(s){let e=s.lastIndexOf("/");return(e===-1?s:s.slice(e+1)).toLowerCase()}function gt(s,e){return Hs(s,e.map(t=>t.modelId))}function Hs(s,e){if(e.length===0)return{kind:"none",requested:s};if(e.includes(s))return{kind:"exact",modelId:s};let t=ei(s),n=e.filter(o=>ei(o)===t);if(n.length===1)return{kind:"resolved",modelId:n[0],requested:s};if(n.length>1)return{kind:"ambiguous",requested:s,candidates:n};let r=s.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:s};if(o.length>1)return{kind:"ambiguous",requested:s,candidates:o}}return{kind:"unknown",requested:s}}function ni(s){if(s.length===0)return s;let e=new Map,t=new Map,n=new Map;for(let a=0;a<s.length;a++){let d=s[a];if(d===void 0)continue;let u=js(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 l of Iu){if(!ti(u[l]))continue;let p=n.get(c);p===void 0?n.set(c,new Map([[l,u[l]]])):p.set(l,u[l])}if(Array.isArray(u.content)&&u.content.length>0){let l=t.get(c);l?l.push(...u.content):t.set(c,[...u.content])}}}let r=[],o=null,i=null;for(let a=0;a<s.length;a++){let d=s[a];if(d===void 0)continue;let u=js(d);if(!u||typeof u.sessionUpdate!="string"){r.push(d),o=null;continue}let c=u.sessionUpdate;if(c==="agent_message_chunk"||c==="agent_thought_chunk"||c==="user_message_chunk"){o&&o.kind===c?vu(r,o.outIndex,bu(u.content)):(r.push(d),o={outIndex:r.length-1,kind:c});continue}if(o=null,c==="tool_call_update"){let l=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(l!==void 0&&e.get(l)!==a)continue;let p=l!==void 0&&t.has(l)?Su(d,t.get(l)??[]):d,f=l===void 0?void 0:n.get(l);if(f!==void 0)for(let[h,g]of f)ti(js(p)?.[h])||(p=Au(p,h,g));r.push(p);continue}if(c==="plan"){i!==null?r[i]=d:(r.push(d),i=r.length-1);continue}(c==="prompt_received"||c==="turn_complete")&&(i=null),r.push(d)}return r}function js(s){if(s.method!=="session/update")return;let t=s.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function bu(s){if(!s||typeof s!="object")return"";let e=s;return typeof e.text=="string"?e.text:""}function vu(s,e,t){if(t.length===0)return;let n=s[e];if(n===void 0)return;let r=n.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";s[e]={...n,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function Su(s,e){let t=s.params??{},n=t.update??{};return{...s,params:{...t,update:{...n,content:e}}}}var Iu=["rawInput","locations"];function ti(s){return s==null||typeof s!="object"?!1:Array.isArray(s)?s.length>0:Object.keys(s).length>0}function Au(s,e,t){let n=s.params??{},r=n.update??{};return{...s,params:{...n,update:{...r,[e]:t}}}}var si=`[older history truncated]
21
- `,ri=["file_path","filePath","path","command","pattern","query"];function ht(s,e={}){let t=e.maxChars??4e5,n=Ds(s),r=[],o="",i=e.toolOutput?.maxTotal??0,a=()=>{o.length!==0&&(r.push(`Assistant: ${o}`),o="")};for(let d of s){if(d.method!=="session/update")continue;let c=d.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let l=c.sessionUpdate;if(l==="prompt_received"){a();let p=Ws(c.prompt).trim();p.length>0&&r.push(`User: ${p}`)}else if(l==="agent_message_chunk"){let p=qs(c.content);p.length>0&&(o+=p)}else if(l==="tool_call"){if(a(),r.push(Us(c,n)),e.toolOutput!==void 0){let p=Bs(c),f=p!==void 0?n.get(p)?.output:void 0;if(f!==void 0&&i>0){let h=Math.min(e.toolOutput.maxPerCall,i),g=f.length<=h?f:`${f.slice(0,h)}\u2026[${f.length-h} more chars]`;r.push(`Output: ${g}`),i-=Math.min(g.length,h)}}}else l==="turn_complete"&&a()}return a(),Tu(r.join(`
22
- `),t)}function Ds(s){let e=new Map;for(let t of s){if(t.method!=="session/update")continue;let r=t.params?.update;if(!r)continue;let o=r.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;let i=Bs(r);if(i===void 0)continue;let a=e.get(i);if(a===void 0&&(a={name:"(unnamed)",rawInput:{}},e.set(i,a)),a.name==="(unnamed)"){let u=xu(r,o);u!==void 0&&(a.name=u)}if(a.kind===void 0&&typeof r.kind=="string"&&r.kind.length>0&&(a.kind=r.kind),a.output===void 0){let u=wn(r);u!==void 0&&(a.output=u)}let d=r.rawInput;d&&typeof d=="object"&&!Array.isArray(d)&&Object.assign(a.rawInput,d)}for(let t of e.values())t.name=Ls(t);return e}function Ls(s){return Cu(s)?s.kind??"(unnamed)":s.name}function Cu(s){for(let e of ri){let t=s.rawInput[e];if(!(typeof t!="string"||t.length===0)&&(t===s.name||s.name.length>=12&&t.startsWith(s.name)))return!0}return!1}function xu(s,e){let t=Ft(s);if(t!==void 0)return t;if(typeof s.name=="string"&&s.name.length>0)return s.name;if(e==="tool_call"&&typeof s.title=="string"&&s.title.length>0)return s.title}function Bs(s){let e=s.toolCallId;if(typeof e=="string"&&e.length>0)return e}function wn(s){let e=Ru(s);if(e!==void 0)return e;let t=s.rawOutput;if(typeof t=="string")return t.length>0?t:void 0;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.output;if(typeof n=="string")return n.length>0?n:void 0}}function Ru(s){let e=s._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let n=t.toolResponse;if(typeof n=="string")return n.length>0?n:void 0;if(!n||typeof n!="object")return;let{stdout:r,stderr:o}=n,i=[];if(typeof r=="string"&&r.length>0&&i.push(r),typeof o=="string"&&o.length>0&&i.push(`[stderr] ${o}`),i.length!==0)return i.join(`
23
- `)}function Ft(s){let e=s._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let n=t.toolName;if(typeof n=="string"&&n.length>0)return n}function Us(s,e){let t=Bs(s),n=t!==void 0?e?.get(t):void 0,r=n?.name??Eu(s),o=Pu(n?.rawInput??s.rawInput);return o.length===0?`Tool: ${r}`:`Tool: ${r}(${o.join(", ")})`}function Eu(s){let e=Ft(s);return e!==void 0?e:typeof s.name=="string"&&s.name.length>0?s.name:typeof s.title=="string"&&s.title.length>0?s.title:"(unnamed)"}function Pu(s){if(!s||typeof s!="object"||Array.isArray(s))return[];let e=s,t=[];for(let n of ri){let r=e[n];typeof r=="string"&&r.length>0&&t.push(`${n}=${Mu(r,600)}`)}return t}function Ws(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function qs(s){if(!s||typeof s!="object")return"";let e=s.text;return typeof e=="string"?e:""}function Mu(s,e){return s.length<=e?s:s.slice(0,e-1)+"\u2026"}function Tu(s,e){if(s.length<=e)return s;let t=s.split(`
24
- `);for(;t.length>0;){let n=si+t.join(`
25
- `);if(n.length<=e)return n;t.shift()}return si}var oi="(untitled)";function zs(s){let e=[],t=s.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${s.title??oi}`),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 d=Nt("Open threads",t.open_threads);d.length>0&&e.push(d);let u=Nt("Decisions",t.decisions);u.length>0&&e.push(u);let c=Nt("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let l=Nt("Unresolved errors",t.unresolved_errors);l.length>0&&e.push(l);let p=Nt("Tool state",t.tool_state);p.length>0&&e.push(p);let f=ii(t.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let h=ii(t.tools_used);h.length>0&&e.push(`[Tools previously used] ${h}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${s.title??oi}`);s.note!==void 0&&s.note.trim().length>0&&e.push(`[Situation] ${s.note.trim()}`);let{closedText:n,openText:r,keptCount:o}=_u(s.tail,s.tailK,s.watermark??0,s.tailFloor??0);e.push("--- begin recent turns (verbatim, last "+o+") ---"),n.length>0&&e.push(n),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 ---"));let i=s.recallArmed??!0;e.push("");let a=s.framing??(t!==void 0?"compaction":"fork");return a==="swap"?e.push(i?"(This session's agent process was replaced; nothing was summarized away. 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.)":"(This session's agent process was replaced; nothing was summarized away. The turns above are the most recent. 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.)"):a==="compaction"&&i?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.)"):a==="compaction"?e.push("(Hydra has compacted earlier conversation; the turns above are what survives. 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.)"):i?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.push("(This is a side conversation forked from another session. The turns above are the most recent. 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(`
20
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(Wo),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${Wo}ms after SIGKILL; giving up on the reap`)))}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 n=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(n),t()};this.child.once("exit",r)})}},lu=2e3,Wo=5e3;function pu(s){try{let e=C.agentLogFile(s);mn.mkdirSync(qo.dirname(e),{recursive:!0});let t=mn.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Xe from"fs/promises";import*as ha from"os";import*as zo from"os";function $t(){return zo.hostname()}import*as Gt from"path";import{customAlphabet as gp}from"nanoid";var Re="session/set_model",Os="session/set_config_option",Go="model";function Ns(s){return!s||typeof s!="object"||Array.isArray(s)?!1:Array.isArray(s.availableModels)}function Qo(s){return Array.isArray(s)&&s.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===Go)}function ct(s){if(!s)return;if(Ns(s)||Ns(s.models))return Re;let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))if(t!=="hydra-acp"&&Ns(n))return Re}if(Qo(s.configOptions))return Os}function Ko(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.sessionUpdate;if(e==="current_model_update")return Re;if(e==="config_option_update"&&Qo(s.configOptions))return Os}function Jo(s){return typeof s=="object"&&s!==null&&s.code===x.MethodNotFound}function Vo(s,e,t,n){let r={...n??{}};return delete r.sessionId,delete r.modelId,delete r.configId,delete r.value,s===Re?{...r,sessionId:e,modelId:t}:{...r,sessionId:e,configId:Go,value:t}}function fu(s){return s===Re?Os:Re}async function Je(s){let{request:e,sessionId:t,modelId:n,extraParams:r,logger:o}=s,i=s.verb??Re;try{let a=await e(i,Vo(i,t,n,r));return{verb:i,result:a}}catch(a){if(!Jo(a))throw a;let d=fu(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(n)}`);try{let c=await e(d,Vo(d,t,n,r));return{verb:d,result:c}}catch(c){throw Jo(c)?a:c}}}async function ut(s){let{agent:e,upstreamSessionId:t,persistedMode:n,agentReportedMode:r,advertisedModes:o,logger:i}=s;if(!n)return r;if(n===r)return n;if(o&&o.length>0&&!o.some(a=>a.id===n)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(n)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:n}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(n)}`),n}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(n)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function lt(s){let{agent:e,upstreamSessionId:t,persistedModel:n,agentReportedModel:r,modelVerb:o,logger:i}=s;if(!n)return r;if(n===r)return n;try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`);let{verb:a}=await Je({request:(d,c)=>e.connection.request(d,c),sessionId:t,modelId:n,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(n)}`),n}catch(a){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(n)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as vi}from"nanoid";var Yo="edit",hn=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 Xo(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(t===null||typeof t!="object")continue;let n=t.path;typeof n=="string"&&n.length>0&&e.push(n)}return e}import*as ei from"fs/promises";var gu=64*1024*1024,mu=1*1024*1024,pt=64*1024,hu=6e4,yu=100,wu=1e3,ku=64*1024,bu=256*1024,Zo=20;function vu(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yn=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??gu,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(mu,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 n=Math.max(0,Math.min(t,pt));if(n===0){let l={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(l.eof=!0),l}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let l={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(l.gap=o),this.closed&&(l.eof=!0),l}let d=Math.min(a,n),u={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return o>0&&(u.gap=o),this.closed&&r+d>=this.writeCursor&&(u.eof=!0),u}tail(e){let t=Math.max(0,Math.min(e,pt)),n=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(n,r),i=r<n;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,pt)),n=this.oldestAvailable,r=n>0,o=n,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let n=Math.max(0,Math.min(t,hu));return n===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},n)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,n=e.cursor,r=n??t,o=0;n!==void 0&&n<t&&(o=t-n,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(vu(e.pattern),d),u=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??yu,wu)),f=Math.max(1,Math.min(e.maxBytes??ku,bu)),p=Math.max(0,Math.min(e.contextBefore??0,Zo)),g=Math.max(0,Math.min(e.contextAfter??0,Zo)),m=[],h=[],y=[],k=0,w=!1,S=0,I=0,b=(E,$)=>{for(let Q of y)Q.remaining>0&&(Q.match.after===void 0&&(Q.match.after=[]),Q.match.after.push({cursor:E,line:$}),Q.remaining--,k+=$.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test($)!==u&&m.length<l){let Q={cursor:E,line:$};if(p>0&&h.length>0){Q.before=h.slice();for(let pe of Q.before)k+=pe.line.length}k+=$.length,m.push(Q),g>0&&y.push({match:Q,remaining:g})}if(p>0)for(h.push({cursor:E,line:$});h.length>p;)h.shift();let M=m.length>=l&&y.length===0,W=k>=f;return M||W};for(let E=0;E<i.length;E++){if(i[E]!==10)continue;let $=i.subarray(S,E).toString("utf8"),_=r+S;if(S=E+1,I=S,b(_,$)){w=!0;break}}if(!w&&S<i.length&&this.closed){let E=i.subarray(S).toString("utf8"),$=r+S;b($,E)&&(w=!0),I=i.length}let A=Math.min(r+I,this.writeCursor),R={matches:m,truncated:w,nextCursor:A,scannedBytes:I};return o>0&&(R.gap=o),this.closed&&A>=this.writeCursor&&(R.eof=!0),R}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let n of t)n.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let n=this.currentCapacityBytes;for(;n<t&&n<this.maxCapacityBytes;)n=Math.min(this.maxCapacityBytes,n*2);if(n===this.currentCapacityBytes)return;let r=Buffer.alloc(n);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=n}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let n=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-n;t<=r?e.copy(this.storage,n,0,t):(e.copy(this.storage,n,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let n=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(n,0,r,r+o),o<t&&this.storage.copy(n,o,0,t-o),n}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let n=this.fileCapBytes-this.fileBytesWritten;if(n<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=n?e:e.subarray(0,n);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>ei.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var ft=[{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:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{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."}],jh=new Map(ft.map(s=>[s.verb,s]));function ti(s){let e=s.lastIndexOf("/");return(e===-1?s:s.slice(e+1)).toLowerCase()}function gt(s,e){return Hs(s,e.map(t=>t.modelId))}function Hs(s,e){if(e.length===0)return{kind:"none",requested:s};if(e.includes(s))return{kind:"exact",modelId:s};let t=ti(s),n=e.filter(o=>ti(o)===t);if(n.length===1)return{kind:"resolved",modelId:n[0],requested:s};if(n.length>1)return{kind:"ambiguous",requested:s,candidates:n};let r=s.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:s};if(o.length>1)return{kind:"ambiguous",requested:s,candidates:o}}return{kind:"unknown",requested:s}}function si(s){if(s.length===0)return s;let e=new Map,t=new Map,n=new Map;for(let a=0;a<s.length;a++){let d=s[a];if(d===void 0)continue;let c=js(d);if(c?.sessionUpdate!=="tool_call_update")continue;let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0){e.set(u,a);for(let l of Cu){if(!ni(c[l]))continue;let f=n.get(u);f===void 0?n.set(u,new Map([[l,c[l]]])):f.set(l,c[l])}if(Array.isArray(c.content)&&c.content.length>0){let l=t.get(u);l?l.push(...c.content):t.set(u,[...c.content])}}}let r=[],o=null,i=null;for(let a=0;a<s.length;a++){let d=s[a];if(d===void 0)continue;let c=js(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),o=null;continue}let u=c.sessionUpdate;if(u==="agent_message_chunk"||u==="agent_thought_chunk"||u==="user_message_chunk"){o&&o.kind===u?Iu(r,o.outIndex,Su(c.content)):(r.push(d),o={outIndex:r.length-1,kind:u});continue}if(o=null,u==="tool_call_update"){let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&e.get(l)!==a)continue;let f=l!==void 0&&t.has(l)?Au(d,t.get(l)??[]):d,p=l===void 0?void 0:n.get(l);if(p!==void 0)for(let[g,m]of p)ni(js(f)?.[g])||(f=xu(f,g,m));r.push(f);continue}if(u==="plan"){i!==null?r[i]=d:(r.push(d),i=r.length-1);continue}(u==="prompt_received"||u==="turn_complete")&&(i=null),r.push(d)}return r}function js(s){if(s.method!=="session/update")return;let t=s.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Su(s){if(!s||typeof s!="object")return"";let e=s;return typeof e.text=="string"?e.text:""}function Iu(s,e,t){if(t.length===0)return;let n=s[e];if(n===void 0)return;let r=n.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";s[e]={...n,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function Au(s,e){let t=s.params??{},n=t.update??{};return{...s,params:{...t,update:{...n,content:e}}}}var Cu=["rawInput","locations"];function ni(s){return s==null||typeof s!="object"?!1:Array.isArray(s)?s.length>0:Object.keys(s).length>0}function xu(s,e,t){let n=s.params??{},r=n.update??{};return{...s,params:{...n,update:{...r,[e]:t}}}}var ri=`[older history truncated]
21
+ `,oi=["file_path","filePath","path","command","pattern","query"];function mt(s,e={}){let t=e.maxChars??4e5,n=Us(s),r=[],o="",i=e.toolOutput?.maxTotal??0,a=()=>{o.length!==0&&(r.push(`Assistant: ${o}`),o="")};for(let d of s){if(d.method!=="session/update")continue;let u=d.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let l=u.sessionUpdate;if(l==="prompt_received"){a();let f=Ws(u.prompt).trim();f.length>0&&r.push(`User: ${f}`)}else if(l==="agent_message_chunk"){let f=qs(u.content);f.length>0&&(o+=f)}else if(l==="tool_call"){if(a(),r.push(Ls(u,n)),e.toolOutput!==void 0){let f=Bs(u),p=f!==void 0?n.get(f)?.output:void 0;if(p!==void 0&&i>0){let g=Math.min(e.toolOutput.maxPerCall,i),m=p.length<=g?p:`${p.slice(0,g)}\u2026[${p.length-g} more chars]`;r.push(`Output: ${m}`),i-=Math.min(m.length,g)}}}else l==="turn_complete"&&a()}return a(),$u(r.join(`
22
+ `),t)}function Us(s){let e=new Map;for(let t of s){if(t.method!=="session/update")continue;let r=t.params?.update;if(!r)continue;let o=r.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;let i=Bs(r);if(i===void 0)continue;let a=e.get(i);if(a===void 0&&(a={name:"(unnamed)",rawInput:{}},e.set(i,a)),a.name==="(unnamed)"){let c=Eu(r,o);c!==void 0&&(a.name=c)}if(a.kind===void 0&&typeof r.kind=="string"&&r.kind.length>0&&(a.kind=r.kind),a.output===void 0){let c=wn(r);c!==void 0&&(a.output=c)}let d=r.rawInput;d&&typeof d=="object"&&!Array.isArray(d)&&Object.assign(a.rawInput,d)}for(let t of e.values())t.name=Ds(t);return e}function Ds(s){return Ru(s)?s.kind??"(unnamed)":s.name}function Ru(s){for(let e of oi){let t=s.rawInput[e];if(!(typeof t!="string"||t.length===0)&&(t===s.name||s.name.length>=12&&t.startsWith(s.name)))return!0}return!1}function Eu(s,e){let t=Ft(s);if(t!==void 0)return t;if(typeof s.name=="string"&&s.name.length>0)return s.name;if(e==="tool_call"&&typeof s.title=="string"&&s.title.length>0)return s.title}function Bs(s){let e=s.toolCallId;if(typeof e=="string"&&e.length>0)return e}function wn(s){let e=Pu(s);if(e!==void 0)return e;let t=s.rawOutput;if(typeof t=="string")return t.length>0?t:void 0;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.output;if(typeof n=="string")return n.length>0?n:void 0}}function Pu(s){let e=s._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let n=t.toolResponse;if(typeof n=="string")return n.length>0?n:void 0;if(!n||typeof n!="object")return;let{stdout:r,stderr:o}=n,i=[];if(typeof r=="string"&&r.length>0&&i.push(r),typeof o=="string"&&o.length>0&&i.push(`[stderr] ${o}`),i.length!==0)return i.join(`
23
+ `)}function Ft(s){let e=s._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let n=t.toolName;if(typeof n=="string"&&n.length>0)return n}function Ls(s,e){let t=Bs(s),n=t!==void 0?e?.get(t):void 0,r=n?.name??Mu(s),o=Tu(n?.rawInput??s.rawInput);return o.length===0?`Tool: ${r}`:`Tool: ${r}(${o.join(", ")})`}function Mu(s){let e=Ft(s);return e!==void 0?e:typeof s.name=="string"&&s.name.length>0?s.name:typeof s.title=="string"&&s.title.length>0?s.title:"(unnamed)"}function Tu(s){if(!s||typeof s!="object"||Array.isArray(s))return[];let e=s,t=[];for(let n of oi){let r=e[n];typeof r=="string"&&r.length>0&&t.push(`${n}=${_u(r,600)}`)}return t}function Ws(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function qs(s){if(!s||typeof s!="object")return"";let e=s.text;return typeof e=="string"?e:""}function _u(s,e){return s.length<=e?s:s.slice(0,e-1)+"\u2026"}function $u(s,e){if(s.length<=e)return s;let t=s.split(`
24
+ `);for(;t.length>0;){let n=ri+t.join(`
25
+ `);if(n.length<=e)return n;t.shift()}return ri}var ii="(untitled)";function zs(s){let e=[],t=s.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${s.title??ii}`),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 d=Nt("Open threads",t.open_threads);d.length>0&&e.push(d);let c=Nt("Decisions",t.decisions);c.length>0&&e.push(c);let u=Nt("File edit intentions",t.file_edit_intentions);u.length>0&&e.push(u);let l=Nt("Unresolved errors",t.unresolved_errors);l.length>0&&e.push(l);let f=Nt("Tool state",t.tool_state);f.length>0&&e.push(f);let p=ai(t.files_touched);p.length>0&&e.push(`[Files previously touched] ${p}`);let g=ai(t.tools_used);g.length>0&&e.push(`[Tools previously used] ${g}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${s.title??ii}`);s.note!==void 0&&s.note.trim().length>0&&e.push(`[Situation] ${s.note.trim()}`);let{closedText:n,openText:r,keptCount:o}=Fu(s.tail,s.tailK,s.watermark??0,s.tailFloor??0);e.push("--- begin recent turns (verbatim, last "+o+") ---"),n.length>0&&e.push(n),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 ---"));let i=s.recallArmed??!0;e.push("");let a=s.framing??(t!==void 0?"compaction":"fork");return a==="swap"?e.push(i?"(This session's agent process was replaced; nothing was summarized away. 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.)":"(This session's agent process was replaced; nothing was summarized away. The turns above are the most recent. 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.)"):a==="compaction"&&i?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.)"):a==="compaction"?e.push("(Hydra has compacted earlier conversation; the turns above are what survives. 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.)"):i?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.push("(This is a side conversation forked from another session. The turns above are the most recent. 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(`
26
26
  `)}function Nt(s,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 n=t.map(r=>"- "+r.trim());return`[${s}] ${n.join(`
27
- `)}`}function ii(s){if(!s||!Array.isArray(s))return"";let e=s.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function _u(s,e,t,n){if(s.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=$u(s),i=0,a=[];if(e>0&&r.length>0){let c=r.filter(f=>f.startEntryIndex>=t).length,l=Math.max(c,n),p=Math.min(l,e,r.length);i=p,a=p>0?r.slice(-p):[]}let d=a.length>0?ai(a):"",u=o?ai([o]):"";return{closedText:d,openText:u,keptCount:i}}function ai(s){let e=[];for(let t of s){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let n of t.tools)e.push(n)}return e.join(`
28
- `)}function $u(s){let e=[],t=null,n=Ds(s);for(let o=0;o<s.length;o++){let i=s[o];if(i.method!=="session/update")continue;let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let u=d.sessionUpdate;if(u==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Ws(d.prompt).trim(),agent:"",tools:[],startEntryIndex:o};else if(u==="agent_message_chunk"&&t!==null){let c=qs(d.content);c.length>0&&(t.agent+=c)}else u==="tool_call"&&t!==null?t.tools.push(Us(d,n)):u==="turn_complete"&&t!==null&&(e.push(t),t=null)}let r=t!==null&&t.user.length>0?t:null;return{closed:e,open:r}}function Fu(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Js(s,e,t){if(e.length===0||e===t)return{text:s,rewritten:[]};let n=e.endsWith("/")?e.slice(0,-1):e,r=t.endsWith("/")?t.slice(0,-1):t,o=[],i=new RegExp(`${Fu(n)}/(?![/\\s])`,"g");return{text:s.replace(i,(d,u)=>{let c=s.slice(u+d.length),l=c.search(/[\s"'`,;:)\]}]|$/);return o.push(`${n}/${c.slice(0,l<0?void 0:l)}`),`${r}/`}),rewritten:o}}function Vs(s,e){if(e.length===0)return!1;let t=e.endsWith("/")?e.slice(0,-1):e;return s.includes(t)}function di(s){let e=[];return e.push("[workspace] You have LEFT the isolated workspace."),e.push(`- Your working directory is now ${s.sourceCwd}`),e.push(s.removed?`- The workspace at ${s.formerWorkspacePath} has been removed. Paths under it from earlier in this conversation no longer exist.`:`- The workspace at ${s.formerWorkspacePath} still exists but is NO LONGER YOURS. Editing anything under it is wasted: that work will not reach ${s.sourceCwd}.`),e.push("- Earlier turns refer to files by their workspace paths. Treat those as referring to the same files under your current working directory, and prefer repo-relative paths from here on."),e.join(`
29
- `)}function ci(s){let e=[];e.push(s.reassert===!0?"[workspace] Reminder: you are NOT working in the directory that path names.":"[workspace] Before anything else, note where you are working:"),e.push(`- Your working directory is ${s.workspacePath}`),e.push(`- It is an isolated copy of ${s.sourceCwd}`),e.push(`- Any absolute path under ${s.sourceCwd} refers to the matching file under your working directory. Do not read or write ${s.sourceCwd} directly.`),e.push("- Prefer repo-relative paths (`src/foo.ts`). They are identical in both trees, so they cannot be misread.");for(let t of s.notes)e.push(`- ${t}`);return e.join(`
30
- `)}function ui(s,e,t){if(s.length===0||!s.startsWith("/"))return!1;let n=e.endsWith("/")?e:`${e}/`,r=t.endsWith("/")?t:`${t}/`;return s.startsWith(r)?!1:s.startsWith(n)}K();import*as Ee from"fs/promises";async function Ot(s,e){let t=A.queueFile(s);if(e.length===0){await Ee.unlink(t).catch(()=>{});return}await Ee.mkdir(A.sessionDir(s),{recursive:!0});let n=e.map(r=>JSON.stringify(r)).join(`
27
+ `)}`}function ai(s){if(!s||!Array.isArray(s))return"";let e=s.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Fu(s,e,t,n){if(s.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Nu(s),i=0,a=[];if(e>0&&r.length>0){let u=r.filter(p=>p.startEntryIndex>=t).length,l=Math.max(u,n),f=Math.min(l,e,r.length);i=f,a=f>0?r.slice(-f):[]}let d=a.length>0?di(a):"",c=o?di([o]):"";return{closedText:d,openText:c,keptCount:i}}function di(s){let e=[];for(let t of s){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let n of t.tools)e.push(n)}return e.join(`
28
+ `)}function Nu(s){let e=[],t=null,n=Us(s);for(let o=0;o<s.length;o++){let i=s[o];if(i.method!=="session/update")continue;let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Ws(d.prompt).trim(),agent:"",tools:[],startEntryIndex:o};else if(c==="agent_message_chunk"&&t!==null){let u=qs(d.content);u.length>0&&(t.agent+=u)}else c==="tool_call"&&t!==null?t.tools.push(Ls(d,n)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let r=t!==null&&t.user.length>0?t:null;return{closed:e,open:r}}function ci(s,e){let t=s??[],n=(e??0)>0,r=[],o=new Set,i=t[0];i&&o.add(i.upstreamSessionId);for(let d=1;d<t.length;d++){let c=t[d],u=t[d-1],l={upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,...c.startedAt!==void 0?{at:c.startedAt}:{},...c.endedAt!==void 0?{endedAt:c.endedAt}:{},...c.cost!==void 0?{cost:c.cost}:{},...c.reason!==void 0?{reason:c.reason}:{},...c.runId!==void 0?{runId:c.runId}:{}};c.reason===void 0&&(c.agentId!==u.agentId?l.inferredReason="agent-swap":o.has(c.upstreamSessionId)?l.inferredReason="rollback":n||(l.notCompaction=!0)),o.add(c.upstreamSessionId),r.push(l)}let a=r.filter(d=>d.reason==="compaction");return{rotations:r,compactions:a,runs:Ou(a),unknownCount:r.filter(d=>d.reason===void 0&&d.inferredReason===void 0&&!d.notCompaction).length}}function Ou(s){let e=[],t;for(let n of s){let r=e[e.length-1];if(r!==void 0&&n.runId!==void 0&&n.runId===t){r.swaps++,r.upstreamSessionId=n.upstreamSessionId,r.current=n.endedAt===void 0,n.cost!==void 0&&(r.cost=(r.cost??0)+n.cost);continue}e.push({...n.at!==void 0?{at:n.at}:{},upstreamSessionId:n.upstreamSessionId,swaps:1,...n.cost!==void 0?{cost:n.cost}:{},current:n.endedAt===void 0}),t=n.runId}return e}function Hu(s){if(!s)return"unknown time";let e=Date.parse(s);return Number.isNaN(e)?"unknown time":`${new Date(e).toISOString().slice(0,16)}Z`}function ui(s){let{runs:e,unknownCount:t}=s,n=[];if(e.length>0){n.push(e.length===1?"Compacted 1 time:":`Compacted ${e.length} times:`);for(let r of e){let o=r.cost!==void 0?` $${r.cost.toFixed(2)}`:"",i=r.current?" (current)":"",a=r.swaps>1?` (${r.swaps} swaps)`:"";n.push(` ${Hu(r.at)} ${r.upstreamSessionId}${o}${a}${i}`)}}if(t>0){let r=t===1?"rotation":"rotations";n.push(e.length>0?`${t} earlier ${r}, cause not recorded; the count above is a lower bound.`:`No compactions on record. ${t} ${r} predate reason tracking, and any of them may have been a compaction.`)}return n}function ju(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Js(s,e,t){if(e.length===0||e===t)return{text:s,rewritten:[]};let n=e.endsWith("/")?e.slice(0,-1):e,r=t.endsWith("/")?t.slice(0,-1):t,o=[],i=new RegExp(`${ju(n)}/(?![/\\s])`,"g");return{text:s.replace(i,(d,c)=>{let u=s.slice(c+d.length),l=u.search(/[\s"'`,;:)\]}]|$/);return o.push(`${n}/${u.slice(0,l<0?void 0:l)}`),`${r}/`}),rewritten:o}}function Vs(s,e){if(e.length===0)return!1;let t=e.endsWith("/")?e.slice(0,-1):e;return s.includes(t)}function li(s){let e=[];return e.push("[workspace] You have LEFT the isolated workspace."),e.push(`- Your working directory is now ${s.sourceCwd}`),e.push(s.removed?`- The workspace at ${s.formerWorkspacePath} has been removed. Paths under it from earlier in this conversation no longer exist.`:`- The workspace at ${s.formerWorkspacePath} still exists but is NO LONGER YOURS. Editing anything under it is wasted: that work will not reach ${s.sourceCwd}.`),e.push("- Earlier turns refer to files by their workspace paths. Treat those as referring to the same files under your current working directory, and prefer repo-relative paths from here on."),e.join(`
29
+ `)}function pi(s){let e=[];e.push(s.reassert===!0?"[workspace] Reminder: you are NOT working in the directory that path names.":"[workspace] Before anything else, note where you are working:"),e.push(`- Your working directory is ${s.workspacePath}`),e.push(`- It is an isolated copy of ${s.sourceCwd}`),e.push(`- Any absolute path under ${s.sourceCwd} refers to the matching file under your working directory. Do not read or write ${s.sourceCwd} directly.`),e.push("- Prefer repo-relative paths (`src/foo.ts`). They are identical in both trees, so they cannot be misread.");for(let t of s.notes)e.push(`- ${t}`);return e.join(`
30
+ `)}function fi(s,e,t){if(s.length===0||!s.startsWith("/"))return!1;let n=e.endsWith("/")?e:`${e}/`,r=t.endsWith("/")?t:`${t}/`;return s.startsWith(r)?!1:s.startsWith(n)}K();import*as Ee from"fs/promises";async function Ot(s,e){let t=C.queueFile(s);if(e.length===0){await Ee.unlink(t).catch(()=>{});return}await Ee.mkdir(C.sessionDir(s),{recursive:!0});let n=e.map(r=>JSON.stringify(r)).join(`
31
31
  `)+`
32
- `;await Ee.writeFile(t,n,"utf8")}async function li(s){let e=A.queueFile(s),t;try{t=await Ee.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t.split(`
33
- `))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&n.push(o)}catch{}return n}async function fi(s){let e=A.queueFile(s);await Ee.unlink(e).catch(()=>{})}import*as vi from"fs/promises";var ki="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bi=wi(ki,16),Qs=wi(ki,16),Nu=20,Ou=20,Hu=5,Me="hydra_session_";function Pe(){return`m_${bi()}`}function He(s){return s.startsWith(Me)?s.slice(Me.length):s}var pi=["start","merge","apply","sync","stop","detach","discard","clean","status"],ju=1e3,kn=300*1e3,Du=64,Lu=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);function Bu(s){let e=s?.update;if(!e||typeof e!="object"||e.sessionUpdate!=="usage_update")return!1;let t=e._meta;if(!t||typeof t!="object")return!1;let n=t["_claude/origin"];if(!n||typeof n!="object")return!1;let r=n.kind;return typeof r=="string"&&Lu.has(r)}var gi=120,Uu=128,Wu=1e3,wt=class s{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;modelVerb=Re;modelVerbConfirmed=!1;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;agentTurnInFlight=!1;swapInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleWorkspaceSnapshotHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;unsolicitedTurn;lastBackgroundTask;toolLabels=new Map;armedTasks=new Map;lastArmedBroadcast;sawTurnComplete=!1;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;persistWatermarkHook;uncompactHook;forkHook;mcpServersConfig;forwardedEnv;workspace;workspaceError;workspaceNotes=[];workspaceHook;workspacePreambleSent=!1;formerWorkspace;departureNoteSent=!1;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new mn;filesEditedSeen=new Set;agentChangeHandlers=[];retiringGenerationCost;agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;costLedgerProbe;get persistableUsage(){if(!(!this._currentUsage&&!this.cumulativeCost))return{...this._currentUsage??{},...this.cumulativeCost?{cumulativeCost:this.cumulativeCost}:{cumulativeCost:void 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??`${Me}${bi()}`,this.cwd=e.cwd,this.workspace=e.workspace,this.workspaceError=e.workspaceError,this.workspaceHook=e.workspaceHook,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.scheduleWorkspaceSnapshotHook=e.scheduleWorkspaceSnapshot,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.reloadsUpstreamLedger&&this.armCostLedgerProbe(),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.persistWatermarkHook=e.persistWatermarkHook,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??ju,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.resetModelVerb(e.modelVerb),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){Xu(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let n=await this.runAgentRequestChain("session/request_permission",t),r=hi(n.shortCircuit?t:n.envelope);if(n.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:n.payload,sourceWasTransformer:!0}),n.payload;let o=await this.handlePermissionRequest(n.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>s.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,n=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let c=n;c<this.transformChain.length;c++){let l=this.transformChain[c];if(t.has(l.name)||!l.intercepts.has(a))continue;let p=`t_${Qs()}`,f;try{f=await l.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(g){this.logger?.warn(`transformer ${l.name} error on ${a}: ${g.message}`);continue}let h=f?.action??"continue";if(h==="stop")return;if(h==="processing"){let g=c,m=i,y=new Set(t),k=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:l.name}),this.runResponseChain(m,new Set([...y,l.name]),g+1,k).then(()=>w()).catch(()=>w()))},kn);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:l.name,method:k,envelope:m,chainIdx:g,originatedBy:y,side:"response"})});return}f?.payload&&typeof f.payload=="object"&&(i=f.payload),t.add(l.name)}if(r!=="session/update")return;this.noteAgentActivity(i);let d=Zu(i);if(d!==null){this.setAgentAdvertisedCommands(d);return}let u=Yu(i);if(u!==null){this.setAgentAdvertisedModes(u);return}if(this.noteModelVerbHint(Go(i.update),"session/update"),this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let n of this.clients.values()){if(e&&n.clientId===e)continue;let r={clientId:n.clientId};n.clientInfo?.name&&(r.name=n.clientInfo.name),n.clientInfo?.version&&(r.version=n.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get inUnsolicitedTurn(){return this.unsolicitedTurn!==void 0}get agentPid(){return this.agent.pid}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.agentTurnInFlight||this.unsolicitedTurn!==void 0||this.internalPromptCapture!==void 0||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.unsolicitedTurn!==void 0||this.modeChangeInFlight||this.modelChangeInFlight)}async swapIntoWorkspace(e){await this.swapUpstream({...e.synopsis!==void 0?{artifact:e.synopsis}:{},note:e.note,framing:"swap",...e.title!==void 0?{title:e.title}:{},tailK:8,tailFloor:4,summarizedThroughEntry:e.historyLength,newCwd:e.cwd,reason:e.workspace!==void 0?"workspace-enter":"workspace-leave"}),this.workspace=e.workspace,e.left!==void 0?(this.formerWorkspace={path:e.left.path,sourceCwd:e.cwd,removed:e.left.removed},this.departureNoteSent=!1):this.formerWorkspace=void 0}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");if(this.swapInFlight)throw new Error("a swap is already in progress for this session");this.swapInFlight=!0;try{await this.doSwapUpstream(e)}finally{this.swapInFlight=!1}}async doSwapUpstream(e){this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let t=this.agentId,n=e.newAgentId??this.agentId,r=n!==this.agentId,o=e.newCwd??this.cwd,i=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,u=this.currentMode,c=this.spawnReplacementAgent;if(!c)throw new Error("agent spawning not configured for this session");let l=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await c({agentId:n,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:l});this.accumulateAndResetCost(),this.cwd=o,this.wireAgent(p.agent),r||(await lt({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await ut({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:u,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let f=[];if(this.historyStore)try{f=await this.historyStore.load(this.sessionId)}catch(w){this.logger?.warn(`swapUpstream: historyStore.load failed: ${w.message}`)}let h=zs({...e.artifact!==void 0?{synopsis:e.artifact}:{},...e.note!==void 0?{note:e.note}:{},...e.framing!==void 0?{framing:e.framing}:{},title:e.title,tail:f,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{},recallArmed:(e.summarizedThroughEntry??this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:h}]});let w=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${h.length} toolCalls=${w.toolCalls} thinkingChars=${w.thinkingChars} messageChars=${w.messageChars} used=${w.lastUsed??"?"} size=${w.lastSize??"?"} reply=${JSON.stringify(w.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let g=this.upstreamSessionId,m=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;if(this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,this.resetModelVerb(p.modelVerb),r&&(this.agentId=n,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions(),this.notifyAgentChange("swapUpstream"),e.summarizedThroughEntry!==void 0&&this.persistWatermarkHook)try{this.persistWatermarkHook(e.summarizedThroughEntry)}catch(w){this.logger?.warn(`swapUpstream: persistWatermarkHook failed: ${w.message}`)}if(!r&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:g,...m!==void 0?{previousSummarizedThroughEntry:m}:{}})}catch(w){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${w.message}`)}await y.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:g,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),r||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),r&&this.broadcastAgentSwitch(t,n);let k=e.reason==="workspace-enter"||e.reason==="workspace-leave"?void 0:r?`
32
+ `;await Ee.writeFile(t,n,"utf8")}async function gi(s){let e=C.queueFile(s),t;try{t=await Ee.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t.split(`
33
+ `))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&n.push(o)}catch{}return n}async function mi(s){let e=C.queueFile(s);await Ee.unlink(e).catch(()=>{})}import*as Ai from"fs/promises";var Si="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ii=vi(Si,16),Gs=vi(Si,16),Uu=20,Du=20,Bu=5,Me="hydra_session_";function Pe(){return`m_${Ii()}`}function He(s){return s.startsWith(Me)?s.slice(Me.length):s}var hi=["start","merge","apply","sync","stop","detach","discard","clean","status"],Lu=1e3,kn=300*1e3,Wu=64,qu=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);function zu(s){let e=s?.update;if(!e||typeof e!="object"||e.sessionUpdate!=="usage_update")return!1;let t=e._meta;if(!t||typeof t!="object")return!1;let n=t["_claude/origin"];if(!n||typeof n!="object")return!1;let r=n.kind;return typeof r=="string"&&qu.has(r)}var yi=120,Ju=128,Vu=1e3,wt=class s{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;modelVerb=Re;modelVerbConfirmed=!1;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;agentTurnInFlight=!1;swapInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleWorkspaceSnapshotHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getUpstreamGenerationsHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;unsolicitedTurn;supersededAutonomousTurn;autonomousSalvage;lastBackgroundTask;toolLabels=new Map;armedTasks=new Map;lastArmedBroadcast;sawTurnComplete=!1;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;persistWatermarkHook;uncompactHook;forkHook;mcpServersConfig;forwardedEnv;workspace;workspaceError;workspaceNotes=[];workspaceHook;workspacePreambleSent=!1;formerWorkspace;departureNoteSent=!1;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new hn;filesEditedSeen=new Set;openToolCalls=new Set;agentChangeHandlers=[];retiringGenerationCost;agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;costLedgerProbe;get persistableUsage(){if(!(!this._currentUsage&&!this.cumulativeCost))return{...this._currentUsage??{},...this.cumulativeCost?{cumulativeCost:this.cumulativeCost}:{cumulativeCost:void 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??`${Me}${Ii()}`,this.cwd=e.cwd,this.workspace=e.workspace,this.workspaceError=e.workspaceError,this.workspaceHook=e.workspaceHook,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.scheduleWorkspaceSnapshotHook=e.scheduleWorkspaceSnapshot,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getUpstreamGenerationsHook=e.getUpstreamGenerations,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.reloadsUpstreamLedger&&this.armCostLedgerProbe(),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.persistWatermarkHook=e.persistWatermarkHook,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??Lu,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.resetModelVerb(e.modelVerb),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){nl(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let n=await this.runAgentRequestChain("session/request_permission",t),r=wi(n.shortCircuit?t:n.envelope);if(n.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:n.payload,sourceWasTransformer:!0}),n.payload;let o=await this.handlePermissionRequest(n.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>s.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,n=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let u=n;u<this.transformChain.length;u++){let l=this.transformChain[u];if(t.has(l.name)||!l.intercepts.has(a))continue;let f=`t_${Gs()}`,p;try{p=await l.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(m){this.logger?.warn(`transformer ${l.name} error on ${a}: ${m.message}`);continue}let g=p?.action??"continue";if(g==="stop")return;if(g==="processing"){let m=u,h=i,y=new Set(t),k=r;await new Promise(w=>{let S=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:l.name}),this.runResponseChain(h,new Set([...y,l.name]),m+1,k).then(()=>w()).catch(()=>w()))},kn);typeof S.unref=="function"&&S.unref(),this.pendingClaims.set(f,{resolve:()=>w(),timer:S,transformerName:l.name,method:k,envelope:h,chainIdx:m,originatedBy:y,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(i=p.payload),t.add(l.name)}if(r!=="session/update")return;this.noteAgentActivity(i);let d=sl(i);if(d!==null){this.setAgentAdvertisedCommands(d);return}let c=tl(i);if(c!==null){this.setAgentAdvertisedModes(c);return}if(this.noteModelVerbHint(Ko(i.update),"session/update"),this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let n of this.clients.values()){if(e&&n.clientId===e)continue;let r={clientId:n.clientId};n.clientInfo?.name&&(r.name=n.clientInfo.name),n.clientInfo?.version&&(r.version=n.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get inUnsolicitedTurn(){return this.unsolicitedTurn!==void 0}get agentPid(){return this.agent.pid}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return await this.quiesceBlocker()===void 0}async quiesceBlocker(){if(this.agentTurnInFlight)return"the agent is still working; wait for the current turn to finish, then try again";if(this.unsolicitedTurn!==void 0)return"the agent is part-way through a turn it started by itself; wait for it to finish or interrupt it (^C), then try again";if(this.internalPromptCapture!==void 0)return"hydra is driving the agent right now (compaction seed or transcript injection); this clears by itself, so try again in a moment";if(this.modelChangeInFlight)return"a model change is still settling; try again in a moment";if(this.modeChangeInFlight)return"a mode change is still settling; try again in a moment";let e=await this.openToolCallIdsInHistory();if(e.length>0)return`${e.length} tool call(s) from an earlier turn never reported a result, so the session still reads as busy. ^C closes an abandoned chain; failing that it clears as new history accumulates`}isQuiescedSync(){return!(this.promptInFlight||this.unsolicitedTurn!==void 0||this.modeChangeInFlight||this.modelChangeInFlight)}async swapIntoWorkspace(e){await this.swapUpstream({...e.synopsis!==void 0?{artifact:e.synopsis}:{},note:e.note,framing:"swap",...e.title!==void 0?{title:e.title}:{},tailK:8,tailFloor:4,summarizedThroughEntry:e.historyLength,newCwd:e.cwd,reason:e.workspace!==void 0?"workspace-enter":"workspace-leave"}),this.workspace=e.workspace,e.left!==void 0?(this.formerWorkspace={path:e.left.path,sourceCwd:e.cwd,removed:e.left.removed},this.departureNoteSent=!1):this.formerWorkspace=void 0}async swapUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for swap: ${t}`);if(this.swapInFlight)throw new Error("a swap is already in progress for this session");this.swapInFlight=!0;try{await this.doSwapUpstream(e)}finally{this.swapInFlight=!1}}async doSwapUpstream(e){this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let t=this.agentId,n=e.newAgentId??this.agentId,r=n!==this.agentId,o=e.reason!==void 0&&e.reason!=="compaction"?e.reason:r?"agent-swap":"compaction",i=e.newCwd??this.cwd,a=this.agentArgs,d=this.forwardedEnv,c=this.currentModel,u=this.currentMode,l=this.spawnReplacementAgent;if(!l)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await l({agentId:n,cwd:i,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:f});this.accumulateAndResetCost(),this.cwd=i,this.wireAgent(p.agent),r||(await lt({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger}),await ut({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:u,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let g=[];if(this.historyStore)try{g=await this.historyStore.load(this.sessionId)}catch(_){this.logger?.warn(`swapUpstream: historyStore.load failed: ${_.message}`)}let m=zs({...e.artifact!==void 0?{synopsis:e.artifact}:{},...e.note!==void 0?{note:e.note}:{},...e.framing!==void 0?{framing:e.framing}:{},title:e.title,tail:g,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{},recallArmed:(e.summarizedThroughEntry??this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};let h,y;try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let _=this.internalPromptCapture;h=_.lastUsed,y=_.lastSize,this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${_.toolCalls} thinkingChars=${_.thinkingChars} messageChars=${_.messageChars} used=${_.lastUsed??"?"} size=${_.lastSize??"?"} reply=${JSON.stringify(_.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}h!==void 0&&(this.maybeApplyAgentUsage({update:{sessionUpdate:"usage_update",used:h,...y!==void 0?{size:y}:{}}}),this.broadcastCurrentUsage());let k=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let S=this.agent;if(this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,this.resetModelVerb(p.modelVerb),r&&(this.agentId=n,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions(),this.notifyAgentChange("swapUpstream",o,e.runId),e.summarizedThroughEntry!==void 0&&this.persistWatermarkHook)try{this.persistWatermarkHook(e.summarizedThroughEntry)}catch(_){this.logger?.warn(`swapUpstream: persistWatermarkHook failed: ${_.message}`)}if(!r&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:k,...w!==void 0?{previousSummarizedThroughEntry:w}:{},...e.runId!==void 0?{runId:e.runId}:{}})}catch(_){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${_.message}`)}let I=await this.retireAgent(S,r?"agent switch":e.reason==="workspace-enter"||e.reason==="workspace-leave"?"workspace move":"compaction swap");this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:k,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),r||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),r&&this.broadcastAgentSwitch(t,n);let b=I.length>0?`
34
+ Stopped ${I.length} background task(s) with the previous agent: ${I.join(", ")}. Re-arm anything still needed.
35
+ `:"",E=(e.reason==="workspace-enter"||e.reason==="workspace-leave"?"":r?`
34
36
  Switched to ${n}.
35
37
  `:`
36
38
  Compaction completed.
37
- `;if(k!==void 0){let w=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:k},_meta:{"hydra-acp":{synthetic:!0}}}});for(let b of this.clients.values())b.connection.notify("session/update",w).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 n=this.loadExistingAgentSession;if(!n)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,u=this.currentMode,c=await n(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(c.agent),await lt({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedModel:d,agentReportedModel:c.initialModel,logger:this.logger}),await ut({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedMode:u,agentReportedMode:c.initialMode,logger:this.logger}),c.agent.connection.drainBuffered("session/update");let l=this.agent;this.agent=c.agent,this.upstreamSessionId=c.upstreamSessionId,this.agentMeta=c.agentMeta,this.agentCapabilities=c.agentCapabilities,this.resetModelVerb(c.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await l.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0}),this.notifyAgentChange("rollbackToUpstream"),this.updatedAt=Date.now()}async _hasOpenToolCall(e=Nu){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),n=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of n){let d=i.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 l=d.status;(l==="completed"||l==="failed")&&o.add(c)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}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 n of this.clients.values())n.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 n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:n,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",n).catch(()=>{});this.notifyChain("compaction",{...e})}broadcastWorkspacePhase(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_workspace",...e}});for(let n of this.broadcastHandlers)try{n({method:"session/update",params:t,recordedAt:Date.now()})}catch{}for(let n of this.clients.values())n.connection.notify("session/update",t).catch(()=>{});this.notifyChain("workspace",{...e})}broadcastSyntheticText(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e},_meta:{"hydra-acp":{synthetic:!0}}}});for(let n of this.clients.values())n.connection.notify("session/update",t).catch(()=>{})}attach(e,t,n={}){if(this.closed)throw ge(new Error("session is closed"),C.SessionNotFound);if(this.clients.has(e.clientId))throw ge(new Error(`client ${e.clientId} is already attached`),C.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,n)}async loadReplay(e,t){let n=a=>t.raw?a:ni(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Gs(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?bn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...n(o)],appliedPolicy:"full"}:{entries:[...i,...n(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...n(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,n=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:n}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:n})}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:n});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:n}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:n}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:n})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:n}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let n=t.reason.slice(11),r=this.permissionCallbacks.get(n);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 n={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:n}).catch(()=>{})}reportIsolationBreach(e,t){let n=this.workspace;if(n===void 0){let r=this.formerWorkspace;r!==void 0&&e.startsWith(`${r.path}/`)&&(this.logger?.warn?.(`STALE WORKSPACE WRITE on session ${this.sessionId}: the agent wrote ${e}, which is inside the workspace this session already left. That work will not reach ${r.sourceCwd}.`),this.notifyChain("workspace.staleWrite",{path:e,formerWorkspacePath:r.path,sourceCwd:r.sourceCwd,toolCallId:t}));return}ui(e,n.sourceCwd,n.path)&&(this.logger?.warn?.(`ISOLATION BREACH on session ${this.sessionId}: the agent wrote ${e}, which is in the source tree ${n.sourceCwd}, not its workspace ${n.path}. The user's checkout has been modified.`),this.notifyChain("workspace.breach",{path:e,sourceCwd:n.sourceCwd,workspacePath:n.path,toolCallId:t}))}applyDepartedPromptRewrite(e){let t=this.formerWorkspace;if(t===void 0)return e;let n=!1,r=mi(e,o=>Vs(o,t.path)?(n=!0,Js(o,t.path,t.sourceCwd).text):o);if(!this.departureNoteSent||n){let o=di({sourceCwd:t.sourceCwd,formerWorkspacePath:t.path,removed:t.removed});r=Ks(r,`${o}
39
+ `)+b,$=E===""?void 0:E;if($!==void 0){let _=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:$},_meta:{"hydra-acp":{synthetic:!0}}}});for(let M of this.clients.values())M.connection.notify("session/update",_).catch(()=>{})}this.updatedAt=Date.now()}async rollbackToUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for rollback: ${t}`);let n=this.loadExistingAgentSession;if(!n)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,c=this.currentMode,u=await n(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(u.agent),await lt({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedModel:d,agentReportedModel:u.initialModel,logger:this.logger}),await ut({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedMode:c,agentReportedMode:u.initialMode,logger:this.logger}),u.agent.connection.drainBuffered("session/update");let l=this.agent;this.agent=u.agent,this.upstreamSessionId=u.upstreamSessionId,this.agentMeta=u.agentMeta,this.agentCapabilities=u.agentCapabilities,this.resetModelVerb(u.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await this.retireAgent(l,"rollback"),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0}),this.notifyAgentChange("rollbackToUpstream","rollback"),this.updatedAt=Date.now()}async openToolCallIdsInHistory(e=Uu){if(!this.historyStore)return[];let t=await this.historyStore.load(this.sessionId),n=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of n){let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate,u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u){if(c==="tool_call")r.add(u);else if(c==="tool_call_update"){let l=d.status;(l==="completed"||l==="failed")&&o.add(u)}}}return[...r].filter(i=>!o.has(i))}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 n of this.clients.values())n.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 n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:n,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",n).catch(()=>{});this.notifyChain("compaction",{...e})}broadcastWorkspacePhase(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_workspace",...e}});for(let n of this.broadcastHandlers)try{n({method:"session/update",params:t,recordedAt:Date.now()})}catch{}for(let n of this.clients.values())n.connection.notify("session/update",t).catch(()=>{});this.notifyChain("workspace",{...e})}broadcastSyntheticText(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e},_meta:{"hydra-acp":{synthetic:!0}}}});for(let n of this.clients.values())n.connection.notify("session/update",t).catch(()=>{})}attach(e,t,n={}){if(this.closed)throw me(new Error("session is closed"),x.SessionNotFound);if(this.clients.has(e.clientId))throw me(new Error(`client ${e.clientId} is already attached`),x.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,n)}async loadReplay(e,t){let n=a=>t.raw?a:si(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Qs(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?bn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...n(o)],appliedPolicy:"full"}:{entries:[...i,...n(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...n(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,n=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:n}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:n})}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:n});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:n}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:n}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:n})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:n}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let n=t.reason.slice(11),r=this.permissionCallbacks.get(n);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 n={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:n}).catch(()=>{})}reportIsolationBreach(e,t){let n=this.workspace;if(n===void 0){let r=this.formerWorkspace;r!==void 0&&e.startsWith(`${r.path}/`)&&(this.logger?.warn?.(`STALE WORKSPACE WRITE on session ${this.sessionId}: the agent wrote ${e}, which is inside the workspace this session already left. That work will not reach ${r.sourceCwd}.`),this.notifyChain("workspace.staleWrite",{path:e,formerWorkspacePath:r.path,sourceCwd:r.sourceCwd,toolCallId:t}));return}fi(e,n.sourceCwd,n.path)&&(this.logger?.warn?.(`ISOLATION BREACH on session ${this.sessionId}: the agent wrote ${e}, which is in the source tree ${n.sourceCwd}, not its workspace ${n.path}. The user's checkout has been modified.`),this.notifyChain("workspace.breach",{path:e,sourceCwd:n.sourceCwd,workspacePath:n.path,toolCallId:t}))}applyDepartedPromptRewrite(e){let t=this.formerWorkspace;if(t===void 0)return e;let n=!1,r=ki(e,o=>Vs(o,t.path)?(n=!0,Js(o,t.path,t.sourceCwd).text):o);if(!this.departureNoteSent||n){let o=li({sourceCwd:t.sourceCwd,formerWorkspacePath:t.path,removed:t.removed});r=Ks(r,`${o}
38
40
 
39
- `),this.departureNoteSent=!0}return r}applyWorkspacePromptRewrite(e){let t=this.workspace;if(t===void 0)return this.applyDepartedPromptRewrite(e);let n=!1,r=mi(e,i=>Vs(i,t.sourceCwd)?(n=!0,Js(i,t.sourceCwd,t.path).text):i);if(!this.workspacePreambleSent||n){let i=ci({workspacePath:t.path,sourceCwd:t.sourceCwd,notes:this.workspaceNotes,...this.workspacePreambleSent?{reassert:!0}:{}});r=Ks(r,`${i}
41
+ `),this.departureNoteSent=!0}return r}applyWorkspacePromptRewrite(e){let t=this.workspace;if(t===void 0)return this.applyDepartedPromptRewrite(e);let n=!1,r=ki(e,i=>Vs(i,t.sourceCwd)?(n=!0,Js(i,t.sourceCwd,t.path).text):i);if(!this.workspacePreambleSent||n){let i=pi({workspacePath:t.path,sourceCwd:t.sourceCwd,notes:this.workspaceNotes,...this.workspacePreambleSent?{reassert:!0}:{}});r=Ks(r,`${i}
40
42
 
41
- `),this.workspacePreambleSent=!0}return r}async prompt(e,t,n){let r=this.clients.get(e);if(!r)throw ge(new Error("client not attached"),C.SessionNotFound);if(this.closing)throw ge(new Error("session is closing; new prompts cannot be accepted"),C.SessionClosing);let o=Pe();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(it((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let a of this.interactiveHandlers)try{a(!0)}catch{}}return this.enqueueUserPrompt(r,t,o,n)}broadcastPromptReceived(e){this.closeUnsolicitedTurn("superseded");let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),e.originator.fromSession&&(t.fromSession=e.originator.fromSession),e.originator.fromSessionTitle&&(t.fromSessionTitle=e.originator.fromSessionTitle),e.originator.fromLabel&&(t.fromLabel=e.originator.fromLabel),e.originator.depth!==void 0&&(t.depth=e.originator.depth),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 n=mt(e.prompt);n.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},_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;t._meta={"hydra-acp":{upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}};let n={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:n,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,n,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Pe()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&n!==void 0&&a.cancelledMessageId===n&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,this.sawTurnComplete=!0,this.scheduleWorkspaceSnapshotHook?.(),n!==void 0&&o!==void 0&&this.recordTerminal(n,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&n!==void 0&&a.cancelledMessageId===n&&this.broadcastPromptAmended(a)}noteAgentActivity(e){if(!(this.closing||this.closed)){if(Bu(e)){this.closeUnsolicitedTurn("completed");return}Gs("session/update",e)||(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||this.openUnsolicitedTurn()))}}noteBackgroundTaskArming(e){let t=e?.update;if(!t||typeof t!="object")return;let n=typeof t.toolCallId=="string"?t.toolCallId:void 0;if(n===void 0)return;let r=t.rawInput,o=Vu(t._meta);this.rememberToolLabel(n,t,r,o),this.noteBackgroundTaskStopped(t,r,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:Ju(t.rawOutput);if(!(i!==void 0||r!==void 0&&r.run_in_background===!0))return;let d=this.toolLabels.get(n)?.label??"background task";this.lastBackgroundTask={toolCallId:n,label:d};let u=Date.now(),c=this.armedTasks.get(n),l=i??c?.taskId,p=zu(t.title,o,r)||c?.repeating===!0;this.armedTasks.set(n,{label:d,...l!==void 0?{taskId:l}:{},repeating:p,armedAt:c?.armedAt??u}),this.onArmedTasksChanged()}get armedBackgroundTasks(){return[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{}}))}get armedSince(){let e;for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedTasks.size,t=this.armedSince;e===this.lastArmedBroadcast?.count&&t===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={count:e,since:t},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:e,...t!==void 0?{since:t}:{},tasks:this.armedBackgroundTasks}))}noteBackgroundTaskStopped(e,t,n){if(!(n?.toolName==="TaskStop"||e.title==="TaskStop"))return;let o=t?.task_id;if(typeof o!="string"||o.length===0)return;let i=!1;for(let[a,d]of this.armedTasks)d.taskId===o&&(this.armedTasks.delete(a),i=!0);i&&this.onArmedTasksChanged()}rememberToolLabel(e,t,n,r){let o=n!==void 0&&typeof n.description=="string"&&n.description?n.description:void 0;if(o!==void 0)this.toolLabels.set(e,{label:o.slice(0,gi),fromDescription:!0});else if(this.toolLabels.get(e)?.fromDescription!==!0){let i=typeof t.title=="string"&&t.title?t.title:typeof r?.toolName=="string"&&r.toolName?r.toolName:void 0;i!==void 0&&this.toolLabels.set(e,{label:i.slice(0,gi),fromDescription:!1})}for(;this.toolLabels.size>Uu;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now(),t=this.lastBackgroundTask,n=!1;for(let[i,a]of this.armedTasks)a.repeating||(this.armedTasks.delete(i),n=!0);n&&this.onArmedTasksChanged();let r={messageId:Pe(),startedAt:e,cause:t};this.unsolicitedTurn=r,this.promptStartedAt=e,this.logger?.info(`session ${this.sessionId} agent resumed with no prompt in flight`+(t?` (after ${t.label})`:""));let o={unsolicited:!0};t&&(o.cause=t),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"turn_started",messageId:r.messageId,_meta:{"hydra-acp":o}}})}async holdForUnsolicitedTurn(e){if(this.unsolicitedTurn===void 0)return;let t=Date.now(),n=this.unsolicitedTurn.cause;this.broadcastQueueNotification("hydra-acp/prompt_queue/held",{sessionId:this.sessionId,messageId:e.messageId,reason:"agent_resumed",...n?{cause:n}:{}});let r="turn_ended";for(;;){if(this.closing||this.closed){r="closing";break}if(e.cancelled){r="cancelled";break}if(this.unsolicitedTurn===void 0){r="turn_ended";break}await new Promise(o=>{let i=setTimeout(o,Wu);typeof i.unref=="function"&&i.unref()})}this.broadcastQueueNotification("hydra-acp/prompt_queue/released",{sessionId:this.sessionId,messageId:e.messageId,reason:r,heldMs:Date.now()-t})}closeUnsolicitedTurn(e){let t=this.unsolicitedTurn;t!==void 0&&(this.unsolicitedTurn=void 0,this.promptStartedAt=void 0,this.recordCurrentUsageSnapshot(),!this.closed&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"turn_ended",messageId:Pe(),startedMessageId:t.messageId,durationMs:Date.now()-t.startedAt,_meta:{"hydra-acp":{unsolicited:!0,reason:e}}}}))}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Du;){let n=this.recentlyTerminal.keys().next().value;if(n===void 0)break;this.recentlyTerminal.delete(n)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let n={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",n)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(n=>n.messageId===e&&n.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 n=this.visibleQueueDepth(),r=t?.position??Math.max(0,n-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:n,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let n of this.clients.values())n.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 n of this.promptQueue)n.kind!=="user"||n.cancelled||e.push({messageId:n.messageId,originator:n.originator,prompt:n.prompt,position:t++,enqueuedAt:n.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let n={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(n.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(n.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:n,clientId:n.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 n=this.promptQueue[t];return n.cancelled=!0,this.promptQueue.splice(t,1),n.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),n.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let n=this.promptQueue.find(r=>r.messageId===e);return!n||n.kind!=="user"?{updated:!1,reason:"not_found"}:(n.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let n=this.clients.get(e);if(!n)throw ge(new Error("client not attached"),C.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(n,o,r,i);let d=this.promptQueue.find(c=>c.messageId===r&&c.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let u=this.recentlyTerminal.get(r);return u?u.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(n,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,n,r){let o=Pe(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.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:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:n,position:1}),this.amendInProgress={cancelledMessageId:n,newMessageId:o},this.cancelExtensionDispatch(n,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let n=Pe(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:n,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),n}async cancel(e){if(!this.clients.get(e))throw ge(new Error("client not attached"),C.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),this.closeUnsolicitedTurn("cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(n=>n.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,n=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(n.has(d.name))continue;let u=`request:${e}`;if(!d.intercepts.has(u))continue;let c=`t_${Qs()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${d.name} error on ${u}: ${f.message}`);continue}let p=l?.action??"continue";if(p==="stop")return o==="notification"?void 0:l?.payload??Ys(e);if(p==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),n.add(d.name);continue}if(p==="processing"){let f=a,h=i,g=new Set(n);return new Promise(m=>{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,h,new Set([...g,d.name]),f+1,o).then(m).catch(()=>m(o==="notification"?void 0:Ys(e))))},kn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:m,timer:y,transformerName:d.name,method:e,envelope:h,chainIdx:f,originatedBy:g,side:"request",tailKind:o})})}n.add(d.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async forwardModelChange(e,t){let n=await Je({request:(r,o)=>this.forwardRequest(r,o),sessionId:this.sessionId,modelId:e,verb:this.modelVerb,extraParams:t,logger:this.logger});return this.modelVerb=n.verb,this.modelVerbConfirmed=!0,n.result}noteModelVerbHint(e,t){e===void 0||this.modelVerbConfirmed||e===this.modelVerb||(this.logger?.info(`model verb for agent ${this.agentId} inferred as ${e} from ${t} (was ${this.modelVerb})`),this.modelVerb=e)}resetModelVerb(e){this.modelVerb=e??Re,this.modelVerbConfirmed=!1}async runAgentRequestChain(e,t,n=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(n.has(d.name)||!d.intercepts.has(i))continue;let u=`t_${Qs()}`,c;try{c=await d.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${i}: ${p.message}`);continue}let l=c?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:c?.payload??ol(e)};if(l==="continue"){c?.payload&&typeof c.payload=="object"&&(o=c.payload),n.add(d.name);continue}if(l==="processing"){let p=a,f=o,h=new Set(n),g=e;return new Promise(m=>{let y=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:d.name}),this.runAgentRequestChain(g,f,new Set([...h,d.name]),p+1).then(m).catch(()=>m({shortCircuit:!1,envelope:f})))},kn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(u,{resolve:k=>m({shortCircuit:!0,payload:k}),timer:y,transformerName:d.name,method:g,envelope:f,chainIdx:p,originatedBy:h,side:"agent-request"})})}n.add(d.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let n=this.pendingClaims.get(e);return n?(clearTimeout(n.timer),this.pendingClaims.delete(e),n.resolve(t),!0):!1}keepAliveClaim(e,t){let n=this.pendingClaims.get(e);if(!n)return!1;clearTimeout(n.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):kn,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:n.transformerName}),n.side==="response")this.runResponseChain(n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1).then(()=>n.resolve(void 0)).catch(()=>n.resolve(void 0));else if(n.side==="agent-request")this.runAgentRequestChain(n.method,n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1).then(n.resolve).catch(()=>n.resolve({shortCircuit:!1,envelope:n.envelope}));else{let i=n.tailKind??"request";this.forwardRequest(n.method,n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1,i).then(n.resolve).catch(()=>n.resolve(i==="notification"?void 0:Ys(n.method)))}},r);return typeof o.unref=="function"&&o.unref(),n.timer=o,!0}async emitToChain(e,t,n){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(n,i,o);return}return this.forwardRequest(t,n,i,o)}async emitToQueue(e,t){let n=this.transformChain.findIndex(u=>u.name===e),r=n>=0?n+1:0,o=(t??{}).prompt??[],i=Pe(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((u,c)=>{let l={kind:"user",messageId:i,originator:d,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:u,reject:c},p=this.insertEntryAt(l,"tail");this.persistRewrite(),this.broadcastQueueAdded(l,{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){let t=this.turnStartedAt!==void 0;this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1} by=${e.by??"unknown"} midTurn=${t} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length} awaitingPermission=${this.hasPermissionFlag}`),t&&this.logger?.warn(`session ${this.sessionId} closed mid-turn by=${e.by??"unknown"}; the in-flight turn will not settle and the agent is being killed`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.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 n of this.titleHandlers)try{n(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded||it((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let r=mt((e??{}).prompt),o=Xs(r,200);o&&(o.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(o)))}maybeApplyAgentModel(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="current_model_update")return!1;let r=yt(n.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof n.currentModel=="string"?n.currentModel:typeof n.model=="string"?n.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="config_option_update")return!1;let r=n.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=yt(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=i.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(i.id==="mode"){let a=Ht(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=i.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 i.id=="string"&&i.id.trim()){let a=i.id.trim(),d=yt(i.options);if(d.length>0){let u=Ht(i.options),c=u.length>0?u.map(m=>({value:m.id,name:m.name??m.id})):d.map(m=>({value:m.modelId,name:m.name??m.modelId})),l=i.name,p=typeof l=="string"&&l.trim()?l.trim():a,f=i.currentValue,h=typeof f=="string"&&f.trim()?f.trim():c[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(m=>m.id===a);if(g>=0){let m={...this.agentAdvertisedConfigOptions[g]};m.options=c,typeof f=="string"&&f.trim()&&(m.currentValue=f.trim()),this.agentAdvertisedConfigOptions[g]=m}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:h,options:c})}}}return!0}maybeApplyAgentMode(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="current_mode_update")return!1;let r=typeof n.currentModeId=="string"?n.currentModeId:typeof n.currentMode=="string"?n.currentMode:typeof n.mode=="string"?n.mode:void 0;if(r===void 0)return!0;let o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof n.used=="number"&&r.used!==n.used&&(r.used=n.used,o=!0),typeof n.size=="number"&&r.size!==n.size&&(r.size=n.size,o=!0),n.cost&&typeof n.cost=="object"){let a=n.cost;typeof a.amount=="number"&&(this.reconcileCostLedger(a.amount)&&(o=!0),r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0)),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.persistableUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}armCostLedgerProbe(){let e=this._currentUsage?.costAmount;typeof e=="number"&&e>0&&(this.costLedgerProbe=e)}reconcileCostLedger(e){let t=this.costLedgerProbe;return t===void 0||(this.costLedgerProbe=void 0,e>=t-1e-6)?!1:(this.cumulativeCost+=t,!0)}notifyAgentChange(e){let t=this.retiringGenerationCost;this.retiringGenerationCost=void 0;for(let n of this.agentChangeHandlers)try{n({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...t!==void 0?{retiredCost:t}:{}})}catch(r){this.logger?.warn(`${e}: agentChange handler failed: ${r.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=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 n=this.currentUsage;if(n!==void 0){let r={sessionUpdate:"usage_update"};if(typeof n.used=="number"&&(r.used=n.used),typeof n.size=="number"&&(r.size=n.size),typeof n.costAmount=="number"||typeof n.costCurrency=="string"){let o={};typeof n.costAmount=="number"&&(o.amount=n.costAmount),typeof n.costCurrency=="string"&&(o.currency=n.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let n=t.update;if(n.sessionUpdate!=="usage_update"||!n.cost||typeof n.cost!="object")return e;let r=n.cost;return typeof r.amount!="number"?e:{...t,update:{...n,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Qu(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Gu(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(",")}]`),Ku(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 n of this.priorityHandlers)try{n(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 n={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(n.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:n}),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 n={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(n.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:n}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let n=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return n.some(r=>r.value===this.agentId)||n.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:n}),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 n=t.update,r=Array.isArray(n.configOptions)?[...n.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...n,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let n of pt){if(t.get(n.verb)!=="__hydra__")continue;let r=n.argsHint?`${n.verb} ${n.argsHint}`:n.verb;e.push({name:r,description:`Alias for '/hydra ${n.verb}': ${n.description}`})}if(this.extensionCommands)for(let{name:n,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${n} ${r.verb}`:`hydra ${n}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let d=n.startsWith("hydra-acp-")?n.slice(10):n;if(n.startsWith("hydra-acp-")&&d.length>0){let u=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,l={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(l.description=r.description),e.push(l)}if(d.length>0&&t.get(d)===n){let u=r.verb?`${d} ${r.verb}`:d,l={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(l.description=r.description),e.push(l)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name),d=a.startsWith("/")?a.slice(1):a;d&&e.add(d)}let n=new Map;for(let i of pt)e.has(i.verb)||n.set(i.verb,"__hydra__");if(!this.extensionCommands)return n;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||n.has(a))continue;let d=r.get(a);d===void 0?r.set(a,i):d!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&n.set(i,a);return n}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}agentKnowsSlashCommand(e){let t=r=>r.startsWith("/")?r.slice(1):r,n=t(e);if(!n)return!1;for(let r of this.agentAdvertisedCommands)if(t(r.name.split(/\s+/)[0]??"")===n)return!0;return!1}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="session_info_update"||typeof n.title!="string")return;let r=n.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(pt.some(l=>l.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return this.runAgentCommandInline(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"workspace":return this.runWorkspaceCommand(i);case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(i,t):this.runForkCommand(i);default:{let l=new Error(`no dispatcher for /hydra verb ${o}`);throw l.code=C.InternalError,l}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let d=`hydra-acp-${o}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,i,t):this.runExtensionCommand(d,i);let u=pt.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:p}of this.extensionCommands.list())l.has(p)||(u.push(p),l.add(p))}let c=new Error(`unknown /hydra verb: ${o} (known: ${u.join(", ")})`);throw c.code=C.InvalidParams,c}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,n){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(h=>h.verb===i)){let h=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${h||"(none)"})`)}let d={sessionId:this.sessionId,verb:i,args:a};n!==void 0&&(d.messageId=n);let u=()=>{},c=new Promise(h=>{u=h});n!==void 0&&this.inFlightExtensionDispatches.set(n,{extensionName:e,connection:r.connection,cancel:h=>u({stopReason:"cancelled",reason:h})});let l,p=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",d),g=await Promise.race([h,c]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=g}catch(h){return this.emitExtensionReply(`${e} ${i}: ${h.message}`)}finally{n!==void 0&&!p&&this.inFlightExtensionDispatches.delete(n)}let f=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return f.length>0?this.emitExtensionReply(f):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let n=this.inFlightExtensionDispatches.get(e);if(!n)return!1;this.inFlightExtensionDispatches.delete(e);try{n.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${n.extensionName} failed: ${r.message}`)}return n.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
43
+ `),this.workspacePreambleSent=!0}return r}async prompt(e,t,n){let r=this.clients.get(e);if(!r)throw me(new Error("client not attached"),x.SessionNotFound);if(this.closing)throw me(new Error("session is closing; new prompts cannot be accepted"),x.SessionClosing);let o=Pe();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Qe((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let a of this.interactiveHandlers)try{a(!0)}catch{}}return this.enqueueUserPrompt(r,t,o,n)}broadcastPromptReceived(e){this.closeUnsolicitedTurn("superseded",`prompt:${e.messageId}`);let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),e.originator.fromSession&&(t.fromSession=e.originator.fromSession),e.originator.fromSessionTitle&&(t.fromSessionTitle=e.originator.fromSessionTitle),e.originator.fromLabel&&(t.fromLabel=e.originator.fromLabel),e.originator.depth!==void 0&&(t.depth=e.originator.depth),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 n=ht(e.prompt);n.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},_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;t._meta={"hydra-acp":{upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}};let n={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:n,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,n,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Pe()};o!==void 0&&(i.stopReason=o);let a=Qe(t?._meta).salvaged;a!==void 0&&(i._meta={[ue]:{salvaged:a}}),this.supersededAutonomousTurn=void 0;let d=this.amendInProgress;d&&n!==void 0&&d.cancelledMessageId===n&&(i._meta={[ue]:{...a!==void 0?{salvaged:a}:{},amended:{cancelledMessageId:d.cancelledMessageId,newMessageId:d.newMessageId}}}),this.promptStartedAt=void 0,this.sawTurnComplete=!0,this.scheduleWorkspaceSnapshotHook?.(),n!==void 0&&o!==void 0&&this.recordTerminal(n,o),(o==="cancelled"||o==="error"||o==="refusal")&&this.closeOpenToolCalls(o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),d&&n!==void 0&&d.cancelledMessageId===n&&this.broadcastPromptAmended(d)}noteAgentActivity(e){if(!(this.closing||this.closed)){if(zu(e)){if(this.unsolicitedTurn!==void 0){this.closeUnsolicitedTurn("completed");return}this.salvageSupersededTerminal();return}Qs("session/update",e)||(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||this.openUnsolicitedTurn()))}}noteBackgroundTaskArming(e){let t=e?.update;if(!t||typeof t!="object")return;let n=typeof t.toolCallId=="string"?t.toolCallId:void 0;if(n===void 0)return;let r=t.rawInput,o=Yu(t._meta);this.rememberToolLabel(n,t,r,o),this.noteBackgroundTaskStopped(t,r,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:Ku(t.rawOutput);if(!(i!==void 0||r!==void 0&&r.run_in_background===!0))return;let d=this.toolLabels.get(n)?.label??"background task";this.lastBackgroundTask={toolCallId:n,label:d};let c=Date.now(),u=this.armedTasks.get(n),l=i??u?.taskId,f=Qu(t.title,o,r)||u?.repeating===!0;this.armedTasks.set(n,{label:d,...l!==void 0?{taskId:l}:{},repeating:f,armedAt:u?.armedAt??c}),this.onArmedTasksChanged()}get armedBackgroundTasks(){return[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{}}))}get armedSince(){let e;for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedTasks.size,t=this.armedSince;e===this.lastArmedBroadcast?.count&&t===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={count:e,since:t},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:e,...t!==void 0?{since:t}:{},tasks:this.armedBackgroundTasks}))}async retireAgent(e,t){return await e.kill().catch(()=>{}),this.discardArmedTasks(t)}discardArmedTasks(e){if(this.armedTasks.size===0)return[];let t=[...this.armedTasks.values()].map(n=>n.label);return this.armedTasks.clear(),this.logger?.info(`session ${this.sessionId} discarded ${t.length} armed task(s) on ${e}: ${t.join(", ")}`),this.onArmedTasksChanged(),t}noteBackgroundTaskStopped(e,t,n){if(!(n?.toolName==="TaskStop"||e.title==="TaskStop"))return;let o=t?.task_id;if(typeof o!="string"||o.length===0)return;let i=!1;for(let[a,d]of this.armedTasks)d.taskId===o&&(this.armedTasks.delete(a),i=!0);i&&this.onArmedTasksChanged()}rememberToolLabel(e,t,n,r){let o=n!==void 0&&typeof n.description=="string"&&n.description?n.description:void 0;if(o!==void 0)this.toolLabels.set(e,{label:o.slice(0,yi),fromDescription:!0});else if(this.toolLabels.get(e)?.fromDescription!==!0){let i=typeof t.title=="string"&&t.title?t.title:typeof r?.toolName=="string"&&r.toolName?r.toolName:void 0;i!==void 0&&this.toolLabels.set(e,{label:i.slice(0,yi),fromDescription:!1})}for(;this.toolLabels.size>Ju;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now(),t=this.lastBackgroundTask,n=!1;for(let[i,a]of this.armedTasks)a.repeating||(this.armedTasks.delete(i),n=!0);n&&this.onArmedTasksChanged();let r={messageId:Pe(),startedAt:e,cause:t};this.unsolicitedTurn=r,this.promptStartedAt=e,this.logger?.info(`session ${this.sessionId} agent resumed with no prompt in flight`+(t?` (after ${t.label})`:""));let o={unsolicited:!0};t&&(o.cause=t),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"turn_started",messageId:r.messageId,_meta:{"hydra-acp":o}}})}async holdForUnsolicitedTurn(e){if(this.unsolicitedTurn===void 0){this.logger?.info(`session ${this.sessionId} queue hold skipped for ${e.messageId} (no unsolicited turn open)`);return}let t=Date.now(),n=this.unsolicitedTurn.cause;this.logger?.info(`session ${this.sessionId} holding ${e.messageId} behind unsolicited turn ${this.unsolicitedTurn.messageId}`+(n?` cause=${JSON.stringify(n.label)}`:"")),this.broadcastQueueNotification("hydra-acp/prompt_queue/held",{sessionId:this.sessionId,messageId:e.messageId,reason:"agent_resumed",...n?{cause:n}:{}});let r="turn_ended";for(;;){if(this.closing||this.closed){r="closing";break}if(e.cancelled){r="cancelled";break}if(this.unsolicitedTurn===void 0){r="turn_ended";break}await new Promise(i=>{let a=setTimeout(i,Vu);typeof a.unref=="function"&&a.unref()})}let o=Date.now()-t;this.logger?.info(`session ${this.sessionId} released ${e.messageId} reason=${r} heldMs=${o}`),this.broadcastQueueNotification("hydra-acp/prompt_queue/released",{sessionId:this.sessionId,messageId:e.messageId,reason:r,heldMs:o})}closeUnsolicitedTurn(e,t){let n=this.unsolicitedTurn;if(n===void 0)return;let r=Date.now()-n.startedAt;this.unsolicitedTurn=void 0,this.promptStartedAt=void 0,this.logger?.info(`session ${this.sessionId} unsolicited turn ${n.messageId} closed reason=${e} durationMs=${r}`+(t?` by=${t}`:"")+(n.cause?` cause=${JSON.stringify(n.cause.label)}`:"")),e==="superseded"&&(this.supersededAutonomousTurn={turnMessageId:n.messageId,cause:n.cause,supersededAt:Date.now()}),this.recordCurrentUsageSnapshot(),!this.closed&&(e==="cancelled"&&this.closeOpenToolCalls("cancelled"),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"turn_ended",messageId:Pe(),startedMessageId:n.messageId,durationMs:r,_meta:{"hydra-acp":{unsolicited:!0,reason:e}}}}))}salvageSupersededTerminal(){let e=this.supersededAutonomousTurn;if(e===void 0)return;this.supersededAutonomousTurn=void 0;let t=this.autonomousSalvage;t!==void 0&&(this.autonomousSalvage=void 0,this.logger?.warn(`session ${this.sessionId} salvaged session/prompt from autonomous terminal (superseded turn ${e.turnMessageId}, ${Date.now()-e.supersededAt}ms earlier)`+(e.cause?` cause=${JSON.stringify(e.cause.label)}`:"")),t({stopReason:"end_turn",_meta:{[ue]:{salvaged:{reason:"autonomous_terminal",supersededMessageId:e.turnMessageId}}}}))}async awaitPromptResponse(e){if(this.supersededAutonomousTurn===void 0)return e;try{return await new Promise((t,n)=>{this.autonomousSalvage=t,e.then(t,n)})}finally{this.autonomousSalvage=void 0}}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Wu;){let n=this.recentlyTerminal.keys().next().value;if(n===void 0)break;this.recentlyTerminal.delete(n)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let n={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",n)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(n=>n.messageId===e&&n.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 n=this.visibleQueueDepth(),r=t?.position??Math.max(0,n-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:n,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let n of this.clients.values())n.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 n of this.promptQueue)n.kind!=="user"||n.cancelled||e.push({messageId:n.messageId,originator:n.originator,prompt:n.prompt,position:t++,enqueuedAt:n.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let n={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(n.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(n.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:n,clientId:n.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 n=this.promptQueue[t];return n.cancelled=!0,this.promptQueue.splice(t,1),n.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),n.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let n=this.promptQueue.find(r=>r.messageId===e);return!n||n.kind!=="user"?{updated:!1,reason:"not_found"}:(n.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let n=this.clients.get(e);if(!n)throw me(new Error("client not attached"),x.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(n,o,r,i);let d=this.promptQueue.find(u=>u.messageId===r&&u.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(n,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,n,r){let o=Pe(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:n,position:1}),this.amendInProgress={cancelledMessageId:n,newMessageId:o},this.cancelExtensionDispatch(n,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let n=Pe(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:n,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),n}async cancel(e){if(!this.clients.get(e))throw me(new Error("client not attached"),x.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),this.closeUnsolicitedTurn("cancelled"),this.agentTurnInFlight||this.closeOpenToolCalls("cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(n=>n.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,n=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(n.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let u=`t_${Gs()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=l?.action??"continue";if(f==="stop")return o==="notification"?void 0:l?.payload??Ys(e);if(f==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),n.add(d.name);continue}if(f==="processing"){let p=a,g=i,m=new Set(n);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.forwardRequest(e,g,new Set([...m,d.name]),p+1,o).then(h).catch(()=>h(o==="notification"?void 0:Ys(e))))},kn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(u,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:m,side:"request",tailKind:o})})}n.add(d.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async forwardModelChange(e,t){let n=await Je({request:(r,o)=>this.forwardRequest(r,o),sessionId:this.sessionId,modelId:e,verb:this.modelVerb,extraParams:t,logger:this.logger});return this.modelVerb=n.verb,this.modelVerbConfirmed=!0,n.result}noteModelVerbHint(e,t){e===void 0||this.modelVerbConfirmed||e===this.modelVerb||(this.logger?.info(`model verb for agent ${this.agentId} inferred as ${e} from ${t} (was ${this.modelVerb})`),this.modelVerb=e)}resetModelVerb(e){this.modelVerb=e??Re,this.modelVerbConfirmed=!1}async runAgentRequestChain(e,t,n=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(n.has(d.name)||!d.intercepts.has(i))continue;let c=`t_${Gs()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(f){this.logger?.warn(`transformer ${d.name} error on ${i}: ${f.message}`);continue}let l=u?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:u?.payload??cl(e)};if(l==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),n.add(d.name);continue}if(l==="processing"){let f=a,p=o,g=new Set(n),m=e;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.runAgentRequestChain(m,p,new Set([...g,d.name]),f+1).then(h).catch(()=>h({shortCircuit:!1,envelope:p})))},kn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:k=>h({shortCircuit:!0,payload:k}),timer:y,transformerName:d.name,method:m,envelope:p,chainIdx:f,originatedBy:g,side:"agent-request"})})}n.add(d.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let n=this.pendingClaims.get(e);return n?(clearTimeout(n.timer),this.pendingClaims.delete(e),n.resolve(t),!0):!1}keepAliveClaim(e,t){let n=this.pendingClaims.get(e);if(!n)return!1;clearTimeout(n.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):kn,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:n.transformerName}),n.side==="response")this.runResponseChain(n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1).then(()=>n.resolve(void 0)).catch(()=>n.resolve(void 0));else if(n.side==="agent-request")this.runAgentRequestChain(n.method,n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1).then(n.resolve).catch(()=>n.resolve({shortCircuit:!1,envelope:n.envelope}));else{let i=n.tailKind??"request";this.forwardRequest(n.method,n.envelope,new Set([...n.originatedBy,n.transformerName]),n.chainIdx+1,i).then(n.resolve).catch(()=>n.resolve(i==="notification"?void 0:Ys(n.method)))}},r);return typeof o.unref=="function"&&o.unref(),n.timer=o,!0}async emitToChain(e,t,n){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(n,i,o);return}return this.forwardRequest(t,n,i,o)}async emitToQueue(e,t){let n=this.transformChain.findIndex(c=>c.name===e),r=n>=0?n+1:0,o=(t??{}).prompt??[],i=Pe(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((c,u)=>{let l={kind:"user",messageId:i,originator:d,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:c,reject:u},f=this.insertEntryAt(l,"tail");this.persistRewrite(),this.broadcastQueueAdded(l,{position:f}),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){let t=this.turnStartedAt!==void 0;this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1} by=${e.by??"unknown"} midTurn=${t} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length} awaitingPermission=${this.hasPermissionFlag}`),t&&this.logger?.warn(`session ${this.sessionId} closed mid-turn by=${e.by??"unknown"}; the in-flight turn will not settle and the agent is being killed`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.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 n of this.titleHandlers)try{n(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded||Qe((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let r=ht((e??{}).prompt),o=Xs(r,200);o&&(o.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(o)))}maybeApplyAgentModel(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="current_model_update")return!1;let r=yt(n.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof n.currentModel=="string"?n.currentModel:typeof n.model=="string"?n.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="config_option_update")return!1;let r=n.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=yt(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(i.id==="mode"){let a=Ht(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),d=yt(i.options);if(d.length>0){let c=Ht(i.options),u=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),l=i.name,f=typeof l=="string"&&l.trim()?l.trim():a,p=i.currentValue,g=typeof p=="string"&&p.trim()?p.trim():u[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=u,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:g,options:u})}}}return!0}maybeApplyAgentMode(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="current_mode_update")return!1;let r=typeof n.currentModeId=="string"?n.currentModeId:typeof n.currentMode=="string"?n.currentMode:typeof n.mode=="string"?n.mode:void 0;if(r===void 0)return!0;let o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof n.used=="number"&&r.used!==n.used&&(r.used=n.used,o=!0),typeof n.size=="number"&&r.size!==n.size&&(r.size=n.size,o=!0),n.cost&&typeof n.cost=="object"){let a=n.cost;typeof a.amount=="number"&&(this.reconcileCostLedger(a.amount)&&(o=!0),r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0)),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.persistableUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}armCostLedgerProbe(){let e=this._currentUsage?.costAmount;typeof e=="number"&&e>0&&(this.costLedgerProbe=e)}reconcileCostLedger(e){let t=this.costLedgerProbe;return t===void 0||(this.costLedgerProbe=void 0,e>=t-1e-6)?!1:(this.cumulativeCost+=t,!0)}notifyAgentChange(e,t,n){let r=this.retiringGenerationCost;this.retiringGenerationCost=void 0;for(let o of this.agentChangeHandlers)try{o({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...r!==void 0?{retiredCost:r}:{},...t!==void 0?{reason:t}:{},...n!==void 0?{runId:n}:{}})}catch(i){this.logger?.warn(`${e}: agentChange handler failed: ${i.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=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 n of this.usageHandlers)try{n(t)}catch{}this.broadcastCurrentUsage()}broadcastCurrentUsage(){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 n={};typeof e.costAmount=="number"&&(n.amount=e.costAmount),typeof e.costCurrency=="string"&&(n.currency=e.costCurrency),t.cost=n}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:t})}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let n=t.update;if(n.sessionUpdate!=="usage_update"||!n.cost||typeof n.cost!="object")return e;let r=n.cost;return typeof r.amount!="number"?e:{...t,update:{...n,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Xu(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Zu(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(",")}]`),el(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 n of this.priorityHandlers)try{n(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 n={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(n.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:n}),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 n={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(n.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:n}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let n=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return n.some(r=>r.value===this.agentId)||n.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:n}),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 n=t.update,r=Array.isArray(n.configOptions)?[...n.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...n,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let n of ft){if(t.get(n.verb)!=="__hydra__")continue;let r=n.argsHint?`${n.verb} ${n.argsHint}`:n.verb;e.push({name:r,description:`Alias for '/hydra ${n.verb}': ${n.description}`})}if(this.extensionCommands)for(let{name:n,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${n} ${r.verb}`:`hydra ${n}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let d=n.startsWith("hydra-acp-")?n.slice(10):n;if(n.startsWith("hydra-acp-")&&d.length>0){let c=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}if(d.length>0&&t.get(d)===n){let c=r.verb?`${d} ${r.verb}`:d,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name),d=a.startsWith("/")?a.slice(1):a;d&&e.add(d)}let n=new Map;for(let i of ft)e.has(i.verb)||n.set(i.verb,"__hydra__");if(!this.extensionCommands)return n;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||n.has(a))continue;let d=r.get(a);d===void 0?r.set(a,i):d!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&n.set(i,a);return n}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}agentKnowsSlashCommand(e){let t=r=>r.startsWith("/")?r.slice(1):r,n=t(e);if(!n)return!1;for(let r of this.agentAdvertisedCommands)if(t(r.name.split(/\s+/)[0]??"")===n)return!0;return!1}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="session_info_update"||typeof n.title!="string")return;let r=n.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(ft.some(l=>l.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return this.runAgentCommandInline(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"workspace":return this.runWorkspaceCommand(i);case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(i,t):this.runForkCommand(i);default:{let l=new Error(`no dispatcher for /hydra verb ${o}`);throw l.code=x.InternalError,l}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let d=`hydra-acp-${o}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,i,t):this.runExtensionCommand(d,i);let c=ft.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:f}of this.extensionCommands.list())l.has(f)||(c.push(f),l.add(f))}let u=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw u.code=x.InvalidParams,u}runExtensionCommand(e,t){return this.enqueuePrompt(`extension:${e}`,()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,n){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(g=>g.verb===i)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:i,args:a};n!==void 0&&(d.messageId=n);let c=()=>{},u=new Promise(g=>{c=g});n!==void 0&&this.inFlightExtensionDispatches.set(n,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let l,f=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,u]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=m}catch(g){return this.emitExtensionReply(`${e} ${i}: ${g.message}`)}finally{n!==void 0&&!f&&this.inFlightExtensionDispatches.delete(n)}let p=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let n=this.inFlightExtensionDispatches.get(e);if(!n)return!1;this.inFlightExtensionDispatches.delete(e);try{n.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${n.extensionName} failed: ${r.message}`)}return n.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
42
44
  ${e}
43
45
  `},_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 n=t.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",d=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${d}`});e=`Sessions (${t.length}):
44
46
  ${n.join(`
@@ -48,41 +50,41 @@ ${e}
48
50
  ${t.join(`
49
51
  `)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
50
52
  ${n}
51
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let d=i?o.some(c=>c.modelId===i):!0,u=o.map(c=>{let l=c.modelId===i?"\u25B6 ":" ",p=c.name&&c.name!==c.modelId?` ${c.name}`:"";return`${l}${c.modelId}${p}`});!d&&i&&u.unshift(`\u25B6 ${i}`),a=u.join(`
53
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let d=i?o.some(u=>u.modelId===i):!0,c=o.map(u=>{let l=u.modelId===i?"\u25B6 ":" ",f=u.name&&u.name!==u.modelId?` ${u.name}`:"";return`${l}${u.modelId}${f}`});!d&&i&&c.unshift(`\u25B6 ${i}`),a=c.join(`
52
54
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
53
55
  ${a}
54
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let n=gt(t,this.agentAdvertisedModels),r=t;if(n.kind==="resolved")r=n.modelId;else if(n.kind==="ambiguous"||n.kind==="unknown"){let o=this.agentAdvertisedModels.map(l=>l.modelId),i=t.toLowerCase(),a=n.kind==="ambiguous"?n.candidates:o.filter(l=>l.toLowerCase().includes(i)),d=a.length>0?a:o,u=n.kind==="ambiguous"?`"${t}" matches multiple models: ${n.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,c=n.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
55
- ${u}.
56
- ${c}:
56
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let n=gt(t,this.agentAdvertisedModels),r=t;if(n.kind==="resolved")r=n.modelId;else if(n.kind==="ambiguous"||n.kind==="unknown"){let o=this.agentAdvertisedModels.map(l=>l.modelId),i=t.toLowerCase(),a=n.kind==="ambiguous"?n.candidates:o.filter(l=>l.toLowerCase().includes(i)),d=a.length>0?a:o,c=n.kind==="ambiguous"?`"${t}" matches multiple models: ${n.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,u=n.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
+ ${c}.
58
+ ${u}:
57
59
  ${d.join(`
58
60
  `)}
59
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardModelChange(r),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(u=>u.id===o):!0,d=r.map(u=>{let c=u.id===o?"\u25B6 ":" ",l=u.name&&u.name!==u.id?` ${u.name}`:"";return`${c}${u.id}${l}`});!a&&o&&d.unshift(`\u25B6 ${o}`),i=d.join(`
61
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardModelChange(r),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(c=>c.id===o):!0,d=r.map(c=>{let u=c.id===o?"\u25B6 ":" ",l=c.name&&c.name!==c.id?` ${c.name}`:"";return`${u}${c.id}${l}`});!a&&o&&d.unshift(`\u25B6 ${o}`),i=d.join(`
60
62
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
61
63
  ${i}
62
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let n=this.agentAdvertisedModes;if(n.length>0&&!n.some(r=>r.id===t)){let r=n.map(o=>o.id).join(", ");throw ge(new Error(`unknown mode: ${t} (known: ${r})`),C.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]*))?$/),n=t?.[1],r=t?.[2]??"";if(!n){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:`
64
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let n=this.agentAdvertisedModes;if(n.length>0&&!n.some(r=>r.id===t)){let r=n.map(o=>o.id).join(", ");throw me(new Error(`unknown mode: ${t} (known: ${r})`),x.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]*))?$/),n=t?.[1],r=t?.[2]??"";if(!n){let u=this.buildConfigOptions();if(u.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
63
65
  _(no config options advertised yet)_
64
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let l=c.map(p=>yi(p));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
66
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let l=u.map(f=>bi(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
65
67
  ${l.join(`
66
68
 
67
69
  `)}
68
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let o=this.buildConfigOptions(),i=o.find(c=>c.id===n);if(!i){let c=o.map(l=>l.id).join(`
70
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let o=this.buildConfigOptions(),i=o.find(u=>u.id===n);if(!i){let u=o.map(l=>l.id).join(`
69
71
  `);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
70
72
  "${n}" is not a known config option.
71
73
  Available options:
72
- ${c}
74
+ ${u}
73
75
  `},_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:`
74
- ${yi(i)}
75
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(c=>c.value),d=Hs(r,a),u=r;if(d.kind==="resolved")u=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let c=r.toLowerCase(),l=d.kind==="ambiguous"?d.candidates:a.filter(g=>g.toLowerCase().includes(c)),p=l.length>0?l:a,f=d.kind==="ambiguous"?`"${r}" matches multiple values for "${n}": ${d.candidates.join(", ")}`:l.length>0?`"${r}" is not a valid value for "${n}". Did you mean`:`"${r}" is not a valid value for "${n}"`,h=d.kind==="ambiguous"||l.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
76
- ${f}.
77
- ${h}:
78
- ${p.join(`
76
+ ${bi(i)}
77
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(u=>u.value),d=Hs(r,a),c=r;if(d.kind==="resolved")c=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let u=r.toLowerCase(),l=d.kind==="ambiguous"?d.candidates:a.filter(m=>m.toLowerCase().includes(u)),f=l.length>0?l:a,p=d.kind==="ambiguous"?`"${r}" matches multiple values for "${n}": ${d.candidates.join(", ")}`:l.length>0?`"${r}" is not a valid value for "${n}". Did you mean`:`"${r}" is not a valid value for "${n}"`,g=d.kind==="ambiguous"||l.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
78
+ ${p}.
79
+ ${g}:
80
+ ${f.join(`
79
81
  `)}
80
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return n==="model"?(u!==this.currentModel&&await this.forwardModelChange(u),this.applyModelChange(u),{stopReason:"end_turn"}):n==="mode"?(u!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:u}),this.applyModeChange(u),{stopReason:"end_turn"}):n==="agent"?(u!==this.agentId&&await this.runAgentCommandInline(u),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:n,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.runAgentCommandInline(e)}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw ge(new Error("/hydra agent requires an agent id"),C.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw ge(new Error(`already on agent ${r}`),C.InvalidParams);if(!this.scheduleCompactionHook)return this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"};this.scheduleCompactionHook({targetAgentId:r});let o=this.promptInFlight||this.unsolicitedTurn!==void 0;return this.emitExtensionReply(o?`Agent switch to ${r} scheduled. A turn is still in flight \u2014 the rotation lands on the next idle edge; cancel the turn to make that happen now.`:`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{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,by:"/hydra kill"}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw ge(new Error("agent restart not configured for this session"),C.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 n=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(n.join(`
81
- `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runWorkspaceCommand(e){if(!this.workspaceHook)return this.emitExtensionReply("Workspaces are not available on this session (no workspace hook configured)."),{stopReason:"end_turn"};let[t="status",...n]=e.split(/\s+/).filter(d=>d.length>0);if(!pi.includes(t))return this.emitExtensionReply(`Unknown workspace verb "${t}". Use one of: ${pi.join(", ")}.`),{stopReason:"end_turn"};let r=n.filter(d=>d.startsWith("--")),o=r.filter(d=>d!=="--clean"&&d!=="--deep");if(o.length>0)return this.emitExtensionReply(`Unknown workspace flag(s) ${o.join(", ")}. Supported: --clean (start), --deep (clean).`),{stopReason:"end_turn"};let i={clean:r.includes("--clean"),deep:r.includes("--deep")};if(i.clean&&t!=="start")return this.emitExtensionReply(`--clean applies to \`start\`, not to \`${t}\`.`),{stopReason:"end_turn"};if(i.deep&&t!=="clean")return this.emitExtensionReply(`--deep applies to \`clean\`, not to \`${t}\`.`),{stopReason:"end_turn"};let a=n.filter(d=>!d.startsWith("--")).join(" ").trim();try{let d=await this.workspaceHook(t,a.length>0?a:void 0,i);this.emitExtensionReply(d)}catch(d){this.emitExtensionReply(`Workspace ${t} failed: ${d instanceof Error?d.message:String(d)}`)}return{stopReason:"end_turn"}}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),n;for(let r of t){if(r.method!=="session/update")continue;let i=r.params?.update?.messageId;if(typeof i=="string"){if(i===e)return n;n=i}}}async runForkCommandInline(e,t){if(!this.forkHook)return this.emitExtensionReply("Fork not configured for this session."),{stopReason:"end_turn"};let n=(e??"").trim(),r;if(n==="verbatim")r="verbatim";else if(n==="synthesis"||n==="")r=void 0;else return this.emitExtensionReply(`Unknown fork argument: \`${n}\`. Use \`/hydra fork\` or \`/hydra fork verbatim\`.`),{stopReason:"end_turn"};try{let o={};if(r&&(o.mode=r),t&&this.historyStore){let d=await this.findMessageIdBefore(t).catch(()=>{});d&&(o.forkAt=d)}let a=(await this.forkHook(Object.keys(o).length>0?o:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(`Forked to [\`${a}\`](hydra://sessions/${a}).`)}catch(o){this.emitExtensionReply(`Fork failed: ${o instanceof Error?o.message:String(o)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ge(new Error("session is closing"),C.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1,by:"force-cancel"}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,n=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.resetModelVerb(r.modelVerb),this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await o.kill().catch(()=>{}),n&&await this.runInternalPrompt(n).catch(()=>{}),this.broadcastAgentSwitch(t,t);let i={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,t){let n=[],r=await this.getHistorySnapshot();for(let u of r){if(u.method!=="session/update")continue;let l=(u.params??{}).update;if(!l||l._meta?.["hydra-acp"]?.synthetic)continue;let f=l.sessionUpdate;if(f==="prompt_received"){let h=mt(l.prompt);h&&n.push({speaker:"user",text:h})}else if(f==="agent_message_chunk"){let g=l.content?.text;g&&n.push({speaker:`agent: ${e}`,text:g})}else if(f==="tool_call"||f==="tool_call_update"){let h=l.status,g=l.title;(h==="completed"||h==="failed")&&n.push({speaker:"tool",text:`${g??"?"} ${h}`})}}if(n.length===0)return"";let o=[],i;for(let u of n)i&&i.speaker===u.speaker?i.text+=u.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:u.speaker,text:u.text});i&&o.push(`<${i.speaker}>: ${i.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,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 ---",...o,"--- end transcript ---"].join(`
82
- `)}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)",n=[];if(this.historyStore)try{n=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=zs({synopsis:e,title:t,tail:n,tailK:Ou,tailFloor:Hu,watermark:this._summarizedThroughEntry,recallArmed:(this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let n=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),n!==void 0&&(r.filePath=n),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...n!==void 0?{filePath:n}:{},fileCapBytes:e.fileCapBytes}})};let o=new yn(r);this.streamBuffer=o,this.streamFilePath=n;let i={capacityBytes:o.capacity};return n!==void 0&&(i.filePath=n),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let n=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");n.append(r)}return t===!0&&n.close(),{writeCursor:n.writeCursorPos}}async streamRead(e,t,n){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??ft,ft)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&n!==void 0&&n>0){let d=await r.waitForData(i.nextCursor,n);(d==="data"||d==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let n=this.requireStreamBuffer().tail(e);return{bytes:n.bytes.toString("base64"),startCursor:n.startCursor,endCursor:n.endCursor,truncated:n.truncated}}streamHead(e){let n=this.requireStreamBuffer().head(e);return{bytes:n.bytes.toString("base64"),startCursor:n.startCursor,endCursor:n.endCursor,truncated:n.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=C.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closeUnsolicitedTurn("closed"),e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let o of n){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>fi(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>vi.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,n){this._setAttentionFlag(e,t,n,!0)}_setAttentionFlag(e,t,n,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(n))return;this.attentionFlags.set(o,{...i,payload:n,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:n});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,n){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&n&&(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.hasWorkInFlight){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},n=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${n}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()}get currentPromptDepth(){if(this.currentEntry?.kind==="user")return this.currentEntry.originator.depth??0}get hasWorkInFlight(){return this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0}onIdle(e,t){let n={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(n),()=>{let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1),n.timer&&(clearTimeout(n.timer),n.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let n of this.idleHandlers)n.timer&&(clearTimeout(n.timer),n.timer=void 0);return}let t=[...this.idleHandlers];for(let n of t){if(n.debounceMs===0){if(n.once){let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1)}try{n.fn(this)}catch{}continue}n.timer&&(clearTimeout(n.timer),n.timer=void 0),n.timer=setTimeout(()=>{if(n.timer=void 0,!this.closed&&this.isQuiescedSync()){if(n.once){let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1)}try{n.fn(this)}catch{}}},n.debounceMs),typeof n.timer.unref=="function"&&n.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 n=t,r=typeof n.sessionUpdate=="string"?n.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof n.toolCallId=="string"&&n.toolCallId.length>0?n.toolCallId:void 0;if(!o)return;let i=typeof n.kind=="string"?n.kind:void 0;this.toolCallKind.note(o,i);let a=this.toolCallKind.effective(o,i);if(a===Ko&&Array.isArray(n.locations))for(let c of n.locations){if(!c||typeof c!="object")continue;let l=c.path;if(typeof l!="string"||l.length===0||this.filesEditedSeen.has(l))continue;this.filesEditedSeen.add(l);let p=c.line,f={path:l,toolCallId:o};typeof p=="number"&&(f.line=p),this.notifyChain("file.edited",f),this.reportIsolationBreach(l,o)}if(r!=="tool_call_update")return;let d=typeof n.status=="string"?n.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,d);let u={toolCallId:o,status:d};a&&(u.kind=a),n.content!==void 0&&(u.content=n.content),Array.isArray(n.locations)&&(u.locations=n.locations),this.notifyChain("tool.completed",u)}notifyChain(e,t){let n=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(n)&&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,n){let r=this.rewriteForClient(t),o=!Gs(e,r),i=o?el(e,r):r,a=Date.now(),d=o?We(i,a):i;if(o){let u={method:e,params:i,recordedAt:a};if(this.lastRecordedAt=u.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,u).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(u)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let u of this.clients.values())n&&u.clientId===n||u.connection.notify(e,d).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ge(new Error("no clients attached to handle permission request"),C.PermissionDenied);let n=this.rewriteForClient(e),r=hi(n),o=Pe(),{toolCall:i,options:a}=n??{};return new Promise((d,u)=>{let c=!1,l=[],p=0,f,h=this.sessionId,g=k=>{c||(c=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),k())},m=k=>k?.code===C.MethodNotFound;function y(k){if(c)return;let w=k.connection.request("session/request_permission",n);l.push({client:k}),p++,w.then(b=>{p--,g(()=>{let v=tl({toolCallId:r,result:b,resolver:k});for(let S of l)S.client.clientId!==k.clientId&&S.client.connection.notify("session/update",{sessionId:h,update:v}).catch(()=>{});d(b)})}).catch(b=>{if(p--,m(b)||(f=b),p===0&&!c){let v=f??ge(new Error("no client handled permission request"),C.PermissionDenied);g(()=>u(v))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,y);for(let k of t)y(k)})}async enqueuePrompt(e){return new Promise((t,n)=>{let r={kind:"internal",messageId:Pe(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:n};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,n,r){let o=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r?.fromSession&&(i.fromSession=r.fromSession),r?.fromSessionTitle&&(i.fromSessionTitle=r.fromSessionTitle),r?.fromLabel&&(i.fromLabel=r.fromLabel),r?.depth!==void 0&&(i.depth=r.depth);let a=this.parseQueuePosition(t);return new Promise((d,u)=>{let c={kind:"user",messageId:n,originator:i,clientId:e.clientId,prompt:o,enqueuedAt:Date.now(),cancelled:!1,resolve:d,reject:u},l=this.insertEntryAt(c,a);this.persistRewrite(),this.broadcastQueueAdded(c,{position:l}),this.drainQueue()})}promptCarriesSentBy(e){if(!e||typeof e!="object")return!1;let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t[be];if(!n||typeof n!="object"||Array.isArray(n))return!1;let r=n.sentBy;return!!r&&typeof r=="object"}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let n=t["hydra-acp"];if(!n||typeof n!="object"||Array.isArray(n))return"tail";let r=n.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let n=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),n;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),n+o+1}return this.promptQueue.push(e),n+this.promptQueue.length-1}persistRewrite(){let e=[];for(let n of this.promptQueue)n.kind!=="user"||n.cancelled||e.push(this.persistedFromEntry(n));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ot(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[0];if(e?.kind==="user"&&(await this.holdForUnsolicitedTurn(e),this.closing))break;let t=this.promptQueue.shift();if(!t)break;if(!t.cancelled){this.currentEntry=t,t.kind==="user"&&this.persistRewrite(),t.kind==="user"&&this.broadcastQueueRemoved(t.messageId,"started");try{let n=await this.runQueueEntry(t);t.resolve(n),await new Promise(r=>setImmediate(r))}catch(n){t.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return this.closeUnsolicitedTurn("superseded"),e.task();this.broadcastPromptReceived(e);let t=mt(e.prompt).replace(/\s+$/,""),n=!t.includes(`
83
- `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=n.startsWith("/")?n.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(n==="/model"||n==="/mode"||n==="/sessions"||n==="/help"||n==="/hydra"||o){let d;if(n==="/sessions")d=await this.handleSessionsCommand();else if(n==="/help")d=await this.handleHelpCommand();else if(n==="/mode")d=await this.handleModeCommand(t);else if(n==="/model")d=await this.handleModelCommand(t);else if(o){let u=t.slice(n.length).trim(),c=u?`/hydra ${r} ${u}`:`/hydra ${r}`;d=await this.handleSlashCommand(c,e.messageId)}else d=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,d,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),d}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i=e.prompt;n&&this.agentAdvertisedCommands.length>0&&!this.agentKnowsSlashCommand(n)&&(i=Ks(e.prompt,rl));let a;this.agentTurnInFlight=!0;try{i=this.applyWorkspacePromptRewrite(i),a=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:i},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(d){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),d}finally{this.agentTurnInFlight=!1}return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function ge(s,e){return s.code=e,s}var qu=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 zu(s,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||s==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function Ju(s){return typeof s!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(s)?.[1]}function Vu(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.claudeCode;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};return t.toolName!==void 0&&(n.toolName=t.toolName),t.toolResponse&&typeof t.toolResponse=="object"&&(n.toolResponse=t.toolResponse),n}function Gs(s,e){if(s!=="session/update")return!1;let n=(e??{}).update?.sessionUpdate;return typeof n=="string"&&qu.has(n)}function Qu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function Gu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.id!==e[t]?.id||s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function Ku(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.modelId!==e[t]?.modelId||s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function yt(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object"||Array.isArray(t))continue;let n=t,r=typeof n.modelId=="string"&&n.modelId.trim()||typeof n.value=="string"&&n.value.trim()||typeof n.id=="string"&&n.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof n.name=="string"&&n.name.length>0&&(o.name=n.name),typeof n.description=="string"&&n.description.length>0&&(o.description=n.description),e.push(o)}return e}function Ht(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object"||Array.isArray(t))continue;let n=t,r=typeof n.value=="string"&&n.value.trim()||typeof n.id=="string"&&n.id.trim()||void 0;if(!r)continue;let o={id:r};typeof n.name=="string"&&n.name.length>0&&(o.name=n.name),typeof n.description=="string"&&n.description.length>0&&(o.description=n.description),e.push(o)}return e}function Yu(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let n=t.availableModes;if(!Array.isArray(n))return[];let r=[];for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function Xu(s,e){let n=(e??{}).update??{},r=n.sessionUpdate;if(r==="agent_message_chunk"){let o=n.content??{};typeof o.text=="string"&&(s.chunks.push(o.text),s.messageChars+=o.text.length);return}if(r==="agent_thought_chunk"){let o=n.content??{};typeof o.text=="string"&&(s.thinkingChars+=o.text.length);return}if(r==="tool_call"){s.toolCalls++;return}if(r==="usage_update"){typeof n.used=="number"&&(s.lastUsed=n.used),typeof n.size=="number"&&(s.lastSize=n.size);return}}function Zu(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let n=t.availableCommands??t.commands;if(!Array.isArray(n))return[];let r=[];for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function el(s,e){if(s!=="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:Pe()}}}function bn(s,e){for(let t=0;t<s.length;t++){let n=s[t];if(!n||n.method!=="session/update")continue;if(n.params?.update?.messageId===e)return t}return-1}function hi(s){if(!s||typeof s!="object")return;let e=s.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function tl(s){let e=nl(s.result),t={sessionUpdate:"permission_resolved"};return s.toolCallId!==void 0&&(t.toolCallId=s.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=sl(s.resolver),t}function nl(s){if(!s||typeof s!="object")return;let e=s.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let n={kind:t},r=e.optionId;typeof r=="string"&&(n.optionId=r);let o=e.reason;return typeof o=="string"&&(n.reason=o),n}function sl(s){let e={clientId:s.clientId};return s.clientInfo?.name&&(e.name=s.clientInfo.name),s.clientInfo?.version&&(e.version=s.clientInfo.version),e}function mt(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}var rl="\u200B";function mi(s,e){return s.map(t=>{if(t&&typeof t=="object"&&typeof t.text=="string"){let n=t;return{...n,text:e(n.text)}}return t})}function Ks(s,e){let t=s.findIndex(o=>o&&typeof o=="object"&&typeof o.text=="string");if(t<0)return s;let n=s[t],r=[...s];return r[t]={...n,text:`${e}${n.text}`},r}function Ys(s){return s==="session/prompt"?{stopReason:"stopped"}:{}}function ol(s){return s==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function yi(s){let e=s.name&&s.name!==s.id?`${s.id} (${s.name}) \u2014 \u25B6 ${s.currentValue}`:`${s.id} \u2014 \u25B6 ${s.currentValue}`;if(s.options.length===0)return e;let t=Math.max(...s.options.map(r=>r.value.length)),n=s.options.map(r=>{let o=r.value===s.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
82
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return n==="model"?(c!==this.currentModel&&await this.forwardModelChange(c),this.applyModelChange(c),{stopReason:"end_turn"}):n==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):n==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:n,value:c}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt("title",()=>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.runAgentCommandInline(e)}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw me(new Error("/hydra agent requires an agent id"),x.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw me(new Error(`already on agent ${r}`),x.InvalidParams);if(!this.scheduleCompactionHook)return this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"};this.scheduleCompactionHook({targetAgentId:r});let o=this.promptInFlight||this.unsolicitedTurn!==void 0;return this.emitExtensionReply(o?`Agent switch to ${r} scheduled. A turn is still in flight \u2014 the rotation lands on the next idle edge; cancel the turn to make that happen now.`:`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{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,by:"/hydra kill"}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt("restart",()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw me(new Error("agent restart not configured for this session"),x.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt("compact",()=>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,n=await this.getUpstreamGenerationsHook?.()??[],r=ci(n,t),o=ui(r);if(e==null&&t==null&&o.length===0)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};let i=[];return e==null?i.push(`No compaction in progress. Last summarized through entry: ${t??0}`):(i.push(`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`),e.lastError!==void 0&&i.push(`Last error: ${e.lastError}`)),i.push(`Current upstream: ${this.upstreamSessionId}`),o.length>0&&i.push("",...o),this.emitExtensionReply(i.join(`
83
+ `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt("uncompact",()=>this.runUncompactCommandInline())}async runWorkspaceCommand(e){if(!this.workspaceHook)return this.emitExtensionReply("Workspaces are not available on this session (no workspace hook configured)."),{stopReason:"end_turn"};let[t="status",...n]=e.split(/\s+/).filter(d=>d.length>0);if(!hi.includes(t))return this.emitExtensionReply(`Unknown workspace verb "${t}". Use one of: ${hi.join(", ")}.`),{stopReason:"end_turn"};let r=n.filter(d=>d.startsWith("--")),o=r.filter(d=>d!=="--clean"&&d!=="--deep");if(o.length>0)return this.emitExtensionReply(`Unknown workspace flag(s) ${o.join(", ")}. Supported: --clean (start), --deep (clean).`),{stopReason:"end_turn"};let i={clean:r.includes("--clean"),deep:r.includes("--deep")};if(i.clean&&t!=="start")return this.emitExtensionReply(`--clean applies to \`start\`, not to \`${t}\`.`),{stopReason:"end_turn"};if(i.deep&&t!=="clean")return this.emitExtensionReply(`--deep applies to \`clean\`, not to \`${t}\`.`),{stopReason:"end_turn"};let a=n.filter(d=>!d.startsWith("--")).join(" ").trim();try{let d=await this.workspaceHook(t,a.length>0?a:void 0,i);this.emitExtensionReply(d)}catch(d){this.emitExtensionReply(`Workspace ${t} failed: ${d instanceof Error?d.message:String(d)}`)}return{stopReason:"end_turn"}}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("fork",()=>this.runForkCommandInline(e,void 0))}async findMessageIdBefore(e){if(!this.historyStore)return;let t=await this.historyStore.load(this.sessionId),n;for(let r of t){if(r.method!=="session/update")continue;let i=r.params?.update?.messageId;if(typeof i=="string"){if(i===e)return n;n=i}}}async runForkCommandInline(e,t){if(!this.forkHook)return this.emitExtensionReply("Fork not configured for this session."),{stopReason:"end_turn"};let n=(e??"").trim(),r;if(n==="verbatim")r="verbatim";else if(n==="synthesis"||n==="")r=void 0;else return this.emitExtensionReply(`Unknown fork argument: \`${n}\`. Use \`/hydra fork\` or \`/hydra fork verbatim\`.`),{stopReason:"end_turn"};try{let o={};if(r&&(o.mode=r),t&&this.historyStore){let d=await this.findMessageIdBefore(t).catch(()=>{});d&&(o.forkAt=d)}let a=(await this.forkHook(Object.keys(o).length>0?o:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(`Forked to [\`${a}\`](hydra://sessions/${a}).`)}catch(o){this.emitExtensionReply(`Fork failed: ${o instanceof Error?o.message:String(o)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw me(new Error("session is closing"),x.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1,by:"force-cancel"}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,n=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.resetModelVerb(r.modelVerb),this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await this.retireAgent(o,"agent restart"),n&&await this.runInternalPrompt(n).catch(()=>{}),this.broadcastAgentSwitch(t,t),this.notifyAgentChange("respawnAgent","restart")}async buildSwitchTranscript(e,t){let n=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let l=(c.params??{}).update;if(!l||l._meta?.["hydra-acp"]?.synthetic)continue;let p=l.sessionUpdate;if(p==="prompt_received"){let g=ht(l.prompt);g&&n.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let m=l.content?.text;m&&n.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let g=l.status,m=l.title;(g==="completed"||g==="failed")&&n.push({speaker:"tool",text:`${m??"?"} ${g}`})}}if(n.length===0)return"";let o=[],i;for(let c of n)i&&i.speaker===c.speaker?i.text+=c.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:c.speaker,text:c.text});i&&o.push(`<${i.speaker}>: ${i.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,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 ---",...o,"--- end transcript ---"].join(`
84
+ `)}async seedFromImport(){await this.enqueuePrompt("seed:import",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("seed:fork",async()=>{let t=this.title??"(untitled)",n=[];if(this.historyStore)try{n=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=zs({synopsis:e,title:t,tail:n,tailK:Du,tailFloor:Bu,watermark:this._summarizedThroughEntry,recallArmed:(this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let n=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),n!==void 0&&(r.filePath=n),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...n!==void 0?{filePath:n}:{},fileCapBytes:e.fileCapBytes}})};let o=new yn(r);this.streamBuffer=o,this.streamFilePath=n;let i={capacityBytes:o.capacity};return n!==void 0&&(i.filePath=n),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let n=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");n.append(r)}return t===!0&&n.close(),{writeCursor:n.writeCursorPos}}async streamRead(e,t,n){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??pt,pt)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&n!==void 0&&n>0){let d=await r.waitForData(i.nextCursor,n);(d==="data"||d==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let n=this.requireStreamBuffer().tail(e);return{bytes:n.bytes.toString("base64"),startCursor:n.startCursor,endCursor:n.endCursor,truncated:n.truncated}}streamHead(e){let n=this.requireStreamBuffer().head(e);return{bytes:n.bytes.toString("base64"),startCursor:n.startCursor,endCursor:n.endCursor,truncated:n.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=x.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closeUnsolicitedTurn("closed"),e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let o of n){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear(),this.openToolCalls.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>mi(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>Ai.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,n){this._setAttentionFlag(e,t,n,!0)}_setAttentionFlag(e,t,n,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(n))return;this.attentionFlags.set(o,{...i,payload:n,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:n});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,n){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&n&&(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.hasWorkInFlight){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},n=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${n}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()}get currentPromptDepth(){if(this.currentEntry?.kind==="user")return this.currentEntry.originator.depth??0}get hasWorkInFlight(){return this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0}onIdle(e,t){let n={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(n),()=>{let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1),n.timer&&(clearTimeout(n.timer),n.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let n of this.idleHandlers)n.timer&&(clearTimeout(n.timer),n.timer=void 0);return}let t=[...this.idleHandlers];for(let n of t){if(n.debounceMs===0){if(n.once){let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1)}try{n.fn(this)}catch{}continue}n.timer&&(clearTimeout(n.timer),n.timer=void 0),n.timer=setTimeout(()=>{if(n.timer=void 0,!this.closed&&this.isQuiescedSync()){if(n.once){let r=this.idleHandlers.indexOf(n);r>=0&&this.idleHandlers.splice(r,1)}try{n.fn(this)}catch{}}},n.debounceMs),typeof n.timer.unref=="function"&&n.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}noteRecordedToolCall(e,t){if(e!=="session/update")return;let n=t?.update;if(n===void 0)return;let r=typeof n.toolCallId=="string"?n.toolCallId:"";if(r.length!==0){if(n.sessionUpdate==="tool_call"){this.openToolCalls.add(r);return}n.sessionUpdate==="tool_call_update"&&(n.status==="completed"||n.status==="failed")&&this.openToolCalls.delete(r)}}closeOpenToolCalls(e){if(this.openToolCalls.size===0||this.closed)return;let t=[...this.openToolCalls];this.openToolCalls.clear();for(let n of t)this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",_meta:{[ue]:{synthetic:!0,closedBy:e}}}});this.logger?.info(`session ${this.sessionId} closed ${t.length} open tool call(s) on ${e}`)}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let n=t,r=typeof n.sessionUpdate=="string"?n.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof n.toolCallId=="string"&&n.toolCallId.length>0?n.toolCallId:void 0;if(!o)return;let i=typeof n.kind=="string"?n.kind:void 0;this.toolCallKind.note(o,i);let a=this.toolCallKind.effective(o,i);if(a===Yo&&Array.isArray(n.locations))for(let u of n.locations){if(!u||typeof u!="object")continue;let l=u.path;if(typeof l!="string"||l.length===0||this.filesEditedSeen.has(l))continue;this.filesEditedSeen.add(l);let f=u.line,p={path:l,toolCallId:o};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p),this.reportIsolationBreach(l,o)}if(r!=="tool_call_update")return;let d=typeof n.status=="string"?n.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,d);let c={toolCallId:o,status:d};a&&(c.kind=a),n.content!==void 0&&(c.content=n.content),Array.isArray(n.locations)&&(c.locations=n.locations),this.notifyChain("tool.completed",c)}notifyChain(e,t){let n=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(n)&&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,n){let r=this.rewriteForClient(t),o=!Qs(e,r),i=o?rl(e,r):r,a=Date.now(),d=o?We(i,a):i;if(o){this.noteRecordedToolCall(e,i);let c={method:e,params:i,recordedAt:a};if(this.lastRecordedAt=c.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,c).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(c)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let c of this.clients.values())n&&c.clientId===n||c.connection.notify(e,d).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw me(new Error("no clients attached to handle permission request"),x.PermissionDenied);let n=this.rewriteForClient(e),r=wi(n),o=Pe(),{toolCall:i,options:a}=n??{};return new Promise((d,c)=>{let u=!1,l=[],f=0,p,g=this.sessionId,m=k=>{u||(u=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),k())},h=k=>k?.code===x.MethodNotFound;function y(k){if(u)return;let w=k.connection.request("session/request_permission",n);l.push({client:k}),f++,w.then(S=>{f--,m(()=>{let I=ol({toolCallId:r,result:S,resolver:k});for(let b of l)b.client.clientId!==k.clientId&&b.client.connection.notify("session/update",{sessionId:g,update:I}).catch(()=>{});d(S)})}).catch(S=>{if(f--,h(S)||(p=S),f===0&&!u){let I=p??me(new Error("no client handled permission request"),x.PermissionDenied);m(()=>c(I))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,y);for(let k of t)y(k)})}async enqueuePrompt(e,t){return new Promise((n,r)=>{let o={kind:"internal",messageId:Pe(),label:e,enqueuedAt:Date.now(),cancelled:!1,task:t,resolve:n,reject:r};this.promptQueue.push(o),this.drainQueue()})}async enqueueUserPrompt(e,t,n,r){let o=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r?.fromSession&&(i.fromSession=r.fromSession),r?.fromSessionTitle&&(i.fromSessionTitle=r.fromSessionTitle),r?.fromLabel&&(i.fromLabel=r.fromLabel),r?.depth!==void 0&&(i.depth=r.depth);let a=this.parseQueuePosition(t);return new Promise((d,c)=>{let u={kind:"user",messageId:n,originator:i,clientId:e.clientId,prompt:o,enqueuedAt:Date.now(),cancelled:!1,resolve:d,reject:c},l=this.insertEntryAt(u,a);this.persistRewrite(),this.broadcastQueueAdded(u,{position:l}),this.drainQueue()})}promptCarriesSentBy(e){if(!e||typeof e!="object")return!1;let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t[ue];if(!n||typeof n!="object"||Array.isArray(n))return!1;let r=n.sentBy;return!!r&&typeof r=="object"}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let n=t["hydra-acp"];if(!n||typeof n!="object"||Array.isArray(n))return"tail";let r=n.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let n=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),n;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),n+o+1}return this.promptQueue.push(e),n+this.promptQueue.length-1}persistRewrite(){let e=[];for(let n of this.promptQueue)n.kind!=="user"||n.cancelled||e.push(this.persistedFromEntry(n));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ot(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[0];if(e?.kind==="user"&&(await this.holdForUnsolicitedTurn(e),this.closing))break;let t=this.promptQueue.shift();if(!t)break;if(!t.cancelled){this.currentEntry=t,t.kind==="user"&&this.persistRewrite(),t.kind==="user"&&this.broadcastQueueRemoved(t.messageId,"started");try{let n=await this.runQueueEntry(t);t.resolve(n),await new Promise(r=>setImmediate(r))}catch(n){t.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.supersededAutonomousTurn=void 0,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return this.closeUnsolicitedTurn("superseded",`internal:${e.label}`),e.task();this.broadcastPromptReceived(e);let t=ht(e.prompt).replace(/\s+$/,""),n=!t.includes(`
85
+ `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=n.startsWith("/")?n.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(n==="/model"||n==="/mode"||n==="/sessions"||n==="/help"||n==="/hydra"||o){let d;if(n==="/sessions")d=await this.handleSessionsCommand();else if(n==="/help")d=await this.handleHelpCommand();else if(n==="/mode")d=await this.handleModeCommand(t);else if(n==="/model")d=await this.handleModelCommand(t);else if(o){let c=t.slice(n.length).trim(),u=c?`/hydra ${r} ${c}`:`/hydra ${r}`;d=await this.handleSlashCommand(u,e.messageId)}else d=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,d,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),d}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i=e.prompt;n&&this.agentAdvertisedCommands.length>0&&!this.agentKnowsSlashCommand(n)&&(i=Ks(e.prompt,dl));let a;this.agentTurnInFlight=!0;try{i=this.applyWorkspacePromptRewrite(i),a=await this.awaitPromptResponse(this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:i},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0))}catch(d){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),d}finally{this.agentTurnInFlight=!1}return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function me(s,e){return s.code=e,s}var Gu=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 Qu(s,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||s==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function Ku(s){return typeof s!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(s)?.[1]}function Yu(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.claudeCode;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};return t.toolName!==void 0&&(n.toolName=t.toolName),t.toolResponse&&typeof t.toolResponse=="object"&&(n.toolResponse=t.toolResponse),n}function Qs(s,e){if(s!=="session/update")return!1;let n=(e??{}).update?.sessionUpdate;return typeof n=="string"&&Gu.has(n)}function Xu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function Zu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.id!==e[t]?.id||s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function el(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]?.modelId!==e[t]?.modelId||s[t]?.name!==e[t]?.name||s[t]?.description!==e[t]?.description)return!1;return!0}function yt(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object"||Array.isArray(t))continue;let n=t,r=typeof n.modelId=="string"&&n.modelId.trim()||typeof n.value=="string"&&n.value.trim()||typeof n.id=="string"&&n.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof n.name=="string"&&n.name.length>0&&(o.name=n.name),typeof n.description=="string"&&n.description.length>0&&(o.description=n.description),e.push(o)}return e}function Ht(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object"||Array.isArray(t))continue;let n=t,r=typeof n.value=="string"&&n.value.trim()||typeof n.id=="string"&&n.id.trim()||void 0;if(!r)continue;let o={id:r};typeof n.name=="string"&&n.name.length>0&&(o.name=n.name),typeof n.description=="string"&&n.description.length>0&&(o.description=n.description),e.push(o)}return e}function tl(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let n=t.availableModes;if(!Array.isArray(n))return[];let r=[];for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function nl(s,e){let n=(e??{}).update??{},r=n.sessionUpdate;if(r==="agent_message_chunk"){let o=n.content??{};typeof o.text=="string"&&(s.chunks.push(o.text),s.messageChars+=o.text.length);return}if(r==="agent_thought_chunk"){let o=n.content??{};typeof o.text=="string"&&(s.thinkingChars+=o.text.length);return}if(r==="tool_call"){s.toolCalls++;return}if(r==="usage_update"){typeof n.used=="number"&&(s.lastUsed=n.used),typeof n.size=="number"&&(s.lastSize=n.size);return}}function sl(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let n=t.availableCommands??t.commands;if(!Array.isArray(n))return[];let r=[];for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function rl(s,e){if(s!=="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:Pe()}}}function bn(s,e){for(let t=0;t<s.length;t++){let n=s[t];if(!n||n.method!=="session/update")continue;if(n.params?.update?.messageId===e)return t}return-1}function wi(s){if(!s||typeof s!="object")return;let e=s.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function ol(s){let e=il(s.result),t={sessionUpdate:"permission_resolved"};return s.toolCallId!==void 0&&(t.toolCallId=s.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=al(s.resolver),t}function il(s){if(!s||typeof s!="object")return;let e=s.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let n={kind:t},r=e.optionId;typeof r=="string"&&(n.optionId=r);let o=e.reason;return typeof o=="string"&&(n.reason=o),n}function al(s){let e={clientId:s.clientId};return s.clientInfo?.name&&(e.name=s.clientInfo.name),s.clientInfo?.version&&(e.version=s.clientInfo.version),e}function ht(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}var dl="\u200B";function ki(s,e){return s.map(t=>{if(t&&typeof t=="object"&&typeof t.text=="string"){let n=t;return{...n,text:e(n.text)}}return t})}function Ks(s,e){let t=s.findIndex(o=>o&&typeof o=="object"&&typeof o.text=="string");if(t<0)return s;let n=s[t],r=[...s];return r[t]={...n,text:`${e}${n.text}`},r}function Ys(s){return s==="session/prompt"?{stopReason:"stopped"}:{}}function cl(s){return s==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function bi(s){let e=s.name&&s.name!==s.id?`${s.id} (${s.name}) \u2014 \u25B6 ${s.currentValue}`:`${s.id} \u2014 \u25B6 ${s.currentValue}`;if(s.options.length===0)return e;let t=Math.max(...s.options.map(r=>r.value.length)),n=s.options.map(r=>{let o=r.value===s.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
84
86
  ${n.join(`
85
- `)}`}function Xs(s,e){for(let t of s.split(/\r?\n/)){let n=t.trim();if(n)return n.length>e?`${n.slice(0,e)}\u2026`:n}}K();Oe();import*as vt from"fs/promises";import*as oy from"path";import{customAlphabet as dl}from"nanoid";import{z as E}from"zod";import{z as kt}from"zod";var il=kt.object({source:kt.string(),reason:kt.string(),raisedAt:kt.number(),payload:kt.unknown()}),Si=kt.array(il);import{z as V}from"zod";var Ii=V.object({status:V.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:V.number(),iter:V.number().int().nonnegative().optional(),attempts:V.number().int().nonnegative().optional(),lastError:V.string().optional(),worker:V.object({upstreamSessionId:V.string(),pid:V.number().int().nonnegative()}).optional()}),jt=V.object({goal:V.string().optional(),outcome:V.string().optional(),files_touched:V.array(V.string()).optional(),tools_used:V.array(V.string()).optional(),rejected_approaches:V.array(V.string()).optional(),open_threads:V.array(V.string()).optional(),decisions:V.array(V.string()).optional(),file_edit_intentions:V.array(V.string()).optional(),unresolved_errors:V.array(V.string()).optional(),tool_state:V.array(V.string()).optional()}),Ai=200,Zs=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
87
+ `)}`}function Xs(s,e){for(let t of s.split(/\r?\n/)){let n=t.trim();if(n)return n.length>e?`${n.slice(0,e)}\u2026`:n}}K();Oe();import*as vt from"fs/promises";import*as gy from"path";import{customAlphabet as pl}from"nanoid";import{z as P}from"zod";import{z as kt}from"zod";var ul=kt.object({source:kt.string(),reason:kt.string(),raisedAt:kt.number(),payload:kt.unknown()}),Ci=kt.array(ul);import{z}from"zod";var xi=z.object({status:z.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:z.number(),runId:z.string().optional(),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()}),jt=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()}),Ri=200,Zs=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
86
88
  {
87
89
  "title": "short summary, max 80 chars",
88
90
  "synopsis": {
@@ -92,7 +94,7 @@ ${n.join(`
92
94
  "open_threads": ["work started but not finished"]
93
95
  }
94
96
  }
95
- Use empty arrays/strings where a field doesn't apply.`;function Ci(s){let e=s.trim();if(e.length===0)return;let t=bt(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=bt(e.slice(o,i+1)))}if(t===void 0){let o=Ri(e);o!==void 0&&(t=bt(o))}if(t===void 0||t===null||typeof t!="object")return;let n=t,r={};if(typeof n.title=="string"){let o=n.title.trim();o.length>0&&(r.title=o.slice(0,Ai))}if(n.synopsis!==void 0&&n.synopsis!==null){let o=jt.safeParse(n.synopsis);o.success&&al(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var er=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
97
+ Use empty arrays/strings where a field doesn't apply.`;function Ei(s){let e=s.trim();if(e.length===0)return;let t=bt(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=bt(e.slice(o,i+1)))}if(t===void 0){let o=Mi(e);o!==void 0&&(t=bt(o))}if(t===void 0||t===null||typeof t!="object")return;let n=t,r={};if(typeof n.title=="string"){let o=n.title.trim();o.length>0&&(r.title=o.slice(0,Ri))}if(n.synopsis!==void 0&&n.synopsis!==null){let o=jt.safeParse(n.synopsis);o.success&&ll(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var er=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
96
98
  {
97
99
  "title": "short summary, max 80 chars",
98
100
  "goal": "the user's original ask",
@@ -104,94 +106,94 @@ Use empty arrays/strings where a field doesn't apply.`;function Ci(s){let e=s.tr
104
106
  "unresolved_errors": ["errors left open at session end"],
105
107
  "tool_state": ["runtime state relevant for recall"]
106
108
  }
107
- Use empty arrays/strings where a field doesn't apply.`;function xi(s){let e=s.trim();if(e.length===0)return;let t=bt(e);if(t===void 0){let u=e.indexOf("{"),c=e.lastIndexOf("}");u>=0&&c>u&&(t=bt(e.slice(u,c+1)))}if(t===void 0){let u=Ri(e);u!==void 0&&(t=bt(u))}if(t===void 0||t===null||typeof t!="object")return;let n=t,r={};if(typeof n.title=="string"){let u=n.title.trim();u.length>0&&(r.title=u.slice(0,Ai))}let o={},i=!1,a=["goal","outcome"];for(let u of a)if(typeof n[u]=="string"){let c=n[u].trim();c.length>0&&(o[u]=c,i=!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(n[u])){let c=n[u],l=V.array(V.string()).safeParse(c);l.success&&c.length>0&&(o[u]=l.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function bt(s){try{return JSON.parse(s)}catch{return}}function Ri(s){let e=s.indexOf("{");if(e<0)return;let t=0,n=!1,r=!1;for(let o=e;o<s.length;o++){let i=s[o];if(n){r?r=!1:i==="\\"?r=!0:i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return s.slice(e,o+1)}}function al(s){return s.goal!==void 0&&s.goal.trim().length>0||s.outcome!==void 0&&s.outcome.trim().length>0||s.files_touched!==void 0&&s.files_touched.length>0||s.tools_used!==void 0&&s.tools_used.length>0||s.rejected_approaches!==void 0&&s.rejected_approaches.length>0||s.open_threads!==void 0&&s.open_threads.length>0||s.decisions!==void 0&&s.decisions.length>0||s.file_edit_intentions!==void 0&&s.file_edit_intentions.length>0||s.unresolved_errors!==void 0&&s.unresolved_errors.length>0||s.tool_state!==void 0&&s.tool_state.length>0}var cl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ul=dl(cl,16),ll="hydra_lineage_";function Dt(){return`${ll}${ul()}`}var nr=E.object({name:E.string(),description:E.string().optional()}),sr=E.object({id:E.string(),name:E.string().optional(),description:E.string().optional()}),fl=E.object({modelId:E.string(),name:E.string().optional(),description:E.string().optional()}),rr=E.object({used:E.number().optional(),size:E.number().optional(),costAmount:E.number().optional(),costCurrency:E.string().optional(),cumulativeCost:E.number().optional()}),or=E.object({name:E.string(),version:E.string().optional()}),pl=E.object({path:E.string(),sourceCwd:E.string(),label:E.string(),requestedLabel:E.string().optional(),provider:E.string(),snapshot:E.string().optional(),line:E.string().optional(),vcs:E.record(E.string(),E.string()).optional(),clean:E.boolean().optional()}),gl=E.object({previousUpstreamSessionId:E.string(),previousSummarizedThroughEntry:E.number().int().nonnegative().optional()}),hl=E.object({upstreamSessionId:E.string(),agentId:E.string(),startedAt:E.string().optional(),endedAt:E.string().optional(),cost:E.number().nonnegative().optional(),inferred:E.boolean().optional()}),ml=E.object({version:E.literal(1),sessionId:E.string(),lineageId:E.string().optional(),upstreamSessionId:E.string(),importedFromSessionId:E.string().optional(),importedFromUpstreamSessionId:E.string().optional(),importedFromMachine:E.string().optional(),agentId:E.string(),cwd:E.string(),title:E.string().optional(),synopsis:jt.optional(),compactionState:Ii.optional(),rollbackBreadcrumb:gl.optional(),upstreamGenerations:E.array(hl).optional(),summarizedThroughEntry:E.number().int().nonnegative().optional(),agentArgs:E.array(E.string()).optional(),currentModel:E.string().optional(),currentMode:E.string().optional(),currentUsage:rr.optional(),agentCommands:E.array(nr).optional(),agentModes:E.array(sr).optional(),agentModels:E.array(fl).optional(),pendingHistorySync:E.boolean().optional(),pendingAgentSwap:E.string().optional(),parentSessionId:E.string().optional(),forkedFromSessionId:E.string().optional(),forkedFromMessageId:E.string().optional(),forkSynthesisState:E.enum(["running","failed"]).optional(),originatingClient:or.optional(),interactive:E.boolean().optional(),priority:E.number().int().nonnegative().optional(),forwardedEnv:E.record(E.string(),E.string()).optional(),workspace:pl.optional(),attentionFlags:Si.default([]).optional(),extensionState:E.record(E.string(),E.record(E.string(),E.unknown())).default({}).optional(),createdAt:E.string(),updatedAt:E.string()}),tr=/^[A-Za-z0-9_-]+$/;function yl(s){if(!tr.test(s))throw new Error(`unsafe session id: ${s}`)}var vn=class{async write(e){yl(e.sessionId);let t={version:1,...e};await fe(A.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!tr.test(e))return;let t=await ee(A.sessionFile(e));if(t!==void 0)try{return ml.parse(t)}catch{return}}async delete(e){if(tr.test(e)){try{await vt.unlink(A.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await vt.rmdir(A.sessionDir(e))}catch(t){let n=t;if(n.code!=="ENOENT"&&n.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let n of t)if(n.lineageId===e)return n}async list(){let e;try{e=await vt.readdir(A.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),n=[];for(let r of t)r&&n.push(r);return n}};function ir(s){let e=new Date().toISOString(),t=s.createdAt??e,n=s.upstreamGenerations??(s.upstreamSessionId?[{upstreamSessionId:s.upstreamSessionId,agentId:s.agentId,startedAt:t}]:[]);return{sessionId:s.sessionId,lineageId:s.lineageId,upstreamSessionId:s.upstreamSessionId,importedFromSessionId:s.importedFromSessionId,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,importedFromMachine:s.importedFromMachine,agentId:s.agentId,cwd:s.cwd,title:s.title,synopsis:s.synopsis,summarizedThroughEntry:s.summarizedThroughEntry,compactionState:s.compactionState,rollbackBreadcrumb:s.rollbackBreadcrumb,upstreamGenerations:n,agentArgs:s.agentArgs,currentModel:s.currentModel,currentMode:s.currentMode,currentUsage:s.currentUsage,agentCommands:s.agentCommands,agentModes:s.agentModes,agentModels:s.agentModels,pendingHistorySync:s.pendingHistorySync,pendingAgentSwap:s.pendingAgentSwap,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:s.interactive,priority:s.priority,forwardedEnv:s.forwardedEnv,workspace:s.workspace,attentionFlags:s.attentionFlags??[],extensionState:s.extensionState??{},createdAt:t,updatedAt:s.updatedAt??e}}Oe();K();import*as re from"fs/promises";import*as oe from"path";K();import*as Sn from"path";import{createHash as wl}from"crypto";var ve=class extends Error{constructor(e,t){super(`provider "${e}" does not support ${t}; check capabilities().supports before calling`),this.name="WorkspaceUnsupportedError"}};function St(s){let e=wl("sha256").update(Sn.resolve(s)).digest("hex").slice(0,12);return Sn.join(B(),"workspaces",e)}async function In(s,e,t=100){if(await e(s))return s;for(let n=2;n<=t;n+=1){let r=`${s}-${n}`;if(await e(r))return r}}function Ge(s,e=10){if(s.length<=e)return[...s];let t=s.slice(0,e),n=s.length-e;return[...t,`... and ${n} more`]}function ar(s){return s.changedPaths.length>0||s.recorded!==void 0&&s.recorded!==s.actual}function kl(s){let e=[];for(let t of s){if(t.changedPaths.length===0){e.push(`${t.relPath} (nested tree advanced to ${t.actual.slice(0,8)})`);continue}for(let n of t.changedPaths)e.push(`${t.relPath}/${n}`)}return e}function dr(s,e){let t=new Set(e.map(r=>r.relPath));return[...s.filter(r=>!t.has(r.replace(/\/$/,""))),...kl(e.filter(ar))]}function An(s){let e=s.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e.slice(0,64):"workspace"}var cr="copy",Pi=new Set([".git"]);function Lt(s){return`${s}.manifest.json`}async function Ei(s){let e=new Map,t=[s];for(;t.length>0;){let n=t.pop();if(n===void 0)break;let r;try{r=await re.readdir(n,{withFileTypes:!0})}catch{continue}for(let o of r){let i=oe.join(n,o.name);if(!(n===s&&Pi.has(o.name))){if(o.isDirectory()){t.push(i);continue}if(o.isFile())try{let a=await re.stat(i);e.set(oe.relative(s,i),{size:a.size,mtimeMs:a.mtimeMs})}catch{continue}}}}return e}var Cn=class{kind=cr;capabilities(){return{cheapWorkspaces:!1,sharedHistory:!1,nonMutatingCapture:!0,conflictReporting:!1,locking:!1,requiresServer:!1,supports:{record:!1,integrate:!1,captureWorkingState:!1,changedPaths:!1,environmentNotes:!0,rematerialize:!1,nestedTrees:!1}}}async materializeNested(){return{ok:!0,count:0}}async retainSnapshot(){}async dropSnapshotRef(){}async rematerialize(e){return{ok:!1,reason:`copy provider retains nothing outside ${e.path}; it cannot be rebuilt`}}async createWorkspace(e){if(e.from!==void 0)return{ok:!1,reason:"copy provider cannot create from a snapshot; it records none"};let t=oe.resolve(e.sourceCwd),n=e.contentFrom!==void 0?oe.resolve(e.contentFrom):t;try{if(!(await re.stat(n)).isDirectory())return{ok:!1,reason:`${n} is not a directory`}}catch{return{ok:!1,reason:`${n} does not exist`}}let r=St(t);try{await re.mkdir(r,{recursive:!0})}catch(u){return{ok:!1,reason:`could not create workspace root: ${String(u)}`}}let o=await In(An(e.label),async u=>re.access(oe.join(r,u)).then(()=>!1).catch(()=>!0));if(o===void 0)return{ok:!1,reason:`no free name available for "${e.label}"`};let i=oe.join(r,o);try{await re.cp(n,i,{recursive:!0,errorOnExist:!1,force:!0,filter:u=>{let c=oe.relative(n,u);if(c.length===0)return!0;let l=c.split(oe.sep)[0];return l===void 0||!Pi.has(l)}})}catch(u){return await re.rm(i,{recursive:!0,force:!0}).catch(()=>{}),{ok:!1,reason:`copy failed: ${String(u)}`}}let a=await Ei(i),d={sourceCwd:t,label:o,createdAt:new Date().toISOString(),entries:Object.fromEntries(a)};return await fe(Lt(i),d,{pretty:!1}),{ok:!0,workspace:{path:i,sourceCwd:t,label:o,provider:this.kind}}}async removeWorkspace(e,t){if(!t.force){let n=await this.status(e);if(!n.clean)throw new Error(`workspace ${e.path} has ${n.changedPaths.length} changed path(s); pass force to remove`)}await re.rm(e.path,{recursive:!0,force:!0}),await re.rm(Lt(e.path),{force:!0})}async listWorkspaces(e){let t=St(oe.resolve(e)),n;try{n=await re.readdir(t)}catch{return[]}let r=[];for(let o of n){if(o.endsWith(".manifest.json"))continue;let i=oe.join(t,o),a=await ee(Lt(i));a!==void 0&&r.push({path:i,sourceCwd:a.sourceCwd,label:a.label,provider:this.kind})}return r}async status(e){let t=await ee(Lt(e.path)),n=await Ei(e.path);if(t===void 0)return{clean:!1,changedPaths:[...n.keys()].sort(),hasRecordedWork:!1};let r=[];for(let[o,i]of n){let a=t.entries[o];(a===void 0||a.size!==i.size||a.mtimeMs!==i.mtimeMs)&&r.push(o)}for(let o of Object.keys(t.entries))n.has(o)||r.push(o);return r.sort(),{clean:r.length===0,changedPaths:r,hasRecordedWork:!1}}async statusReport(e){let{changedPaths:t}=await this.status(e),n=t.length===0?["no changes since this copy was made"]:[`${t.length} changed file(s) since this copy was made:`,...Ge(t.map(r=>` ${r}`))];return n.push(`Not tracking ${P(e.sourceCwd)}: a copied directory has no shared history, so there is nothing to be in or out of sync with.`),n}async environmentNotes(e){return[`This directory is an isolated copy of ${e.sourceCwd}. It is not under version control: there is no history, no branches, and version-control commands will not behave as they would in the original.`,"Changes here are not automatically returned to the original directory."]}async captureWorkingState(){throw new ve(this.kind,"captureWorkingState")}async record(){throw new ve(this.kind,"record")}async attributeOrphan(e){let t=await ee(Lt(e));if(t?.sourceCwd!==void 0)return{path:e,sourceCwd:t.sourceCwd,label:t.label??oe.basename(e),provider:this.kind}}async discardLine(){return{ok:!0,dropped:0}}ownsLine(){return!1}async pruneStale(){}async changedPaths(){throw new ve(this.kind,"changedPaths")}async integrate(){return{ok:!1,conflicts:[],declined:!0,reason:`the "${this.kind}" provider keeps no history, so there is nothing to integrate from`}}async currentState(){}async contentId(){}async currentLineName(){}async resolveRoot(e){return e}async resolveRetained(){}async contains(){return!1}async divergence(){}async changedPathsBetween(){return[]}async captureDelta(){throw new ve(this.kind,"captureDelta")}async applyDelta(){return{ok:!1,reason:`the "${this.kind}" provider cannot reproduce a captured change`}}async resetTo(){return{ok:!1,reason:`the "${this.kind}" provider records no state to return to`}}async integrationInProgress(){return!1}async abortIntegration(){}async conflictedPaths(){return[]}async listNested(){return[]}async captureNested(){return[]}async reproduceNested(){return{applied:[],failed:[]}}async integrateNested(){return{applied:[],failed:[]}}async lock(){throw new ve(this.kind,"lock")}async unlock(){throw new ve(this.kind,"unlock")}};K();import{execFile as Fi}from"child_process";import{randomBytes as Il}from"crypto";import*as Se from"fs/promises";import*as Ni from"os";import*as Q from"path";function bl(s){let e=s.indexOf(" ");return e===-1?{key:s,value:""}:{key:s.slice(0,e),value:s.slice(e+1)}}function Mi(s){let e=[],t,n=()=>{t!==void 0&&(e.push(t),t=void 0)};for(let r of s.split(`
108
- `)){let o=r.replace(/\r$/,"");if(o.length===0){n();continue}let{key:i,value:a}=bl(o);if(i==="worktree"){n(),t={path:a,bare:!1,detached:!1};continue}if(t!==void 0)switch(i){case"HEAD":t.head=a;break;case"branch":t.branch=a;break;case"bare":t.bare=!0;break;case"detached":t.detached=!0;break;case"locked":t.lockedReason=a;break;case"prunable":t.prunableReason=a;break;default:break}}return n(),e}function Ti(s){if(s===void 0)return;let e="refs/heads/";return s.startsWith(e)?s.slice(e.length):s}var En="git",_i="hydra-acp:",ur="hydra",U=5e3,te=12e4,xn=9e5;function $i(s){return Se.access(s).then(()=>!0).catch(()=>!1)}function Al(s){return Se.realpath(s).catch(()=>s)}function N(s,e,t,n){return new Promise(r=>{Fi("git",s,{cwd:e,timeout:t,maxBuffer:8*1024*1024,...n?{env:{...process.env,...n}}:{}},(o,i,a)=>{r({ok:!o,stdout:i??"",stderr:a??""})})})}function lr(s,e,t,n=te){return new Promise(r=>{let o=Fi("git",s,{cwd:e,timeout:n,maxBuffer:67108864},(i,a,d)=>{r({ok:!i,stdout:a??"",stderr:d??""})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}function fr(s){let e=[];for(let t of s.split(`
109
- `)){let n=t.replace(/\r$/,"");if(n.length<4)continue;let r=n.slice(3),o=r.indexOf(" -> ");e.push({code:n.slice(0,2),path:o===-1?r:r.slice(o+4)})}return e}var Rn=class{kind=En;refRoot(e){return e.vcs?.repoRoot??e.sourceCwd}ownsLine(e){return e.startsWith(`${ur}/`)}capabilities(){return{cheapWorkspaces:!0,sharedHistory:!0,nonMutatingCapture:!0,conflictReporting:!0,locking:!0,requiresServer:!1,supports:{record:!0,integrate:!0,captureWorkingState:!0,changedPaths:!1,environmentNotes:!0,rematerialize:!0,nestedTrees:!0}}}async materializeNested(e,t){if(!await $i(Q.join(e.path,".gitmodules")))return{ok:!0,count:0};let r=await N(["submodule","update","--init","--recursive",...t?.discardLocal===!0?["--force"]:[]],e.path,xn);if(!r.ok)return{ok:!1,count:0,reason:r.stderr.trim()||"git submodule update --init failed"};if(t?.discardLocal===!0){let a=await N(["submodule","foreach","--recursive","git","reset","--hard"],e.path,xn);if(!a.ok)return{ok:!1,count:0,reason:a.stderr.trim()||"could not reset submodules"};let d=t.purgeIgnored===!0?"-ffdx":"-fd",u=await N(["submodule","foreach","--recursive","git","clean",d],e.path,xn);if(!u.ok)return{ok:!1,count:0,reason:u.stderr.trim()||"could not clean submodules"}}let o=await N(["submodule","status","--recursive"],e.path,U);return{ok:!0,count:o.ok?o.stdout.split(`
110
- `).filter(a=>a.trim().length>0).length:0}}async rematerialize(e){let t=e.vcs?.branch;if(t===void 0)return{ok:!1,reason:"workspace has no recorded branch to restore from"};let n=this.refRoot(e);if(!await $i(n))return{ok:!1,reason:`source repository ${n} no longer exists`};let r=await N(["rev-parse","--verify","--quiet",`refs/heads/${t}`],n,U);if(!r.ok||r.stdout.trim().length===0)return{ok:!1,reason:`branch ${t} no longer exists in ${n}`};await N(["worktree","unlock",e.path],n,U),await N(["worktree","prune"],n,U);let o=await N(["worktree","add",e.path,t],n,te);return o.ok?{ok:!0,workspace:{...e,line:t,vcs:{...e.vcs??{},kind:"git",branch:t,repoRoot:n}}}:{ok:!1,reason:`could not restore worktree: ${o.stderr.trim()||"unknown error"}`}}async createWorkspace(e){let t=Q.resolve(e.sourceCwd),n=await N(["rev-parse","--show-toplevel"],t,U);if(!n.ok)return{ok:!1,reason:`${t} is not a git repository (or git is unavailable)`};let r=n.stdout.trim();if(r.length===0)return{ok:!1,reason:`could not resolve the repository root for ${t}`};let o=await N(["rev-parse","HEAD"],r,U);if(!o.ok)return{ok:!1,reason:`${r} has no commits yet, so there is nothing to branch from`};let i=e.from??o.stdout.trim(),a=An(e.label),d=St(t);try{await Se.mkdir(d,{recursive:!0})}catch(f){return{ok:!1,reason:`could not create workspace root: ${String(f)}`}}let u=await In(a,async f=>await Se.access(Q.join(d,f)).then(()=>!0).catch(()=>!1)?!1:!(await N(["rev-parse","--verify","--quiet",`refs/heads/${ur}/${f}`],r,U)).ok);if(u===void 0)return{ok:!1,reason:`no free name available for "${a}"`};let c=Q.join(d,u),l=`${ur}/${u}`,p=await N(["worktree","add","--no-track","-b",l,c,i],r,te);return p.ok?{ok:!0,workspace:{path:c,sourceCwd:t,label:u,provider:this.kind,snapshot:i,line:l,vcs:{kind:"git",branch:l,base:i,repoRoot:r}}}:{ok:!1,reason:`git worktree add failed: ${p.stderr.trim()||"unknown error"}`}}async removeWorkspace(e,t){if(!t.force){let o=await this.status(e);if(!o.clean)throw new Error(`workspace ${e.path} has ${o.changedPaths.length} changed path(s)${o.hasRecordedWork?" and unintegrated recorded work":""}; pass force to remove`)}let n=this.refRoot(e);await this.unlock(e).catch(()=>{});let r=await N(["worktree","remove","--force",e.path],n,te);t.discardLine===!0&&e.vcs?.branch!==void 0&&await N(["branch","-D",e.vcs.branch],n,U),r.ok||(await Se.rm(e.path,{recursive:!0,force:!0}),await N(["worktree","prune"],n,U))}async listWorkspaces(e){let t=Q.resolve(e),n=await N(["rev-parse","--show-toplevel"],t,U);if(!n.ok)return[];let r=n.stdout.trim(),o=await N(["worktree","list","--porcelain"],r,U);if(!o.ok)return[];let i=St(t),a=await Al(i),d=[];for(let u of Mi(o.stdout)){let c=Q.dirname(u.path);if(c!==i&&c!==a)continue;let l=Q.join(i,Q.basename(u.path)),p={kind:"git",repoRoot:r},f=Ti(u.branch);f!==void 0&&(p.branch=f),u.head!==void 0&&(p.head=u.head),u.lockedReason!==void 0&&(p.locked=u.lockedReason);let h=u.lockedReason?.startsWith(_i)===!0;d.push({path:l,sourceCwd:t,label:Q.basename(l),...h?{heldByUs:!0}:{},provider:this.kind,...f!==void 0?{line:f}:{},vcs:p})}return d}async status(e){let t=await N(["status","--porcelain","--untracked-files=all"],e.path,U);if(!t.ok)return{clean:!1,changedPaths:[],hasRecordedWork:!1};let n=fr(t.stdout),r=n.map(a=>a.path),o=n.some(({code:a})=>a!=="??"&&a[0]!==" "&&a[0]!=="?"),i=!1;if(e.snapshot!==void 0){let a=await N(["rev-list","--count",`${e.snapshot}..HEAD`],e.path,U);a.ok&&(i=Number.parseInt(a.stdout.trim(),10)>0)}return{clean:r.length===0&&!i,changedPaths:r,hasRecordedWork:i,hasStagedWork:o}}async lock(e,t){let n=this.refRoot(e);await N(["worktree","lock","--reason",`${_i}${t}`,e.path],n,U)}async unlock(e){let t=this.refRoot(e);await N(["worktree","unlock",e.path],t,U)}async environmentNotes(e){let t=[],n=e.vcs?.branch;return t.push(`This directory is a git worktree of ${e.sourceCwd}${n!==void 0?`, on branch ${n}`:""}. Do not read or write ${e.sourceCwd} directly; paths under it refer to the corresponding file here. Prefer repo-relative paths, which are identical in both.`),t.push("`.git` here is a file, not a directory. That is normal for a worktree and does not need repairing."),await Se.access(Q.join(e.path,".gitmodules")).then(()=>!0).catch(()=>!1)&&t.push("Submodules here are initialized and checked out at the commits this tree records, which means each sits on a detached HEAD. That is normal and does not need repairing. Never re-add a submodule's contents as ordinary tracked files in the superproject: that silently corrupts the integration back to the source branch."),t}async statusReport(e){let t=[],n=await N(["status","--porcelain","--untracked-files=all"],e.path,U);if(n.ok){let r=fr(n.stdout);if(r.length===0)t.push("no uncommitted changes");else{let o=0,i=0,a=0;for(let{code:u}of r){if(u==="??"){a+=1;continue}u[0]!==" "&&u[0]!=="?"&&(o+=1),u[1]!==" "&&u[1]!=="?"&&(i+=1)}let d=[];o>0&&d.push(`${o} staged`),i>0&&d.push(`${i} unstaged`),a>0&&d.push(`${a} untracked`),t.push(`${d.join(", ")}:`),t.push(...Ge(r.map(u=>` ${u.code} ${u.path}`)))}}return t.push(...await this.syncLines(e)),t}async syncLines(e){if(e.vcs?.branch===void 0)return[];let[t,n]=await Promise.all([N(["rev-parse","HEAD"],e.sourceCwd,U),N(["rev-parse","HEAD"],e.path,U)]),r=t.stdout.trim(),o=n.stdout.trim();if(!t.ok||!n.ok||r.length===0||o.length===0)return[];let i=P(e.sourceCwd);if(r===o)return[`in sync with ${i}`];let a=await N(["rev-list","--left-right","--count",`${r}...${o}`],e.path,U),d=a.stdout.trim().split(/\s+/).map(p=>Number.parseInt(p,10)),u=d[0],c=d[1];if(!a.ok||u===void 0||c===void 0||!Number.isFinite(u)||!Number.isFinite(c))return[];let l=[];return u>0&&l.push(`${u} commit(s) behind ${i}. \`/hydra workspace sync\` brings them in; landing is fast-forward-only, so this also unblocks \`stop\`.`),c>0&&l.push(`${c} commit(s) recorded here and not landed yet.`),l}async captureWorkingState(e,t){let n=Q.join(Ni.tmpdir(),`hydra-index-${process.pid}-${Il(6).toString("hex")}`),r={GIT_INDEX_FILE:n};try{let o=await N(["rev-parse","--verify","HEAD"],e,U),i=o.ok&&o.stdout.trim().length>0;if(i){let l=await N(["read-tree","HEAD"],e,te,r);if(!l.ok)throw new Error(`could not seed the snapshot index: ${l.stderr.trim()}`)}let a=await N(["add","-A"],e,te,r);if(!a.ok)throw new Error(`could not stage working state: ${a.stderr.trim()}`);let d=await N(["write-tree"],e,te,r);if(!d.ok||d.stdout.trim().length===0)throw new Error(`could not write tree: ${d.stderr.trim()}`);let u=["commit-tree",d.stdout.trim(),"-m",t];i&&u.push("-p",o.stdout.trim());let c=await N(u,e,te,r);if(!c.ok||c.stdout.trim().length===0)throw new Error(`could not create snapshot commit: ${c.stderr.trim()}`);return c.stdout.trim()}finally{await Se.rm(n,{force:!0}).catch(()=>{})}}async retainSnapshot(e,t,n){let r=this.refRoot(e);await N(["update-ref","--create-reflog",t,n],r,U)}async dropSnapshotRef(e,t){let n=this.refRoot(e);await N(["update-ref","-d",t],n,U)}async currentState(e){let t=await N(["rev-parse","HEAD"],e,U),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async contentId(e,t){let n=await N(["rev-parse",`${t}^{tree}`],e,U),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async currentLineName(e){let t=await N(["rev-parse","--abbrev-ref","HEAD"],e,U),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async resolveRoot(e){let t=await N(["rev-parse","--show-toplevel"],e,U),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async resolveRetained(e,t){let n=await N(["rev-parse","--verify","--quiet",`${t}^{commit}`],this.refRoot(e),U),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async contains(e,t){return(await N(["merge-base","--is-ancestor",t.state,t.within],e,U)).ok}async divergence(e,t,n){let r=await N(["rev-list","--left-right","--count",`${t}...${n}`],e,U);if(!r.ok)return;let o=r.stdout.trim().split(/\s+/).map(d=>Number.parseInt(d,10)),i=o[0],a=o[1];if(!(i===void 0||a===void 0||!Number.isFinite(i)||!Number.isFinite(a)))return{ahead:i,behind:a}}async changedPathsBetween(e,t,n){let r=await N(["diff","--name-only",t,n],e,U);return r.ok?r.stdout.split(`
111
- `).map(o=>o.replace(/\r$/,"").trim()).filter(o=>o.length>0):[]}async captureDelta(e,t,n){let r=await N(["diff","--binary","--ignore-submodules=all",t,n],e,te);if(r.ok)return r.stdout}async applyDelta(e,t,n){if(t.trim().length===0)return{ok:!0,alreadyPresent:!0};let r=n?.stage===!0?["--index"]:[],o=await lr(["apply",...r],e,t);if(o.ok)return{ok:!0};if(n?.tolerant!==!0)return{ok:!1,reason:o.stderr.trim()||"the change did not apply"};if((await lr(["apply","--reverse","--check"],e,t)).ok)return{ok:!0,alreadyPresent:!0};let a=await lr(["apply","--3way"],e,t);return a.ok?{ok:!0}:{ok:!1,reason:a.stderr.trim()||"the change overlaps what is already there"}}async resetTo(e,t,n){let r=await N(["reset","--hard",t],e,te);if(!r.ok)return{ok:!1,reason:r.stderr.trim()||"could not return to that state"};let o=await N(["clean",n?.purgeIgnored===!0?"-ffdx":"-fd"],e,te);if(!o.ok)return{ok:!1,reason:o.stderr.trim()||"returned to that state but could not remove extra files"};let i=await this.materializeNested({path:e,sourceCwd:e,label:"",provider:this.kind},{discardLocal:!0,...n?.purgeIgnored===!0?{purgeIgnored:!0}:{}});return i.ok?{ok:!0}:{ok:!1,reason:i.reason??"could not reset nested trees"}}async integrationInProgress(e){return(await N(["rev-parse","-q","--verify","MERGE_HEAD"],e,U)).ok}async abortIntegration(e){await N(["merge","--abort"],e,te)}async conflictedPaths(e){let t=await N(["diff","--name-only","--diff-filter=U"],e,U);return t.ok?t.stdout.split(`
112
- `).map(n=>n.replace(/\r$/,"").trim()).filter(n=>n.length>0):[]}async record(e,t){let n=await N(["add","-A"],e.path,te);if(!n.ok)throw new Error(`could not stage ${e.path}: ${n.stderr.trim()||"unknown error"}`);let r=await this.status(e),o=await this.currentState(e.path);if(r.changedPaths.length===0){if(o===void 0)throw new Error(`could not read the state of ${e.path}`);return o}let i=await N(["commit","-m",t],e.path,te);if(!i.ok)throw new Error(`could not record ${e.path}: ${i.stderr.trim()||i.stdout.trim()||"unknown error"}`);let a=await this.currentState(e.path);if(a===void 0)throw new Error(`recorded ${e.path} but could not read the resulting state`);return a}async attributeOrphan(e){let t=await N(["rev-parse","--path-format=absolute","--git-common-dir"],e,U),n=t.stdout.trim();if(!t.ok||n.length===0)return;let r=Q.dirname(n),o=await this.currentLineName(e);return{path:e,sourceCwd:r,label:Q.basename(e),provider:this.kind,...o!==void 0?{line:o}:{},vcs:{repoRoot:r,...o!==void 0?{branch:o}:{}}}}async discardLine(e,t){let n=this.refRoot(e),o=(await this.divergence(n,"HEAD",t))?.behind??0,i=await N(["branch","-D",t],n,U);return i.ok?{ok:!0,dropped:o}:{ok:!1,dropped:o,reason:i.stderr.trim()||"could not discard the line"}}async pruneStale(e){await N(["worktree","prune"],this.refRoot(e),U)}async changedPaths(){throw new ve(this.kind,"changedPaths")}async integrate(e){let{into:t,from:n}=e,r=await this.currentState(t);if(r===void 0)return{ok:!1,conflicts:[],declined:!0,reason:`cannot read the state of ${t}`};if(await this.contains(t,{state:n,within:r}))return{ok:!0,snapshot:r,alreadyUpToDate:!0};if(e.fastForwardOnly===!0&&!await this.contains(t,{state:r,within:n}))return{ok:!1,conflicts:[],declined:!0,reason:`${t} cannot simply advance to that state; it has moved on independently`};let o=e.fastForwardOnly===!0?["merge","--ff-only",n]:["merge","--no-edit","-m",e.message??"hydra: integrate",n],i=await N(o,t,te);if(i.ok){let u=await this.currentState(t);return u===void 0?{ok:!1,conflicts:[],reason:"integrated but could not read the resulting state"}:{ok:!0,snapshot:u}}let a=await this.conflictedPaths(t),d=await this.integrationInProgress(t);return a.length===0&&!d?{ok:!1,conflicts:[],declined:!0,reason:i.stderr.trim()||"the integration was refused"}:(e.onConflict==="abort"&&await this.abortIntegration(t),{ok:!1,conflicts:a})}async listNested(e){let t=await N(["submodule","status","--recursive"],e,te);if(!t.ok)return[];let n=[];for(let r of t.stdout.split(`
113
- `)){let o=r.replace(/\r$/,"");if(o.trim().length===0||(o[0]??" ")==="-")continue;let a=o.slice(1),d=a.indexOf(" ");if(d<=0)continue;let u=a.slice(d+1).replace(/\s+\(.*\)\s*$/,"").trim();if(u.length===0||!Cl(e,u))continue;let c=Q.join(e,u),[l,p,f]=await Promise.all([this.currentState(c),N(["rev-parse",`HEAD:${u}`],e,U),N(["status","--porcelain","--untracked-files=all"],c,U)]);if(l===void 0)continue;let h=p.ok?p.stdout.trim():"";n.push({relPath:u,actual:l,...h.length>0?{recorded:h}:{},changedPaths:f.ok?fr(f.stdout).map(g=>g.path):[]})}return n}async captureNested(e,t){let n=[];for(let r of t){if(!ar(r))continue;if(r.changedPaths.length===0){n.push(r);continue}let o=Q.join(e,r.relPath),i=await this.captureWorkingState(o,"hydra: nested work carried into workspace").catch(()=>{});if(i===void 0){n.push(r);continue}let a=await this.captureDelta(o,r.actual,i);n.push(a===void 0?r:{...r,delta:a})}return n}async reproduceNested(e,t,n){let r=[],o=[];for(let i of n){let a=Q.join(e,i.relPath),d=Q.join(t,i.relPath),u=await this.alignNested(a,d,i.actual);if(u!==void 0){o.push({path:i.relPath,reason:u});continue}if(i.delta!==void 0){let c=await this.applyDelta(a,i.delta);if(!c.ok){o.push({path:i.relPath,reason:c.reason??"changes did not apply"});continue}}r.push(i.relPath)}return{applied:r,failed:o}}async integrateNested(e,t,n){let r=[],o=[],i=new Map(n.map(u=>[u.relPath,u])),a=await this.listNested(e),d=new Set([...a.map(u=>u.relPath),...i.keys()]);for(let u of[...d].sort()){let c=a.find(m=>m.relPath===u),l=i.get(u);if(c===void 0){o.push({path:u,reason:"not populated in the receiving tree"});continue}let p=c.recorded!==void 0&&c.recorded!==c.actual,f=l?.delta!==void 0;if(!p&&!f)continue;if(c.changedPaths.length>0){o.push({path:u,reason:`it has ${c.changedPaths.length} uncommitted change(s) of its own, and nothing can tell those apart from what was integrated`});continue}let h=Q.join(e,u),g=Q.join(t,u);if(p&&c.recorded!==void 0){let m=await this.alignNested(h,g,c.recorded);if(m!==void 0){o.push({path:u,reason:m});continue}}if(l?.delta!==void 0){let m=await this.applyDelta(h,l.delta);if(!m.ok){o.push({path:u,reason:m.reason??"the uncommitted changes there did not apply"});continue}}r.push(u)}return{applied:r,failed:o}}async alignNested(e,t,n){let r=await this.currentState(e);if(r===void 0)return"not populated here";if(r===n)return;if(!(await N(["cat-file","-e",`${n}^{commit}`],e,U)).ok&&!(await N(["fetch","--no-tags",t,n],e,xn)).ok)return`could not transfer ${n.slice(0,8)} from the other copy`;if(!(await N(["checkout","--detach",n],e,te)).ok)return`could not move to ${n.slice(0,8)}`}};function Cl(s,e){if(Q.isAbsolute(e))return!1;let t=Q.resolve(s),n=Q.resolve(t,e);return n!==t&&n.startsWith(t+Q.sep)}var xl=En,Rl=new Map([[En,new Rn],[cr,new Cn]]);function Y(s){return Rl.get(s??xl)}var Pn="refs/hydra";function Bt(s){let e=`${Pn}/workspaces/${s}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function pr(s){return`${Pn}/landing/${s}`}function Oi(s){return`${Pn}/sync/${s}`}function Hi(s,e){return`${Pn}/retired/${s}-${e.slice(0,12)}`}function ji(s){let e=Bt(s);return[e.autosave,e.start,e.baseline]}async function gr(s){let{source:e,ws:t,startSnapshotRef:n,baselineRef:r,retainRef:o,provider:i}=s;if(i===void 0)throw new Error("no provider available to inspect the source tree");let a=await i.status({...t,path:e}).catch(()=>{}),d="";for(let l of[r,n]){if(l===void 0)continue;let p=await i.resolveRetained(t,l).catch(()=>{});if(p!==void 0){d=p;break}}let u=a===void 0||a.changedPaths.length>0;if(d.length===0){if(u)throw new Error(`${e} has uncommitted changes but this workspace has no start anchor, so its copy of your work cannot be told apart from edits you made since. Refusing rather than reporting a conflict that is not yours. Commit or stash the source, then retry.`);d=await i.currentState(e).catch(()=>{})??""}if(!u)return{clean:!0,base:d};if(i.capabilities().supports.captureWorkingState!==!0)throw new Error(`${e} has uncommitted changes and this provider cannot snapshot them, so they cannot be preserved across the landing. Commit or stash them first.`);let c=await i.captureWorkingState(e,"hydra: source state before landing").catch(()=>{});if(c===void 0)throw new Error(`could not snapshot the uncommitted changes in ${e}, so refusing to touch them`);return await i.retainSnapshot({...t,path:e},o,c),{clean:!1,snapshot:c,base:d,retainedRef:o}}async function Ke(s){let{source:e,capture:t,provider:n}=s;if(t.clean||t.snapshot===void 0||n===void 0)return!0;let r=await n.captureDelta(e,t.base,t.snapshot).catch(()=>{});return r===void 0?!1:(await n.applyDelta(e,r,{tolerant:!0})).ok}async function Ut(s){s.capture.retainedRef===void 0||s.provider===void 0||await s.provider.dropSnapshotRef({...s.ws,path:s.source},s.capture.retainedRef).catch(()=>{})}Oe();import{execFile as El}from"child_process";import*as Te from"fs/promises";import*as he from"path";var Pl=".hydra/worktree.json",Ml=".worktreeinclude",Tl=120;async function Mn(s){let e=await ee(he.join(s,Pl))??{},t=new Set(Array.isArray(e.carry)?e.carry:[]),n=await Te.readFile(he.join(s,Ml),"utf8").catch(()=>{});if(n!==void 0)for(let o of n.split(`
114
- `)){let i=o.trim();i.length===0||i.startsWith("#")||i.startsWith("!")||i.includes("*")||i.includes("?")||t.add(i)}let r={};return t.size>0&&(r.carry=[...t]),typeof e.postCreate=="string"&&(r.postCreate=e.postCreate),typeof e.preRemove=="string"&&(r.preRemove=e.preRemove),typeof e.hookTimeoutSeconds=="number"&&(r.hookTimeoutSeconds=e.hookTimeoutSeconds),r}async function hr(s,e,t){let n=[],r=[],o=he.resolve(s),i=he.resolve(e);for(let a of t){let d=he.resolve(o,a),u=he.resolve(i,a);if(!d.startsWith(o+he.sep)||!u.startsWith(i+he.sep)){r.push(a);continue}if(await Te.access(u).then(()=>!0).catch(()=>!1)){r.push(a);continue}let l=await Te.stat(d).catch(()=>{});if(l===void 0){r.push(a);continue}try{await Te.mkdir(he.dirname(u),{recursive:!0}),await Te.cp(d,u,{recursive:l.isDirectory()}),n.push(a)}catch{r.push(a)}}return{copied:n,skipped:r}}async function Tn(s,e){let t=JSON.stringify({path:e.workspacePath,sourceCwd:e.sourceCwd,label:e.label,...e.sessionId!==void 0?{sessionId:e.sessionId}:{}}),n=(e.timeoutSeconds??Tl)*1e3;return new Promise(r=>{let o=El("/bin/sh",["-c",s],{cwd:e.workspacePath,timeout:n,maxBuffer:8388608,env:{...process.env,HYDRA_WORKSPACE_PATH:e.workspacePath,HYDRA_SOURCE_CWD:e.sourceCwd,HYDRA_WORKSPACE_LABEL:e.label,...e.sessionId!==void 0?{HYDRA_SESSION_ID:e.sessionId}:{}}},(i,a,d)=>{if(i){let u=(d||i.message||"").trim().slice(0,500);r({ok:!1,reason:u.length>0?u:"hook failed"});return}r({ok:!0})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}K();Oe();import*as je from"fs/promises";import{z as _e}from"zod";var _l=_e.object({version:_e.literal(1),agentId:_e.string(),upstreamSessionId:_e.string(),deletedAt:_e.string(),upstreamUpdatedAt:_e.string().optional(),cwd:_e.string().optional(),title:_e.string().optional(),reason:_e.enum(["user","expired"]).optional(),interactive:_e.boolean().optional()}),_n=class{async add(e){let t={version:1,...e};await fe(A.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await je.access(A.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let n=A.tombstoneFile(e,t),r=await ee(n);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 _l.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await je.unlink(A.tombstoneFile(e,t))}catch(n){if(n.code!=="ENOENT")throw n}try{await je.rmdir(A.tombstoneAgentDir(e))}catch(n){let r=n;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw n}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await je.readdir(A.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}n.push(...await this.listForAgent(o))}return n}async listForAgent(e){let t;try{t=await je.readdir(A.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&n.push(i)}return n}};function Di(s,e){return s.reason==="user"||e===void 0?!1:s.upstreamUpdatedAt===void 0?!0:e>s.upstreamUpdatedAt}import*as Yi from"fs/promises";import{fileURLToPath as $l}from"url";import*as Wt from"path";import*as $n from"fs";function Fl(){try{let s=Wt.dirname($l(import.meta.url));for(let e=0;e<8;e+=1){let t=Wt.join(s,"package.json");if($n.existsSync(t)){let r=JSON.parse($n.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 n=Wt.dirname(s);if(n===s)break;s=n}}catch{}return"0.0.0"}var ie=Fl(),Fn="hydra-acp-cat";var Nl=12e4;async function Bi(s,e,t){let n=s.timeoutMs??Nl,r,o,i=!1;try{let a=(async()=>{r=ze.spawn({agentId:s.agentId,cwd:s.cwd,plan:s.plan,logger:s.logger});let d=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ie}}),u=await r.connection.request("session/new",{cwd:s.cwd,mcpServers:[]}),c=u.sessionId;if(typeof c!="string"){s.logger?.warn(`synopsis: agent ${s.agentId} returned non-string sessionId from session/new`),s.onFailure?.(`agent ${s.agentId} did not return a sessionId from session/new`);return}if(s.onWorkerSpawned?.(c,r.pid),s.modelId){let h=Hl(u);if(h.size===0||h.has(s.modelId)){let g=r.connection;try{await Je({request:(m,y)=>g.request(m,y),sessionId:c,modelId:s.modelId,verb:ct(u),logger:s.logger})}catch(m){s.logger?.warn(`synopsis: agent ${s.agentId} rejected model change to ${JSON.stringify(s.modelId)}: ${m.message}; continuing on default`)}}else s.logger?.warn(`synopsis: model ${JSON.stringify(s.modelId)} not advertised by agent ${s.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let l=[];r.connection.onNotification("session/update",h=>{let g=Ol(h);g.length>0&&l.push(g)}),await r.connection.request("session/prompt",{sessionId:c,prompt:[{type:"text",text:e}]});let p=l.join(""),f=t(p);if(!f){let h=JSON.stringify(p.slice(0,200));s.logger?.warn(`synopsis: agent ${s.agentId} reply did not parse (replyLen=${p.length} preview=${h})`);let g=p.slice(0,120).replace(/\s+/g," ").trim();s.onFailure?.(`agent ${s.agentId} returned unparseable JSON (${p.length} chars): ${g}${p.length>120?"\u2026":""}`)}return f})();return await new Promise((d,u)=>{o=setTimeout(()=>{i=!0,s.logger?.warn(`synopsis: agent ${s.agentId} timed out after ${n}ms`),s.onFailure?.(`agent ${s.agentId} timed out after ${n}ms`),d(void 0)},n),o.unref?.(),a.then(c=>{o&&clearTimeout(o),i||d(c)},c=>{o&&clearTimeout(o),i||u(c)})})}catch(a){let d=a.message;s.logger?.warn(`synopsis: agent ${s.agentId} failed: ${d}`),s.onFailure?.(`agent ${s.agentId} failed: ${d}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function Nn(s){let e=ht(s.history,{maxChars:s.maxTranscriptChars}),t=s.sessionId!==void 0?`[hydra-acp title-regen worker for session ${s.sessionId}]`:"[hydra-acp title-regen worker]",n=e.length>0?`${t}
109
+ Use empty arrays/strings where a field doesn't apply.`;function Pi(s){let e=s.trim();if(e.length===0)return;let t=bt(e);if(t===void 0){let c=e.indexOf("{"),u=e.lastIndexOf("}");c>=0&&u>c&&(t=bt(e.slice(c,u+1)))}if(t===void 0){let c=Mi(e);c!==void 0&&(t=bt(c))}if(t===void 0||t===null||typeof t!="object")return;let n=t,r={};if(typeof n.title=="string"){let c=n.title.trim();c.length>0&&(r.title=c.slice(0,Ri))}let o={},i=!1,a=["goal","outcome"];for(let c of a)if(typeof n[c]=="string"){let u=n[c].trim();u.length>0&&(o[c]=u,i=!0)}let d=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let c of d)if(Array.isArray(n[c])){let u=n[c],l=z.array(z.string()).safeParse(u);l.success&&u.length>0&&(o[c]=l.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function bt(s){try{return JSON.parse(s)}catch{return}}function Mi(s){let e=s.indexOf("{");if(e<0)return;let t=0,n=!1,r=!1;for(let o=e;o<s.length;o++){let i=s[o];if(n){r?r=!1:i==="\\"?r=!0:i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return s.slice(e,o+1)}}function ll(s){return s.goal!==void 0&&s.goal.trim().length>0||s.outcome!==void 0&&s.outcome.trim().length>0||s.files_touched!==void 0&&s.files_touched.length>0||s.tools_used!==void 0&&s.tools_used.length>0||s.rejected_approaches!==void 0&&s.rejected_approaches.length>0||s.open_threads!==void 0&&s.open_threads.length>0||s.decisions!==void 0&&s.decisions.length>0||s.file_edit_intentions!==void 0&&s.file_edit_intentions.length>0||s.unresolved_errors!==void 0&&s.unresolved_errors.length>0||s.tool_state!==void 0&&s.tool_state.length>0}var fl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gl=pl(fl,16),ml="hydra_lineage_";function Ut(){return`${ml}${gl()}`}var nr=P.object({name:P.string(),description:P.string().optional()}),sr=P.object({id:P.string(),name:P.string().optional(),description:P.string().optional()}),hl=P.object({modelId:P.string(),name:P.string().optional(),description:P.string().optional()}),rr=P.object({used:P.number().optional(),size:P.number().optional(),costAmount:P.number().optional(),costCurrency:P.string().optional(),cumulativeCost:P.number().optional()}),or=P.object({name:P.string(),version:P.string().optional()}),yl=P.object({path:P.string(),sourceCwd:P.string(),label:P.string(),requestedLabel:P.string().optional(),provider:P.string(),snapshot:P.string().optional(),line:P.string().optional(),vcs:P.record(P.string(),P.string()).optional(),clean:P.boolean().optional()}),wl=P.object({previousUpstreamSessionId:P.string(),previousSummarizedThroughEntry:P.number().int().nonnegative().optional(),runId:P.string().optional()}),kl=P.enum(["compaction","agent-swap","workspace-enter","workspace-leave","rollback","restart"]),bl=P.object({upstreamSessionId:P.string(),agentId:P.string(),reason:kl.optional(),runId:P.string().optional(),startedAt:P.string().optional(),endedAt:P.string().optional(),cost:P.number().nonnegative().optional(),inferred:P.boolean().optional()}),vl=P.object({version:P.literal(1),sessionId:P.string(),lineageId:P.string().optional(),upstreamSessionId:P.string(),importedFromSessionId:P.string().optional(),importedFromUpstreamSessionId:P.string().optional(),importedFromMachine:P.string().optional(),agentId:P.string(),cwd:P.string(),title:P.string().optional(),synopsis:jt.optional(),compactionState:xi.optional(),rollbackBreadcrumb:wl.optional(),upstreamGenerations:P.array(bl).optional(),summarizedThroughEntry:P.number().int().nonnegative().optional(),agentArgs:P.array(P.string()).optional(),currentModel:P.string().optional(),currentMode:P.string().optional(),currentUsage:rr.optional(),agentCommands:P.array(nr).optional(),agentModes:P.array(sr).optional(),agentModels:P.array(hl).optional(),pendingHistorySync:P.boolean().optional(),pendingAgentSwap:P.string().optional(),parentSessionId:P.string().optional(),forkedFromSessionId:P.string().optional(),forkedFromMessageId:P.string().optional(),forkSynthesisState:P.enum(["running","failed"]).optional(),originatingClient:or.optional(),interactive:P.boolean().optional(),priority:P.number().int().nonnegative().optional(),forwardedEnv:P.record(P.string(),P.string()).optional(),workspace:yl.optional(),attentionFlags:Ci.default([]).optional(),extensionState:P.record(P.string(),P.record(P.string(),P.unknown())).default({}).optional(),createdAt:P.string(),updatedAt:P.string()}),tr=/^[A-Za-z0-9_-]+$/;function Sl(s){if(!tr.test(s))throw new Error(`unsafe session id: ${s}`)}var vn=class{async write(e){Sl(e.sessionId);let t={version:1,...e};await fe(C.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!tr.test(e))return;let t=await ee(C.sessionFile(e));if(t!==void 0)try{return vl.parse(t)}catch{return}}async delete(e){if(tr.test(e)){try{await vt.unlink(C.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await vt.rmdir(C.sessionDir(e))}catch(t){let n=t;if(n.code!=="ENOENT"&&n.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let n of t)if(n.lineageId===e)return n}async list(){let e;try{e=await vt.readdir(C.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),n=[];for(let r of t)r&&n.push(r);return n}};function ir(s){let e=new Date().toISOString(),t=s.createdAt??e,n=s.upstreamGenerations??(s.upstreamSessionId?[{upstreamSessionId:s.upstreamSessionId,agentId:s.agentId,startedAt:t}]:[]);return{sessionId:s.sessionId,lineageId:s.lineageId,upstreamSessionId:s.upstreamSessionId,importedFromSessionId:s.importedFromSessionId,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,importedFromMachine:s.importedFromMachine,agentId:s.agentId,cwd:s.cwd,title:s.title,synopsis:s.synopsis,summarizedThroughEntry:s.summarizedThroughEntry,compactionState:s.compactionState,rollbackBreadcrumb:s.rollbackBreadcrumb,upstreamGenerations:n,agentArgs:s.agentArgs,currentModel:s.currentModel,currentMode:s.currentMode,currentUsage:s.currentUsage,agentCommands:s.agentCommands,agentModes:s.agentModes,agentModels:s.agentModels,pendingHistorySync:s.pendingHistorySync,pendingAgentSwap:s.pendingAgentSwap,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:s.interactive,priority:s.priority,forwardedEnv:s.forwardedEnv,workspace:s.workspace,attentionFlags:s.attentionFlags??[],extensionState:s.extensionState??{},createdAt:t,updatedAt:s.updatedAt??e}}Oe();K();import*as re from"fs/promises";import*as oe from"path";K();import*as Sn from"path";import{createHash as Il}from"crypto";var ve=class extends Error{constructor(e,t){super(`provider "${e}" does not support ${t}; check capabilities().supports before calling`),this.name="WorkspaceUnsupportedError"}};function St(s){let e=Il("sha256").update(Sn.resolve(s)).digest("hex").slice(0,12);return Sn.join(B(),"workspaces",e)}async function In(s,e,t=100){if(await e(s))return s;for(let n=2;n<=t;n+=1){let r=`${s}-${n}`;if(await e(r))return r}}function Ke(s,e=10){if(s.length<=e)return[...s];let t=s.slice(0,e),n=s.length-e;return[...t,`... and ${n} more`]}function ar(s){return s.changedPaths.length>0||s.recorded!==void 0&&s.recorded!==s.actual}function Al(s){let e=[];for(let t of s){if(t.changedPaths.length===0){e.push(`${t.relPath} (nested tree advanced to ${t.actual.slice(0,8)})`);continue}for(let n of t.changedPaths)e.push(`${t.relPath}/${n}`)}return e}function dr(s,e){let t=new Set(e.map(r=>r.relPath));return[...s.filter(r=>!t.has(r.replace(/\/$/,""))),...Al(e.filter(ar))]}function An(s){let e=s.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e.slice(0,64):"workspace"}var cr="copy",_i=new Set([".git"]);function Dt(s){return`${s}.manifest.json`}async function Ti(s){let e=new Map,t=[s];for(;t.length>0;){let n=t.pop();if(n===void 0)break;let r;try{r=await re.readdir(n,{withFileTypes:!0})}catch{continue}for(let o of r){let i=oe.join(n,o.name);if(!(n===s&&_i.has(o.name))){if(o.isDirectory()){t.push(i);continue}if(o.isFile())try{let a=await re.stat(i);e.set(oe.relative(s,i),{size:a.size,mtimeMs:a.mtimeMs})}catch{continue}}}}return e}var Cn=class{kind=cr;capabilities(){return{cheapWorkspaces:!1,sharedHistory:!1,nonMutatingCapture:!0,conflictReporting:!1,locking:!1,requiresServer:!1,supports:{record:!1,integrate:!1,captureWorkingState:!1,changedPaths:!1,environmentNotes:!0,rematerialize:!1,nestedTrees:!1}}}async materializeNested(){return{ok:!0,count:0}}async retainSnapshot(){}async dropSnapshotRef(){}async rematerialize(e){return{ok:!1,reason:`copy provider retains nothing outside ${e.path}; it cannot be rebuilt`}}async createWorkspace(e){if(e.from!==void 0)return{ok:!1,reason:"copy provider cannot create from a snapshot; it records none"};let t=oe.resolve(e.sourceCwd),n=e.contentFrom!==void 0?oe.resolve(e.contentFrom):t;try{if(!(await re.stat(n)).isDirectory())return{ok:!1,reason:`${n} is not a directory`}}catch{return{ok:!1,reason:`${n} does not exist`}}let r=St(t);try{await re.mkdir(r,{recursive:!0})}catch(c){return{ok:!1,reason:`could not create workspace root: ${String(c)}`}}let o=await In(An(e.label),async c=>re.access(oe.join(r,c)).then(()=>!1).catch(()=>!0));if(o===void 0)return{ok:!1,reason:`no free name available for "${e.label}"`};let i=oe.join(r,o);try{await re.cp(n,i,{recursive:!0,errorOnExist:!1,force:!0,filter:c=>{let u=oe.relative(n,c);if(u.length===0)return!0;let l=u.split(oe.sep)[0];return l===void 0||!_i.has(l)}})}catch(c){return await re.rm(i,{recursive:!0,force:!0}).catch(()=>{}),{ok:!1,reason:`copy failed: ${String(c)}`}}let a=await Ti(i),d={sourceCwd:t,label:o,createdAt:new Date().toISOString(),entries:Object.fromEntries(a)};return await fe(Dt(i),d,{pretty:!1}),{ok:!0,workspace:{path:i,sourceCwd:t,label:o,provider:this.kind}}}async removeWorkspace(e,t){if(!t.force){let n=await this.status(e);if(!n.clean)throw new Error(`workspace ${e.path} has ${n.changedPaths.length} changed path(s); pass force to remove`)}await re.rm(e.path,{recursive:!0,force:!0}),await re.rm(Dt(e.path),{force:!0})}async listWorkspaces(e){let t=St(oe.resolve(e)),n;try{n=await re.readdir(t)}catch{return[]}let r=[];for(let o of n){if(o.endsWith(".manifest.json"))continue;let i=oe.join(t,o),a=await ee(Dt(i));a!==void 0&&r.push({path:i,sourceCwd:a.sourceCwd,label:a.label,provider:this.kind})}return r}async status(e){let t=await ee(Dt(e.path)),n=await Ti(e.path);if(t===void 0)return{clean:!1,changedPaths:[...n.keys()].sort(),hasRecordedWork:!1};let r=[];for(let[o,i]of n){let a=t.entries[o];(a===void 0||a.size!==i.size||a.mtimeMs!==i.mtimeMs)&&r.push(o)}for(let o of Object.keys(t.entries))n.has(o)||r.push(o);return r.sort(),{clean:r.length===0,changedPaths:r,hasRecordedWork:!1}}async statusReport(e){let{changedPaths:t}=await this.status(e),n=t.length===0?["no changes since this copy was made"]:[`${t.length} changed file(s) since this copy was made:`,...Ke(t.map(r=>` ${r}`))];return n.push(`Not tracking ${T(e.sourceCwd)}: a copied directory has no shared history, so there is nothing to be in or out of sync with.`),n}async environmentNotes(e){return[`This directory is an isolated copy of ${e.sourceCwd}. It is not under version control: there is no history, no branches, and version-control commands will not behave as they would in the original.`,"Changes here are not automatically returned to the original directory."]}async captureWorkingState(){throw new ve(this.kind,"captureWorkingState")}async record(){throw new ve(this.kind,"record")}async attributeOrphan(e){let t=await ee(Dt(e));if(t?.sourceCwd!==void 0)return{path:e,sourceCwd:t.sourceCwd,label:t.label??oe.basename(e),provider:this.kind}}async discardLine(){return{ok:!0,dropped:0}}ownsLine(){return!1}async pruneStale(){}async changedPaths(){throw new ve(this.kind,"changedPaths")}async integrate(){return{ok:!1,conflicts:[],declined:!0,reason:`the "${this.kind}" provider keeps no history, so there is nothing to integrate from`}}async currentState(){}async contentId(){}async currentLineName(){}async resolveRoot(e){return e}async resolveRetained(){}async contains(){return!1}async divergence(){}async changedPathsBetween(){return[]}async captureDelta(){throw new ve(this.kind,"captureDelta")}async applyDelta(){return{ok:!1,reason:`the "${this.kind}" provider cannot reproduce a captured change`}}async resetTo(){return{ok:!1,reason:`the "${this.kind}" provider records no state to return to`}}async integrationInProgress(){return!1}async abortIntegration(){}async conflictedPaths(){return[]}async listNested(){return[]}async captureNested(){return[]}async reproduceNested(){return{applied:[],failed:[]}}async integrateNested(){return{applied:[],failed:[]}}async lock(){throw new ve(this.kind,"lock")}async unlock(){throw new ve(this.kind,"unlock")}};K();import{execFile as Hi}from"child_process";import{randomBytes as El}from"crypto";import*as Se from"fs/promises";import*as ji from"os";import*as G from"path";function Cl(s){let e=s.indexOf(" ");return e===-1?{key:s,value:""}:{key:s.slice(0,e),value:s.slice(e+1)}}function $i(s){let e=[],t,n=()=>{t!==void 0&&(e.push(t),t=void 0)};for(let r of s.split(`
110
+ `)){let o=r.replace(/\r$/,"");if(o.length===0){n();continue}let{key:i,value:a}=Cl(o);if(i==="worktree"){n(),t={path:a,bare:!1,detached:!1};continue}if(t!==void 0)switch(i){case"HEAD":t.head=a;break;case"branch":t.branch=a;break;case"bare":t.bare=!0;break;case"detached":t.detached=!0;break;case"locked":t.lockedReason=a;break;case"prunable":t.prunableReason=a;break;default:break}}return n(),e}function Fi(s){if(s===void 0)return;let e="refs/heads/";return s.startsWith(e)?s.slice(e.length):s}var En="git",Ni="hydra-acp:",ur="hydra",L=5e3,te=12e4,xn=9e5;function Oi(s){return Se.access(s).then(()=>!0).catch(()=>!1)}function Pl(s){return Se.realpath(s).catch(()=>s)}function H(s,e,t,n){return new Promise(r=>{Hi("git",s,{cwd:e,timeout:t,maxBuffer:8*1024*1024,...n?{env:{...process.env,...n}}:{}},(o,i,a)=>{r({ok:!o,stdout:i??"",stderr:a??""})})})}function lr(s,e,t,n=te){return new Promise(r=>{let o=Hi("git",s,{cwd:e,timeout:n,maxBuffer:67108864},(i,a,d)=>{r({ok:!i,stdout:a??"",stderr:d??""})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}function pr(s){let e=[];for(let t of s.split(`
111
+ `)){let n=t.replace(/\r$/,"");if(n.length<4)continue;let r=n.slice(3),o=r.indexOf(" -> ");e.push({code:n.slice(0,2),path:o===-1?r:r.slice(o+4)})}return e}var Rn=class{kind=En;refRoot(e){return e.vcs?.repoRoot??e.sourceCwd}ownsLine(e){return e.startsWith(`${ur}/`)}capabilities(){return{cheapWorkspaces:!0,sharedHistory:!0,nonMutatingCapture:!0,conflictReporting:!0,locking:!0,requiresServer:!1,supports:{record:!0,integrate:!0,captureWorkingState:!0,changedPaths:!1,environmentNotes:!0,rematerialize:!0,nestedTrees:!0}}}async materializeNested(e,t){if(!await Oi(G.join(e.path,".gitmodules")))return{ok:!0,count:0};let r=await H(["submodule","update","--init","--recursive",...t?.discardLocal===!0?["--force"]:[]],e.path,xn);if(!r.ok)return{ok:!1,count:0,reason:r.stderr.trim()||"git submodule update --init failed"};if(t?.discardLocal===!0){let a=await H(["submodule","foreach","--recursive","git","reset","--hard"],e.path,xn);if(!a.ok)return{ok:!1,count:0,reason:a.stderr.trim()||"could not reset submodules"};let d=t.purgeIgnored===!0?"-ffdx":"-fd",c=await H(["submodule","foreach","--recursive","git","clean",d],e.path,xn);if(!c.ok)return{ok:!1,count:0,reason:c.stderr.trim()||"could not clean submodules"}}let o=await H(["submodule","status","--recursive"],e.path,L);return{ok:!0,count:o.ok?o.stdout.split(`
112
+ `).filter(a=>a.trim().length>0).length:0}}async rematerialize(e){let t=e.vcs?.branch;if(t===void 0)return{ok:!1,reason:"workspace has no recorded branch to restore from"};let n=this.refRoot(e);if(!await Oi(n))return{ok:!1,reason:`source repository ${n} no longer exists`};let r=await H(["rev-parse","--verify","--quiet",`refs/heads/${t}`],n,L);if(!r.ok||r.stdout.trim().length===0)return{ok:!1,reason:`branch ${t} no longer exists in ${n}`};await H(["worktree","unlock",e.path],n,L),await H(["worktree","prune"],n,L);let o=await H(["worktree","add",e.path,t],n,te);return o.ok?{ok:!0,workspace:{...e,line:t,vcs:{...e.vcs??{},kind:"git",branch:t,repoRoot:n}}}:{ok:!1,reason:`could not restore worktree: ${o.stderr.trim()||"unknown error"}`}}async createWorkspace(e){let t=G.resolve(e.sourceCwd),n=await H(["rev-parse","--show-toplevel"],t,L);if(!n.ok)return{ok:!1,reason:`${t} is not a git repository (or git is unavailable)`};let r=n.stdout.trim();if(r.length===0)return{ok:!1,reason:`could not resolve the repository root for ${t}`};let o=await H(["rev-parse","HEAD"],r,L);if(!o.ok)return{ok:!1,reason:`${r} has no commits yet, so there is nothing to branch from`};let i=e.from??o.stdout.trim(),a=An(e.label),d=St(t);try{await Se.mkdir(d,{recursive:!0})}catch(p){return{ok:!1,reason:`could not create workspace root: ${String(p)}`}}let c=await In(a,async p=>await Se.access(G.join(d,p)).then(()=>!0).catch(()=>!1)?!1:!(await H(["rev-parse","--verify","--quiet",`refs/heads/${ur}/${p}`],r,L)).ok);if(c===void 0)return{ok:!1,reason:`no free name available for "${a}"`};let u=G.join(d,c),l=`${ur}/${c}`,f=await H(["worktree","add","--no-track","-b",l,u,i],r,te);return f.ok?{ok:!0,workspace:{path:u,sourceCwd:t,label:c,provider:this.kind,snapshot:i,line:l,vcs:{kind:"git",branch:l,base:i,repoRoot:r}}}:{ok:!1,reason:`git worktree add failed: ${f.stderr.trim()||"unknown error"}`}}async removeWorkspace(e,t){if(!t.force){let o=await this.status(e);if(!o.clean)throw new Error(`workspace ${e.path} has ${o.changedPaths.length} changed path(s)${o.hasRecordedWork?" and unintegrated recorded work":""}; pass force to remove`)}let n=this.refRoot(e);await this.unlock(e).catch(()=>{});let r=await H(["worktree","remove","--force",e.path],n,te);t.discardLine===!0&&e.vcs?.branch!==void 0&&await H(["branch","-D",e.vcs.branch],n,L),r.ok||(await Se.rm(e.path,{recursive:!0,force:!0}),await H(["worktree","prune"],n,L))}async listWorkspaces(e){let t=G.resolve(e),n=await H(["rev-parse","--show-toplevel"],t,L);if(!n.ok)return[];let r=n.stdout.trim(),o=await H(["worktree","list","--porcelain"],r,L);if(!o.ok)return[];let i=St(t),a=await Pl(i),d=[];for(let c of $i(o.stdout)){let u=G.dirname(c.path);if(u!==i&&u!==a)continue;let l=G.join(i,G.basename(c.path)),f={kind:"git",repoRoot:r},p=Fi(c.branch);p!==void 0&&(f.branch=p),c.head!==void 0&&(f.head=c.head),c.lockedReason!==void 0&&(f.locked=c.lockedReason);let g=c.lockedReason?.startsWith(Ni)===!0;d.push({path:l,sourceCwd:t,label:G.basename(l),...g?{heldByUs:!0}:{},provider:this.kind,...p!==void 0?{line:p}:{},vcs:f})}return d}async status(e){let t=await H(["status","--porcelain","--untracked-files=all"],e.path,L);if(!t.ok)return{clean:!1,changedPaths:[],hasRecordedWork:!1};let n=pr(t.stdout),r=n.map(a=>a.path),o=n.some(({code:a})=>a!=="??"&&a[0]!==" "&&a[0]!=="?"),i=!1;if(e.snapshot!==void 0){let a=await H(["rev-list","--count",`${e.snapshot}..HEAD`],e.path,L);a.ok&&(i=Number.parseInt(a.stdout.trim(),10)>0)}return{clean:r.length===0&&!i,changedPaths:r,hasRecordedWork:i,hasStagedWork:o}}async lock(e,t){let n=this.refRoot(e);await H(["worktree","lock","--reason",`${Ni}${t}`,e.path],n,L)}async unlock(e){let t=this.refRoot(e);await H(["worktree","unlock",e.path],t,L)}async environmentNotes(e){let t=[],n=e.vcs?.branch;return t.push(`This directory is a git worktree of ${e.sourceCwd}${n!==void 0?`, on branch ${n}`:""}. Do not read or write ${e.sourceCwd} directly; paths under it refer to the corresponding file here. Prefer repo-relative paths, which are identical in both.`),t.push("`.git` here is a file, not a directory. That is normal for a worktree and does not need repairing."),await Se.access(G.join(e.path,".gitmodules")).then(()=>!0).catch(()=>!1)&&t.push("Submodules here are initialized and checked out at the commits this tree records, which means each sits on a detached HEAD. That is normal and does not need repairing. Never re-add a submodule's contents as ordinary tracked files in the superproject: that silently corrupts the integration back to the source branch."),t}async statusReport(e){let t=[],n=await H(["status","--porcelain","--untracked-files=all"],e.path,L);if(n.ok){let r=pr(n.stdout);if(r.length===0)t.push("no uncommitted changes");else{let o=0,i=0,a=0;for(let{code:c}of r){if(c==="??"){a+=1;continue}c[0]!==" "&&c[0]!=="?"&&(o+=1),c[1]!==" "&&c[1]!=="?"&&(i+=1)}let d=[];o>0&&d.push(`${o} staged`),i>0&&d.push(`${i} unstaged`),a>0&&d.push(`${a} untracked`),t.push(`${d.join(", ")}:`),t.push(...Ke(r.map(c=>` ${c.code} ${c.path}`)))}}return t.push(...await this.syncLines(e)),t}async syncLines(e){if(e.vcs?.branch===void 0)return[];let[t,n]=await Promise.all([H(["rev-parse","HEAD"],e.sourceCwd,L),H(["rev-parse","HEAD"],e.path,L)]),r=t.stdout.trim(),o=n.stdout.trim();if(!t.ok||!n.ok||r.length===0||o.length===0)return[];let i=T(e.sourceCwd);if(r===o)return[`in sync with ${i}`];let a=await H(["rev-list","--left-right","--count",`${r}...${o}`],e.path,L),d=a.stdout.trim().split(/\s+/).map(f=>Number.parseInt(f,10)),c=d[0],u=d[1];if(!a.ok||c===void 0||u===void 0||!Number.isFinite(c)||!Number.isFinite(u))return[];let l=[];return c>0&&l.push(`${c} commit(s) behind ${i}. \`/hydra workspace sync\` brings them in; landing is fast-forward-only, so this also unblocks \`stop\`.`),u>0&&l.push(`${u} commit(s) recorded here and not landed yet.`),l}async captureWorkingState(e,t){let n=G.join(ji.tmpdir(),`hydra-index-${process.pid}-${El(6).toString("hex")}`),r={GIT_INDEX_FILE:n};try{let o=await H(["rev-parse","--verify","HEAD"],e,L),i=o.ok&&o.stdout.trim().length>0;if(i){let l=await H(["read-tree","HEAD"],e,te,r);if(!l.ok)throw new Error(`could not seed the snapshot index: ${l.stderr.trim()}`)}let a=await H(["add","-A"],e,te,r);if(!a.ok)throw new Error(`could not stage working state: ${a.stderr.trim()}`);let d=await H(["write-tree"],e,te,r);if(!d.ok||d.stdout.trim().length===0)throw new Error(`could not write tree: ${d.stderr.trim()}`);let c=["commit-tree",d.stdout.trim(),"-m",t];i&&c.push("-p",o.stdout.trim());let u=await H(c,e,te,r);if(!u.ok||u.stdout.trim().length===0)throw new Error(`could not create snapshot commit: ${u.stderr.trim()}`);return u.stdout.trim()}finally{await Se.rm(n,{force:!0}).catch(()=>{})}}async retainSnapshot(e,t,n){let r=this.refRoot(e);await H(["update-ref","--create-reflog",t,n],r,L)}async dropSnapshotRef(e,t){let n=this.refRoot(e);await H(["update-ref","-d",t],n,L)}async currentState(e){let t=await H(["rev-parse","HEAD"],e,L),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async contentId(e,t){let n=await H(["rev-parse",`${t}^{tree}`],e,L),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async currentLineName(e){let t=await H(["rev-parse","--abbrev-ref","HEAD"],e,L),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async resolveRoot(e){let t=await H(["rev-parse","--show-toplevel"],e,L),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async resolveRetained(e,t){let n=await H(["rev-parse","--verify","--quiet",`${t}^{commit}`],this.refRoot(e),L),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async contains(e,t){return(await H(["merge-base","--is-ancestor",t.state,t.within],e,L)).ok}async divergence(e,t,n){let r=await H(["rev-list","--left-right","--count",`${t}...${n}`],e,L);if(!r.ok)return;let o=r.stdout.trim().split(/\s+/).map(d=>Number.parseInt(d,10)),i=o[0],a=o[1];if(!(i===void 0||a===void 0||!Number.isFinite(i)||!Number.isFinite(a)))return{ahead:i,behind:a}}async changedPathsBetween(e,t,n){let r=await H(["diff","--name-only",t,n],e,L);return r.ok?r.stdout.split(`
113
+ `).map(o=>o.replace(/\r$/,"").trim()).filter(o=>o.length>0):[]}async captureDelta(e,t,n){let r=await H(["diff","--binary","--ignore-submodules=all",t,n],e,te);if(r.ok)return r.stdout}async applyDelta(e,t,n){if(t.trim().length===0)return{ok:!0,alreadyPresent:!0};let r=n?.stage===!0?["--index"]:[],o=await lr(["apply",...r],e,t);if(o.ok)return{ok:!0};if(n?.tolerant!==!0)return{ok:!1,reason:o.stderr.trim()||"the change did not apply"};if((await lr(["apply","--reverse","--check"],e,t)).ok)return{ok:!0,alreadyPresent:!0};let a=await lr(["apply","--3way"],e,t);return a.ok?{ok:!0}:{ok:!1,reason:a.stderr.trim()||"the change overlaps what is already there"}}async resetTo(e,t,n){let r=await H(["reset","--hard",t],e,te);if(!r.ok)return{ok:!1,reason:r.stderr.trim()||"could not return to that state"};let o=await H(["clean",n?.purgeIgnored===!0?"-ffdx":"-fd"],e,te);if(!o.ok)return{ok:!1,reason:o.stderr.trim()||"returned to that state but could not remove extra files"};let i=await this.materializeNested({path:e,sourceCwd:e,label:"",provider:this.kind},{discardLocal:!0,...n?.purgeIgnored===!0?{purgeIgnored:!0}:{}});return i.ok?{ok:!0}:{ok:!1,reason:i.reason??"could not reset nested trees"}}async integrationInProgress(e){return(await H(["rev-parse","-q","--verify","MERGE_HEAD"],e,L)).ok}async abortIntegration(e){await H(["merge","--abort"],e,te)}async conflictedPaths(e){let t=await H(["diff","--name-only","--diff-filter=U"],e,L);return t.ok?t.stdout.split(`
114
+ `).map(n=>n.replace(/\r$/,"").trim()).filter(n=>n.length>0):[]}async record(e,t){let n=await H(["add","-A"],e.path,te);if(!n.ok)throw new Error(`could not stage ${e.path}: ${n.stderr.trim()||"unknown error"}`);let r=await this.status(e),o=await this.currentState(e.path);if(r.changedPaths.length===0){if(o===void 0)throw new Error(`could not read the state of ${e.path}`);return o}let i=await H(["commit","-m",t],e.path,te);if(!i.ok)throw new Error(`could not record ${e.path}: ${i.stderr.trim()||i.stdout.trim()||"unknown error"}`);let a=await this.currentState(e.path);if(a===void 0)throw new Error(`recorded ${e.path} but could not read the resulting state`);return a}async attributeOrphan(e){let t=await H(["rev-parse","--path-format=absolute","--git-common-dir"],e,L),n=t.stdout.trim();if(!t.ok||n.length===0)return;let r=G.dirname(n),o=await this.currentLineName(e);return{path:e,sourceCwd:r,label:G.basename(e),provider:this.kind,...o!==void 0?{line:o}:{},vcs:{repoRoot:r,...o!==void 0?{branch:o}:{}}}}async discardLine(e,t){let n=this.refRoot(e),o=(await this.divergence(n,"HEAD",t))?.behind??0,i=await H(["branch","-D",t],n,L);return i.ok?{ok:!0,dropped:o}:{ok:!1,dropped:o,reason:i.stderr.trim()||"could not discard the line"}}async pruneStale(e){await H(["worktree","prune"],this.refRoot(e),L)}async changedPaths(){throw new ve(this.kind,"changedPaths")}async integrate(e){let{into:t,from:n}=e,r=await this.currentState(t);if(r===void 0)return{ok:!1,conflicts:[],declined:!0,reason:`cannot read the state of ${t}`};if(await this.contains(t,{state:n,within:r}))return{ok:!0,snapshot:r,alreadyUpToDate:!0};if(e.fastForwardOnly===!0&&!await this.contains(t,{state:r,within:n}))return{ok:!1,conflicts:[],declined:!0,reason:`${t} cannot simply advance to that state; it has moved on independently`};let o=e.fastForwardOnly===!0?["merge","--ff-only",n]:["merge","--no-edit","-m",e.message??"hydra: integrate",n],i=await H(o,t,te);if(i.ok){let c=await this.currentState(t);return c===void 0?{ok:!1,conflicts:[],reason:"integrated but could not read the resulting state"}:{ok:!0,snapshot:c}}let a=await this.conflictedPaths(t),d=await this.integrationInProgress(t);return a.length===0&&!d?{ok:!1,conflicts:[],declined:!0,reason:i.stderr.trim()||"the integration was refused"}:(e.onConflict==="abort"&&await this.abortIntegration(t),{ok:!1,conflicts:a})}async listNested(e){let t=await H(["submodule","status","--recursive"],e,te);if(!t.ok)return[];let n=[];for(let r of t.stdout.split(`
115
+ `)){let o=r.replace(/\r$/,"");if(o.trim().length===0||(o[0]??" ")==="-")continue;let a=o.slice(1),d=a.indexOf(" ");if(d<=0)continue;let c=a.slice(d+1).replace(/\s+\(.*\)\s*$/,"").trim();if(c.length===0||!Ml(e,c))continue;let u=G.join(e,c),[l,f,p]=await Promise.all([this.currentState(u),H(["rev-parse",`HEAD:${c}`],e,L),H(["status","--porcelain","--untracked-files=all"],u,L)]);if(l===void 0)continue;let g=f.ok?f.stdout.trim():"";n.push({relPath:c,actual:l,...g.length>0?{recorded:g}:{},changedPaths:p.ok?pr(p.stdout).map(m=>m.path):[]})}return n}async captureNested(e,t){let n=[];for(let r of t){if(!ar(r))continue;if(r.changedPaths.length===0){n.push(r);continue}let o=G.join(e,r.relPath),i=await this.captureWorkingState(o,"hydra: nested work carried into workspace").catch(()=>{});if(i===void 0){n.push(r);continue}let a=await this.captureDelta(o,r.actual,i);n.push(a===void 0?r:{...r,delta:a})}return n}async reproduceNested(e,t,n){let r=[],o=[];for(let i of n){let a=G.join(e,i.relPath),d=G.join(t,i.relPath),c=await this.alignNested(a,d,i.actual);if(c!==void 0){o.push({path:i.relPath,reason:c});continue}if(i.delta!==void 0){let u=await this.applyDelta(a,i.delta);if(!u.ok){o.push({path:i.relPath,reason:u.reason??"changes did not apply"});continue}}r.push(i.relPath)}return{applied:r,failed:o}}async integrateNested(e,t,n){let r=[],o=[],i=new Map(n.map(c=>[c.relPath,c])),a=await this.listNested(e),d=new Set([...a.map(c=>c.relPath),...i.keys()]);for(let c of[...d].sort()){let u=a.find(h=>h.relPath===c),l=i.get(c);if(u===void 0){o.push({path:c,reason:"not populated in the receiving tree"});continue}let f=u.recorded!==void 0&&u.recorded!==u.actual,p=l?.delta!==void 0;if(!f&&!p)continue;if(u.changedPaths.length>0){o.push({path:c,reason:`it has ${u.changedPaths.length} uncommitted change(s) of its own, and nothing can tell those apart from what was integrated`});continue}let g=G.join(e,c),m=G.join(t,c);if(f&&u.recorded!==void 0){let h=await this.alignNested(g,m,u.recorded);if(h!==void 0){o.push({path:c,reason:h});continue}}if(l?.delta!==void 0){let h=await this.applyDelta(g,l.delta);if(!h.ok){o.push({path:c,reason:h.reason??"the uncommitted changes there did not apply"});continue}}r.push(c)}return{applied:r,failed:o}}async alignNested(e,t,n){let r=await this.currentState(e);if(r===void 0)return"not populated here";if(r===n)return;if(!(await H(["cat-file","-e",`${n}^{commit}`],e,L)).ok&&!(await H(["fetch","--no-tags",t,n],e,xn)).ok)return`could not transfer ${n.slice(0,8)} from the other copy`;if(!(await H(["checkout","--detach",n],e,te)).ok)return`could not move to ${n.slice(0,8)}`}};function Ml(s,e){if(G.isAbsolute(e))return!1;let t=G.resolve(s),n=G.resolve(t,e);return n!==t&&n.startsWith(t+G.sep)}var Tl=En,_l=new Map([[En,new Rn],[cr,new Cn]]);function Y(s){return _l.get(s??Tl)}var Pn="refs/hydra";function Bt(s){let e=`${Pn}/workspaces/${s}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function fr(s){return`${Pn}/landing/${s}`}function Ui(s){return`${Pn}/sync/${s}`}function Di(s,e){return`${Pn}/retired/${s}-${e.slice(0,12)}`}function Bi(s){let e=Bt(s);return[e.autosave,e.start,e.baseline]}async function gr(s){let{source:e,ws:t,startSnapshotRef:n,baselineRef:r,retainRef:o,provider:i}=s;if(i===void 0)throw new Error("no provider available to inspect the source tree");let a=await i.status({...t,path:e}).catch(()=>{}),d="";for(let l of[r,n]){if(l===void 0)continue;let f=await i.resolveRetained(t,l).catch(()=>{});if(f!==void 0){d=f;break}}let c=a===void 0||a.changedPaths.length>0;if(d.length===0){if(c)throw new Error(`${e} has uncommitted changes but this workspace has no start anchor, so its copy of your work cannot be told apart from edits you made since. Refusing rather than reporting a conflict that is not yours. Commit or stash the source, then retry.`);d=await i.currentState(e).catch(()=>{})??""}if(!c)return{clean:!0,base:d};if(i.capabilities().supports.captureWorkingState!==!0)throw new Error(`${e} has uncommitted changes and this provider cannot snapshot them, so they cannot be preserved across the landing. Commit or stash them first.`);let u=await i.captureWorkingState(e,"hydra: source state before landing").catch(()=>{});if(u===void 0)throw new Error(`could not snapshot the uncommitted changes in ${e}, so refusing to touch them`);return await i.retainSnapshot({...t,path:e},o,u),{clean:!1,snapshot:u,base:d,retainedRef:o}}async function Ye(s){let{source:e,capture:t,provider:n}=s;if(t.clean||t.snapshot===void 0||n===void 0)return!0;let r=await n.captureDelta(e,t.base,t.snapshot).catch(()=>{});return r===void 0?!1:(await n.applyDelta(e,r,{tolerant:!0})).ok}async function Lt(s){s.capture.retainedRef===void 0||s.provider===void 0||await s.provider.dropSnapshotRef({...s.ws,path:s.source},s.capture.retainedRef).catch(()=>{})}Oe();import{execFile as $l}from"child_process";import*as Te from"fs/promises";import*as he from"path";var Fl=".hydra/worktree.json",Nl=".worktreeinclude",Ol=120;async function Mn(s){let e=await ee(he.join(s,Fl))??{},t=new Set(Array.isArray(e.carry)?e.carry:[]),n=await Te.readFile(he.join(s,Nl),"utf8").catch(()=>{});if(n!==void 0)for(let o of n.split(`
116
+ `)){let i=o.trim();i.length===0||i.startsWith("#")||i.startsWith("!")||i.includes("*")||i.includes("?")||t.add(i)}let r={};return t.size>0&&(r.carry=[...t]),typeof e.postCreate=="string"&&(r.postCreate=e.postCreate),typeof e.preRemove=="string"&&(r.preRemove=e.preRemove),typeof e.hookTimeoutSeconds=="number"&&(r.hookTimeoutSeconds=e.hookTimeoutSeconds),r}async function mr(s,e,t){let n=[],r=[],o=he.resolve(s),i=he.resolve(e);for(let a of t){let d=he.resolve(o,a),c=he.resolve(i,a);if(!d.startsWith(o+he.sep)||!c.startsWith(i+he.sep)){r.push(a);continue}if(await Te.access(c).then(()=>!0).catch(()=>!1)){r.push(a);continue}let l=await Te.stat(d).catch(()=>{});if(l===void 0){r.push(a);continue}try{await Te.mkdir(he.dirname(c),{recursive:!0}),await Te.cp(d,c,{recursive:l.isDirectory()}),n.push(a)}catch{r.push(a)}}return{copied:n,skipped:r}}async function Tn(s,e){let t=JSON.stringify({path:e.workspacePath,sourceCwd:e.sourceCwd,label:e.label,...e.sessionId!==void 0?{sessionId:e.sessionId}:{}}),n=(e.timeoutSeconds??Ol)*1e3;return new Promise(r=>{let o=$l("/bin/sh",["-c",s],{cwd:e.workspacePath,timeout:n,maxBuffer:8388608,env:{...process.env,HYDRA_WORKSPACE_PATH:e.workspacePath,HYDRA_SOURCE_CWD:e.sourceCwd,HYDRA_WORKSPACE_LABEL:e.label,...e.sessionId!==void 0?{HYDRA_SESSION_ID:e.sessionId}:{}}},(i,a,d)=>{if(i){let c=(d||i.message||"").trim().slice(0,500);r({ok:!1,reason:c.length>0?c:"hook failed"});return}r({ok:!0})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}K();Oe();import*as je from"fs/promises";import{z as _e}from"zod";var Hl=_e.object({version:_e.literal(1),agentId:_e.string(),upstreamSessionId:_e.string(),deletedAt:_e.string(),upstreamUpdatedAt:_e.string().optional(),cwd:_e.string().optional(),title:_e.string().optional(),reason:_e.enum(["user","expired"]).optional(),interactive:_e.boolean().optional()}),_n=class{async add(e){let t={version:1,...e};await fe(C.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await je.access(C.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let n=C.tombstoneFile(e,t),r=await ee(n);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 Hl.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await je.unlink(C.tombstoneFile(e,t))}catch(n){if(n.code!=="ENOENT")throw n}try{await je.rmdir(C.tombstoneAgentDir(e))}catch(n){let r=n;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw n}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await je.readdir(C.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}n.push(...await this.listForAgent(o))}return n}async listForAgent(e){let t;try{t=await je.readdir(C.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&n.push(i)}return n}};function Li(s,e){return s.reason==="user"||e===void 0?!1:s.upstreamUpdatedAt===void 0?!0:e>s.upstreamUpdatedAt}import*as ea from"fs/promises";import{customAlphabet as zl}from"nanoid";import{fileURLToPath as jl}from"url";import*as Wt from"path";import*as $n from"fs";function Ul(){try{let s=Wt.dirname(jl(import.meta.url));for(let e=0;e<8;e+=1){let t=Wt.join(s,"package.json");if($n.existsSync(t)){let r=JSON.parse($n.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 n=Wt.dirname(s);if(n===s)break;s=n}}catch{}return"0.0.0"}var ie=Ul(),Fn="hydra-acp-cat";var Dl=12e4;async function qi(s,e,t){let n=s.timeoutMs??Dl,r,o,i=!1;try{let a=(async()=>{r=ze.spawn({agentId:s.agentId,cwd:s.cwd,plan:s.plan,logger:s.logger});let d=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ie}}),c=await r.connection.request("session/new",{cwd:s.cwd,mcpServers:[]}),u=c.sessionId;if(typeof u!="string"){s.logger?.warn(`synopsis: agent ${s.agentId} returned non-string sessionId from session/new`),s.onFailure?.(`agent ${s.agentId} did not return a sessionId from session/new`);return}if(s.onWorkerSpawned?.(u,r.pid),s.modelId){let g=Ll(c);if(g.size===0||g.has(s.modelId)){let m=r.connection;try{await Je({request:(h,y)=>m.request(h,y),sessionId:u,modelId:s.modelId,verb:ct(c),logger:s.logger})}catch(h){s.logger?.warn(`synopsis: agent ${s.agentId} rejected model change to ${JSON.stringify(s.modelId)}: ${h.message}; continuing on default`)}}else s.logger?.warn(`synopsis: model ${JSON.stringify(s.modelId)} not advertised by agent ${s.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let l=[];r.connection.onNotification("session/update",g=>{let m=Bl(g);m.length>0&&l.push(m)}),await r.connection.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:e}]});let f=l.join(""),p=t(f);if(!p){let g=JSON.stringify(f.slice(0,200));s.logger?.warn(`synopsis: agent ${s.agentId} reply did not parse (replyLen=${f.length} preview=${g})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();s.onFailure?.(`agent ${s.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((d,c)=>{o=setTimeout(()=>{i=!0,s.logger?.warn(`synopsis: agent ${s.agentId} timed out after ${n}ms`),s.onFailure?.(`agent ${s.agentId} timed out after ${n}ms`),d(void 0)},n),o.unref?.(),a.then(u=>{o&&clearTimeout(o),i||d(u)},u=>{o&&clearTimeout(o),i||c(u)})})}catch(a){let d=a.message;s.logger?.warn(`synopsis: agent ${s.agentId} failed: ${d}`),s.onFailure?.(`agent ${s.agentId} failed: ${d}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function Nn(s){let e=mt(s.history,{maxChars:s.maxTranscriptChars}),t=s.sessionId!==void 0?`[hydra-acp title-regen worker for session ${s.sessionId}]`:"[hydra-acp title-regen worker]",n=e.length>0?`${t}
115
117
 
116
118
  ${e}
117
119
 
118
120
  ${Zs}`:`${t}
119
121
 
120
- ${Zs}`;return Bi(s,n,Ci)}async function Ui(s){let e=ht(s.history,{maxChars:s.maxTranscriptChars}),t=s.sessionId!==void 0?`[hydra-acp compaction worker for session ${s.sessionId}]`:"[hydra-acp compaction worker]",n=e.length>0?`${t}
122
+ ${Zs}`;return qi(s,n,Ei)}async function zi(s){let e=mt(s.history,{maxChars:s.maxTranscriptChars}),t=s.sessionId!==void 0?`[hydra-acp compaction worker for session ${s.sessionId}]`:"[hydra-acp compaction worker]",n=e.length>0?`${t}
121
123
 
122
124
  ${e}
123
125
 
124
126
  ${er}`:`${t}
125
127
 
126
- ${er}`;return Bi(s,n,xi)}function Ol(s){if(!s||typeof s!="object")return"";let e=s.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let n=t.content;return n&&typeof n.text=="string"?n.text:""}function Hl(s){let e=new Set;Li(e,s.availableModels);let t=s.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Li(e,t.availableModels),e}function Li(s,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let n=t.modelId??t.value??t.id;typeof n=="string"&&n.length>0&&s.add(n)}}}function jl(s){let e=new Map;for(let t of Vi(s).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,n])=>({name:t,count:n})).sort((t,n)=>n.count-t.count||t.name.localeCompare(n.name))}function zi(s){return jl(s).map(e=>e.name)}function Dl(s){let e=new Map;for(let t of Vi(s).values())for(let n of t.paths){let r=e.get(n);r===void 0&&(r=new Map,e.set(n,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,n])=>{let r=[...n.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,n)=>n.count-t.count||t.path.localeCompare(n.path))}function Ji(s){return Dl(s).map(e=>e.path)}function Vi(s){let e=new Map,t=0;for(let n of s){let o=n.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,u=e.get(d);u===void 0?(u={toolName:Wi(o),paths:new Set},e.set(d,u)):u.toolName=Wi(o);for(let c of qi(o.rawInput,o.locations))u.paths.add(c);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let d of qi(o.rawInput,o.locations))a.paths.add(d)}return e}function Wi(s){return typeof s.name=="string"&&s.name.length>0?s.name:typeof s.title=="string"&&s.title.length>0?s.title:"(unnamed)"}function qi(s,e){let t=new Set;if(s&&typeof s=="object"&&!Array.isArray(s)){let n=s;typeof n.file_path=="string"?t.add(n.file_path):typeof n.path=="string"&&t.add(n.path);let r=n.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}for(let n of Yo(e))t.add(n);return t}K();var Ll=2,On=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ll}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 n=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...n?{targetAgentId:n}:{}};return}this.queued[e]={kind:"compaction",...n?{targetAgentId:n}:{}},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 n=t-Date.now();if(n<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,n).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 n=this.queued[t];delete this.queued[t];let r=this.runOne(t,n).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let n=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=n==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.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 ye(u,[],{npmRegistry:this.opts.npmRegistry}),l=this.opts.compactionAgent===void 0&&r===void 0,p=n==="compaction"?this.opts.compactionModel??(l?o.currentModel:void 0):this.opts.synopsisModel,f=A.sessionDir(e);if(await Yi.mkdir(f,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${f}`),n==="compaction"){let h=this.opts.compactionMaxIterations??3,g=0,m=a??0,y,k=0,w,b=Date.now(),v={targetAgentId:r},S=R=>this.opts.onCompactionStateChange?.(e,R,v)??Promise.resolve(),x=R=>{this.opts.broadcastHydraCompaction?.(e,R,v)};await S({status:"requested",requestedAt:b}),x({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{g++,this.opts.logger?.info(`synopsis: compaction iteration ${g} sessionId=${e} historyLen=${i.length} watermark=${m}`);let R=await this.opts.histories.load(e,{maxEntries:1/0});if(R.length===m)break;let M=await Ui({agentId:d,cwd:f,plan:c,history:R,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,O)=>{S({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:$,pid:O??0}})},onFailure:$=>{w=$}});if(M){let $=Qi(M.synopsis,R);$&&Gi($)&&(await this.opts.persistSynopsis(e,$,R.length),y=$,k=R.length,w=void 0,await S({status:"running",requestedAt:b,iter:g}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:R.length}),await this.opts.onSynthesisArtifact?.(e,$,k,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${Ki($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(m=R.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(g<h);if(y)g>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${k} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let R=w??(g===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${g} iteration(s)`);await S({status:"failed",requestedAt:b,iter:g,lastError:R}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:R}),r&&await this.opts.onSynthesisUnavailable?.(e,r,R)}}catch(R){let M=R instanceof Error?R.message:String(R);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${M}`),await S({status:"failed",requestedAt:b,iter:g,lastError:M}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:M},{targetAgentId:r}),r)try{await this.opts.onSynthesisUnavailable?.(e,r,M)}catch{}}}else{let h=await Nn({agentId:d,cwd:f,plan:c,history:i,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let g=Qi(h.synopsis,i);g&&Gi(g)?(await this.opts.persistSynopsis(e,g,i.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${Ki(g)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function Qi(s,e){let t=Ji(e),n=zi(e);return s?{...s,files_touched:t.length>0?t:s.files_touched,tools_used:n.length>0?n:s.tools_used}:t.length===0&&n.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:n.length>0?n:void 0}}function Gi(s){return!!(s.goal&&s.goal.trim().length>0||s.outcome&&s.outcome.trim().length>0||s.files_touched&&s.files_touched.length>0||s.tools_used&&s.tools_used.length>0||s.rejected_approaches&&s.rejected_approaches.length>0||s.open_threads&&s.open_threads.length>0)}function Ki(s){let e=[];return s.goal&&e.push("goal"),s.outcome&&e.push("outcome"),s.files_touched&&s.files_touched.length>0&&e.push(`files=${s.files_touched.length}`),s.tools_used&&s.tools_used.length>0&&e.push(`tools=${s.tools_used.length}`),s.rejected_approaches&&s.rejected_approaches.length>0&&e.push(`rejected=${s.rejected_approaches.length}`),s.open_threads&&s.open_threads.length>0&&e.push(`open=${s.open_threads.length}`),`[${e.join(",")}]`}K();import*as z from"fs/promises";import{createReadStream as Vl}from"fs";import{createGunzip as Ql,gzip as Gl,gunzip as Kl}from"zlib";import{createInterface as Yl}from"readline";import{promisify as sa}from"util";function Xi(s){return s==="summary"?"summary":"inline"}var mr=256,Bl=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],Ul=["content","stdout","stderr"];function Zi(s,e){return e!=="summary"?s:s.map(Wl)}function Wl(s){if(s.method!=="session/update")return s;let e=s.params;if(!e||typeof e!="object"||Array.isArray(e))return s;let t=e,n=t.update;if(!n||typeof n!="object"||Array.isArray(n))return s;let r=n;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return s;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(ea));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Hn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let u of Bl)a[u]!==void 0&&(d[u]=a[u]);for(let u of Ul)typeof a[u]=="string"&&(d[u]=Hn(a[u]));o.rawOutput=d}return{...s,params:{...t,update:o}}}function ql(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="diff"}function ea(s){if(ql(s)){let n=s,r={type:"diff",oldText:"",newText:""};return typeof n.path=="string"&&(r.path=n.path),r}if(!s||typeof s!="object"||Array.isArray(s))return s;let e=s,t={...e};return typeof e.text=="string"&&(t.text=Hn(e.text)),typeof e.content=="string"?t.content=Hn(e.content):e.content&&typeof e.content=="object"&&(t.content=ea(e.content)),t}function Hn(s){if(typeof s=="string"&&s.length>mr){let e=s.length-mr;return`${s.slice(0,mr)}\u2026[+${e} chars omitted from summary export]`}return s}var zl=2048;function ta(s){let e=new Set,t=n=>{if(na(n)){e.add(n.__hydraBlob);return}if(Array.isArray(n)){for(let r of n)t(r);return}if(n&&typeof n=="object")for(let r of Object.values(n))t(r)};for(let n of s)t(n.params);return e}function na(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.__hydraBlob=="string"}function Jl(s){if(s.method!=="session/update")return!1;let e=s.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 n=t.sessionUpdate;return n==="tool_call"||n==="tool_call_update"}async function kr(s,e){if(!Jl(s))return s;let t=s.params,n=t.update,r=await yr(n,e);return{...s,params:{...t,update:r}}}async function yr(s,e){if(typeof s=="string"){if(s.length<=zl)return s;let t=await e(s);return t===null?s:{__hydraBlob:t,bytes:s.length}}if(Array.isArray(s)){let t=[];for(let n of s)t.push(await yr(n,e));return t}if(s&&typeof s=="object"){let t={};for(let[n,r]of Object.entries(s))t[n]=await yr(r,e);return t}return s}async function br(s,e){let t=s.params;if(!t||typeof t!="object"||Array.isArray(t))return s;let n=await wr(t,e);return n===t?s:{...s,params:n}}async function wr(s,e){if(na(s))return await e(s.__hydraBlob)??"";if(Array.isArray(s)){let t=!1,n=[];for(let r of s){let o=await wr(r,e);o!==r&&(t=!0),n.push(o)}return t?n:s}if(s&&typeof s=="object"){let t=!1,n={};for(let[r,o]of Object.entries(s)){let i=await wr(o,e);i!==o&&(t=!0),n[r]=i}return t?n:s}return s}var Xl=sa(Gl),Zl=sa(Kl),ef=/^history\.jsonl\.(\d+)(\.gz)?$/,Ie=/^[A-Za-z0-9_-]+$/,tf=1e3,nf=1e7,sf=10,jn=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??tf,this.archiveMaxBytes=e.archiveMaxBytes??nf,this.archiveTiers=e.archiveTiers??sf}async append(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{await z.mkdir(A.sessionDir(e),{recursive:!0});let n=await kr(t,o=>Is(e,o)),r=JSON.stringify(n)+`
127
- `;await z.appendFile(A.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{await z.mkdir(A.sessionDir(e),{recursive:!0});let n=[];for(let o of t)n.push(await kr(o,i=>Is(e,i)));let r=n.length===0?"":n.map(o=>JSON.stringify(o)).join(`
128
+ ${er}`;return qi(s,n,Pi)}function Bl(s){if(!s||typeof s!="object")return"";let e=s.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let n=t.content;return n&&typeof n.text=="string"?n.text:""}function Ll(s){let e=new Set;Wi(e,s.availableModels);let t=s.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Wi(e,t.availableModels),e}function Wi(s,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let n=t.modelId??t.value??t.id;typeof n=="string"&&n.length>0&&s.add(n)}}}function Wl(s){let e=new Map;for(let t of Ki(s).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,n])=>({name:t,count:n})).sort((t,n)=>n.count-t.count||t.name.localeCompare(n.name))}function Gi(s){return Wl(s).map(e=>e.name)}function ql(s){let e=new Map;for(let t of Ki(s).values())for(let n of t.paths){let r=e.get(n);r===void 0&&(r=new Map,e.set(n,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,n])=>{let r=[...n.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,n)=>n.count-t.count||t.path.localeCompare(n.path))}function Qi(s){return ql(s).map(e=>e.path)}function Ki(s){let e=new Map,t=0;for(let n of s){let o=n.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:Ji(o),paths:new Set},e.set(d,c)):c.toolName=Ji(o);for(let u of Vi(o.rawInput,o.locations))c.paths.add(u);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let d of Vi(o.rawInput,o.locations))a.paths.add(d)}return e}function Ji(s){return typeof s.name=="string"&&s.name.length>0?s.name:typeof s.title=="string"&&s.title.length>0?s.title:"(unnamed)"}function Vi(s,e){let t=new Set;if(s&&typeof s=="object"&&!Array.isArray(s)){let n=s;typeof n.file_path=="string"?t.add(n.file_path):typeof n.path=="string"&&t.add(n.path);let r=n.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}for(let n of Xo(e))t.add(n);return t}K();var Jl=zl("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",12),Vl=2,On=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Vl}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 n=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...n?{targetAgentId:n}:{}};return}this.queued[e]={kind:"compaction",...n?{targetAgentId:n}:{}},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 n=t-Date.now();if(n<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,n).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 n=this.queued[t];delete this.queued[t];let r=this.runOne(t,n).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let n=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=n==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let u=await we(c,[],{npmRegistry:this.opts.npmRegistry}),l=this.opts.compactionAgent===void 0&&r===void 0,f=n==="compaction"?this.opts.compactionModel??(l?o.currentModel:void 0):this.opts.synopsisModel,p=C.sessionDir(e);if(await ea.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),n==="compaction"){let g=this.opts.compactionMaxIterations??3,m=0,h=a??0,y,k=0,w,S=Date.now(),I=Jl(),b={targetAgentId:r},A=E=>this.opts.onCompactionStateChange?.(e,{runId:I,...E},b)??Promise.resolve(),R=E=>{this.opts.broadcastHydraCompaction?.(e,E,b)};await A({status:"requested",requestedAt:S}),R({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:S});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${i.length} watermark=${h}`);let E=await this.opts.histories.load(e,{maxEntries:1/0});if(E.length===h)break;let $=await zi({agentId:d,cwd:p,plan:u,history:E,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(M,W)=>{A({status:"running",requestedAt:S,iter:m,worker:{upstreamSessionId:M,pid:W??0}})},onFailure:M=>{w=M}});if($){let M=Yi($.synopsis,E);M&&Xi(M)&&(await this.opts.persistSynopsis(e,M,E.length),y=M,k=E.length,w=void 0,await A({status:"running",requestedAt:S,iter:m}),R({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:E.length}),await this.opts.onSynthesisArtifact?.(e,M,k,r,I),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Zi(M)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(h=E.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(m<g);if(y)this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} runId=${I} watermark=${k} iterations=${m}`+(m>=g?` (hit maxIterations=${g})`:"")),R({sessionUpdate:"hydra_compaction",phase:"converged",iter:m,summarizedThroughEntry:k});else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${g} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let E=w??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await A({status:"failed",requestedAt:S,iter:m,lastError:E}),R({sessionUpdate:"hydra_compaction",phase:"failed",error:E}),r&&await this.opts.onSynthesisUnavailable?.(e,r,E)}}catch(E){let $=E instanceof Error?E.message:String(E);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${$}`),await A({status:"failed",requestedAt:S,iter:m,lastError:$}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:$},{targetAgentId:r}),r)try{await this.opts.onSynthesisUnavailable?.(e,r,$)}catch{}}}else{let g=await Nn({agentId:d,cwd:p,plan:u,history:i,modelId:f,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=Yi(g.synopsis,i);m&&Xi(m)?(await this.opts.persistSynopsis(e,m,i.length),g.title&&await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!g.title)} fields=${Zi(m)}`)):g.title&&(await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function Yi(s,e){let t=Qi(e),n=Gi(e);return s?{...s,files_touched:t.length>0?t:s.files_touched,tools_used:n.length>0?n:s.tools_used}:t.length===0&&n.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:n.length>0?n:void 0}}function Xi(s){return!!(s.goal&&s.goal.trim().length>0||s.outcome&&s.outcome.trim().length>0||s.files_touched&&s.files_touched.length>0||s.tools_used&&s.tools_used.length>0||s.rejected_approaches&&s.rejected_approaches.length>0||s.open_threads&&s.open_threads.length>0)}function Zi(s){let e=[];return s.goal&&e.push("goal"),s.outcome&&e.push("outcome"),s.files_touched&&s.files_touched.length>0&&e.push(`files=${s.files_touched.length}`),s.tools_used&&s.tools_used.length>0&&e.push(`tools=${s.tools_used.length}`),s.rejected_approaches&&s.rejected_approaches.length>0&&e.push(`rejected=${s.rejected_approaches.length}`),s.open_threads&&s.open_threads.length>0&&e.push(`open=${s.open_threads.length}`),`[${e.join(",")}]`}K();import*as J from"fs/promises";import{createReadStream as ep}from"fs";import{createGunzip as tp,gzip as np,gunzip as sp}from"zlib";import{createInterface as rp}from"readline";import{promisify as ia}from"util";function ta(s){return s==="summary"?"summary":"inline"}var hr=256,Gl=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],Ql=["content","stdout","stderr"];function na(s,e){return e!=="summary"?s:s.map(Kl)}function Kl(s){if(s.method!=="session/update")return s;let e=s.params;if(!e||typeof e!="object"||Array.isArray(e))return s;let t=e,n=t.update;if(!n||typeof n!="object"||Array.isArray(n))return s;let r=n;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return s;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(sa));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Hn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let c of Gl)a[c]!==void 0&&(d[c]=a[c]);for(let c of Ql)typeof a[c]=="string"&&(d[c]=Hn(a[c]));o.rawOutput=d}return{...s,params:{...t,update:o}}}function Yl(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="diff"}function sa(s){if(Yl(s)){let n=s,r={type:"diff",oldText:"",newText:""};return typeof n.path=="string"&&(r.path=n.path),r}if(!s||typeof s!="object"||Array.isArray(s))return s;let e=s,t={...e};return typeof e.text=="string"&&(t.text=Hn(e.text)),typeof e.content=="string"?t.content=Hn(e.content):e.content&&typeof e.content=="object"&&(t.content=sa(e.content)),t}function Hn(s){if(typeof s=="string"&&s.length>hr){let e=s.length-hr;return`${s.slice(0,hr)}\u2026[+${e} chars omitted from summary export]`}return s}var Xl=2048;function ra(s){let e=new Set,t=n=>{if(oa(n)){e.add(n.__hydraBlob);return}if(Array.isArray(n)){for(let r of n)t(r);return}if(n&&typeof n=="object")for(let r of Object.values(n))t(r)};for(let n of s)t(n.params);return e}function oa(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.__hydraBlob=="string"}function Zl(s){if(s.method!=="session/update")return!1;let e=s.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 n=t.sessionUpdate;return n==="tool_call"||n==="tool_call_update"}async function kr(s,e){if(!Zl(s))return s;let t=s.params,n=t.update,r=await yr(n,e);return{...s,params:{...t,update:r}}}async function yr(s,e){if(typeof s=="string"){if(s.length<=Xl)return s;let t=await e(s);return t===null?s:{__hydraBlob:t,bytes:s.length}}if(Array.isArray(s)){let t=[];for(let n of s)t.push(await yr(n,e));return t}if(s&&typeof s=="object"){let t={};for(let[n,r]of Object.entries(s))t[n]=await yr(r,e);return t}return s}async function br(s,e){let t=s.params;if(!t||typeof t!="object"||Array.isArray(t))return s;let n=await wr(t,e);return n===t?s:{...s,params:n}}async function wr(s,e){if(oa(s))return await e(s.__hydraBlob)??"";if(Array.isArray(s)){let t=!1,n=[];for(let r of s){let o=await wr(r,e);o!==r&&(t=!0),n.push(o)}return t?n:s}if(s&&typeof s=="object"){let t=!1,n={};for(let[r,o]of Object.entries(s)){let i=await wr(o,e);i!==o&&(t=!0),n[r]=i}return t?n:s}return s}var op=ia(np),ip=ia(sp),ap=/^history\.jsonl\.(\d+)(\.gz)?$/,Ie=/^[A-Za-z0-9_-]+$/,dp=1e3,cp=1e7,up=10,jn=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??dp,this.archiveMaxBytes=e.archiveMaxBytes??cp,this.archiveTiers=e.archiveTiers??up}async append(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{await J.mkdir(C.sessionDir(e),{recursive:!0});let n=await kr(t,o=>Is(e,o)),r=JSON.stringify(n)+`
129
+ `;await J.appendFile(C.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{await J.mkdir(C.sessionDir(e),{recursive:!0});let n=[];for(let o of t)n.push(await kr(o,i=>Is(e,i)));let r=n.length===0?"":n.map(o=>JSON.stringify(o)).join(`
128
130
  `)+`
129
- `;await z.writeFile(A.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{let n;try{n=await z.readFile(A.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=n.split(`
130
- `).filter(a=>a.length>0);if(r.length<=t)return;let o=r.slice(0,r.length-t),i=r.slice(-t);this.archiveMaxBytes>0&&o.length>0&&await this.spillToArchive(e,o),await z.writeFile(A.historyFile(e),i.join(`
131
+ `;await J.writeFile(C.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(Ie.test(e))return this.enqueue(e,async()=>{let n;try{n=await J.readFile(C.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=n.split(`
132
+ `).filter(a=>a.length>0);if(r.length<=t)return;let o=r.slice(0,r.length-t),i=r.slice(-t);this.archiveMaxBytes>0&&o.length>0&&await this.spillToArchive(e,o),await J.writeFile(C.historyFile(e),i.join(`
131
133
  `)+`
132
134
  `,{encoding:"utf8",mode:384})})}async spillToArchive(e,t){let n=t.join(`
133
135
  `)+`
134
- `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let o=A.historyArchiveFile(e,r);await z.mkdir(A.sessionDir(e),{recursive:!0}),await z.appendFile(o,n,{encoding:"utf8",mode:384});let i=0;try{i=(await z.stat(o)).size}catch{i=0}i>=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 n=A.historyArchiveFile(e,t),r;try{r=await z.readFile(n)}catch(i){if(i.code==="ENOENT")return;throw i}let o=await Xl(r);await z.writeFile(n+".gz",o,{mode:384});try{await z.unlink(n)}catch(i){if(i.code!=="ENOENT")throw i}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let n=await this.listArchiveIndices(e),r=n.length===0?0:n[n.length-1],o=r===0?1:r;if(r>0){let i=A.historyArchiveFile(e,r),a=i+".gz",d=!1;try{await z.access(a),d=!0}catch{d=!1}if(d)o=r+1;else try{(await z.stat(i)).size>=this.archiveMaxBytes&&(o=r+1)}catch{o=r}}return this.nextArchiveIndex.set(e,o),o}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let n=await this.listArchiveIndices(e),o=(n.includes(t)?n.length:n.length+1)-this.archiveTiers,i=0;for(;o>0&&i<n.length;){let a=n[i];a!==t&&(await this.unlinkArchive(e,a),o-=1),i+=1}}async unlinkArchive(e,t){let n=A.historyArchiveFile(e,t);for(let r of[n,n+".gz"])try{await z.unlink(r)}catch(o){if(o.code!=="ENOENT")throw o}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await z.readdir(A.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let n=new Set;for(let r of t){let o=ef.exec(r);if(!o)continue;let i=Number.parseInt(o[1],10);Number.isFinite(i)&&i>0&&n.add(i)}return[...n].sort((r,o)=>r-o)}async listArchives(e){if(!Ie.test(e))return[];let t=await this.listArchiveIndices(e),n=[];for(let r of t){let o=A.historyArchiveFile(e,r),i=o+".gz",a=o;try{await z.access(i),a=i}catch{a=o}n.push({index:r,path:a})}return n}async loadArchives(e){if(!Ie.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let n=await this.listArchives(e),r=[];for(let{path:o}of n){let i;try{if(o.endsWith(".gz")){let a=await z.readFile(o);i=(await Zl(a)).toString("utf8")}else i=await z.readFile(o,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of i.split(`
135
- `)){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=Vl(e)}catch(i){if(i.code==="ENOENT")return;throw i}if(await new Promise(i=>{let a=!1,d=u=>{a||(a=!0,i(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(Ql()):t,o=Yl({input:r,crlfDelay:1/0});try{for await(let i of o){if(i.length===0)continue;let a;try{a=JSON.parse(i)}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{o.close(),t.destroy()}}async getArchiveLineCounts(e){if(!Ie.test(e))return[];let t=this.archiveLineCounts.get(e),n=await this.listArchives(e);if(t&&t.length===n.length&&t.every((o,i)=>o.index===n[i].index&&o.path===n[i].path))return t;let r=[];for(let{index:o,path:i}of n){let a=t?.find(u=>u.index===o&&u.path===i);if(a){r.push(a);continue}let d=0;for await(let u of this.streamFile(i))d+=1;r.push({index:o,path:i,lineCount:d})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,n){return br(t,async r=>{let o=n.get(r);if(o!==void 0)return o;let i=await Tt(e,r);return n.set(r,i),i})}async*iterRecallNewestFirst(e){if(!Ie.test(e))return;let t=this.writeQueues.get(e);t&&await t;let n=await this.getArchiveLineCounts(e),r=0;for(let u of n)r+=u.lineCount;let o=new Map,i=[];for await(let u of this.streamFile(A.historyFile(e)))i.push(u);for(let u=i.length-1;u>=0;u--){let c=await this.hydrateEntry(e,i[u],o);yield{entryId:r+u,entry:c}}let a=new Array(n.length),d=0;for(let u=0;u<n.length;u++)a[u]=d,d+=n[u].lineCount;for(let u=n.length-1;u>=0;u--){let c=n[u],l=[];for await(let f of this.streamFile(c.path))l.push(f);let p=a[u];for(let f=l.length-1;f>=0;f--){let h=await this.hydrateEntry(e,l[f],o);yield{entryId:p+f,entry:h}}}}async rangeSlice(e,t,n){if(!Ie.test(e))return[];if(n<t)return[];let r=this.writeQueues.get(e);r&&await r;let o=await this.getArchiveLineCounts(e),i=0;for(let c of o)i+=c.lineCount;let a=[],d=new Map,u=0;for(let c of o){let l=u,p=u+c.lineCount;if(u=p,p<=t)continue;if(l>n)break;let f=0;for await(let h of this.streamFile(c.path)){let g=l+f;if(f+=1,g<t)continue;if(g>n)break;let m=await this.hydrateEntry(e,h,d);a.push({entryId:g,entry:m})}}if(n>=i){let c=Math.max(t-i,0),l=n-i,p=0;for await(let f of this.streamFile(A.historyFile(e))){if(p>l)break;if(p>=c){let h=await this.hydrateEntry(e,f,d);a.push({entryId:i+p,entry:h})}p+=1}}return a}async getRecallTotalCount(e){if(!Ie.test(e))return 0;let t=await this.getArchiveLineCounts(e),n=0;for(let o of t)n+=o.lineCount;let r=0;for await(let o of this.streamFile(A.historyFile(e)))r+=1;return n+r}async load(e,t={}){if(!Ie.test(e))return[];let n=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await z.readFile(A.historyFile(e),"utf8")}catch(p){if(p.code==="ENOENT")return[];throw p}let i=[];for(let p of o.split(`
136
- `)){if(p.length===0)continue;let f;try{f=JSON.parse(p)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let h=f;typeof h.method=="string"&&typeof h.recordedAt=="number"&&i.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!n)return d;let u=new Map,c=async p=>{let f=u.get(p);if(f!==void 0)return f;let h=await Tt(e,p);return u.set(p,h),h},l=[];for(let p of d)l.push(await br(p,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Ie.test(e))return this.enqueue(e,async()=>{try{await z.unlink(A.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}let t=await this.listArchiveIndices(e);for(let n of t)await this.unlinkArchive(e,n);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await mo(e);try{await z.rmdir(A.sessionDir(e))}catch(n){let r=n;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw n}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};K();import{promises as ra}from"fs";import*as oa from"path";async function ia(s,e){await ra.mkdir(oa.dirname(s),{recursive:!0});let t=e.map(n=>JSON.stringify(n));await ra.writeFile(s,t.length>0?t.join(`
136
+ `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let o=C.historyArchiveFile(e,r);await J.mkdir(C.sessionDir(e),{recursive:!0}),await J.appendFile(o,n,{encoding:"utf8",mode:384});let i=0;try{i=(await J.stat(o)).size}catch{i=0}i>=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 n=C.historyArchiveFile(e,t),r;try{r=await J.readFile(n)}catch(i){if(i.code==="ENOENT")return;throw i}let o=await op(r);await J.writeFile(n+".gz",o,{mode:384});try{await J.unlink(n)}catch(i){if(i.code!=="ENOENT")throw i}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let n=await this.listArchiveIndices(e),r=n.length===0?0:n[n.length-1],o=r===0?1:r;if(r>0){let i=C.historyArchiveFile(e,r),a=i+".gz",d=!1;try{await J.access(a),d=!0}catch{d=!1}if(d)o=r+1;else try{(await J.stat(i)).size>=this.archiveMaxBytes&&(o=r+1)}catch{o=r}}return this.nextArchiveIndex.set(e,o),o}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let n=await this.listArchiveIndices(e),o=(n.includes(t)?n.length:n.length+1)-this.archiveTiers,i=0;for(;o>0&&i<n.length;){let a=n[i];a!==t&&(await this.unlinkArchive(e,a),o-=1),i+=1}}async unlinkArchive(e,t){let n=C.historyArchiveFile(e,t);for(let r of[n,n+".gz"])try{await J.unlink(r)}catch(o){if(o.code!=="ENOENT")throw o}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await J.readdir(C.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let n=new Set;for(let r of t){let o=ap.exec(r);if(!o)continue;let i=Number.parseInt(o[1],10);Number.isFinite(i)&&i>0&&n.add(i)}return[...n].sort((r,o)=>r-o)}async listArchives(e){if(!Ie.test(e))return[];let t=await this.listArchiveIndices(e),n=[];for(let r of t){let o=C.historyArchiveFile(e,r),i=o+".gz",a=o;try{await J.access(i),a=i}catch{a=o}n.push({index:r,path:a})}return n}async loadArchives(e){if(!Ie.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let n=await this.listArchives(e),r=[];for(let{path:o}of n){let i;try{if(o.endsWith(".gz")){let a=await J.readFile(o);i=(await ip(a)).toString("utf8")}else i=await J.readFile(o,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of i.split(`
137
+ `)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let c=d;typeof c.method=="string"&&typeof c.recordedAt=="number"&&r.push({method:c.method,params:c.params,recordedAt:c.recordedAt})}}return r}async*streamFile(e){let t;try{t=ep(e)}catch(i){if(i.code==="ENOENT")return;throw i}if(await new Promise(i=>{let a=!1,d=c=>{a||(a=!0,i(c))};t.once("error",c=>{c.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(tp()):t,o=rp({input:r,crlfDelay:1/0});try{for await(let i of o){if(i.length===0)continue;let a;try{a=JSON.parse(i)}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{o.close(),t.destroy()}}async getArchiveLineCounts(e){if(!Ie.test(e))return[];let t=this.archiveLineCounts.get(e),n=await this.listArchives(e);if(t&&t.length===n.length&&t.every((o,i)=>o.index===n[i].index&&o.path===n[i].path))return t;let r=[];for(let{index:o,path:i}of n){let a=t?.find(c=>c.index===o&&c.path===i);if(a){r.push(a);continue}let d=0;for await(let c of this.streamFile(i))d+=1;r.push({index:o,path:i,lineCount:d})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,n){return br(t,async r=>{let o=n.get(r);if(o!==void 0)return o;let i=await Tt(e,r);return n.set(r,i),i})}async*iterRecallNewestFirst(e){if(!Ie.test(e))return;let t=this.writeQueues.get(e);t&&await t;let n=await this.getArchiveLineCounts(e),r=0;for(let c of n)r+=c.lineCount;let o=new Map,i=[];for await(let c of this.streamFile(C.historyFile(e)))i.push(c);for(let c=i.length-1;c>=0;c--){let u=await this.hydrateEntry(e,i[c],o);yield{entryId:r+c,entry:u}}let a=new Array(n.length),d=0;for(let c=0;c<n.length;c++)a[c]=d,d+=n[c].lineCount;for(let c=n.length-1;c>=0;c--){let u=n[c],l=[];for await(let p of this.streamFile(u.path))l.push(p);let f=a[c];for(let p=l.length-1;p>=0;p--){let g=await this.hydrateEntry(e,l[p],o);yield{entryId:f+p,entry:g}}}}async rangeSlice(e,t,n){if(!Ie.test(e))return[];if(n<t)return[];let r=this.writeQueues.get(e);r&&await r;let o=await this.getArchiveLineCounts(e),i=0;for(let u of o)i+=u.lineCount;let a=[],d=new Map,c=0;for(let u of o){let l=c,f=c+u.lineCount;if(c=f,f<=t)continue;if(l>n)break;let p=0;for await(let g of this.streamFile(u.path)){let m=l+p;if(p+=1,m<t)continue;if(m>n)break;let h=await this.hydrateEntry(e,g,d);a.push({entryId:m,entry:h})}}if(n>=i){let u=Math.max(t-i,0),l=n-i,f=0;for await(let p of this.streamFile(C.historyFile(e))){if(f>l)break;if(f>=u){let g=await this.hydrateEntry(e,p,d);a.push({entryId:i+f,entry:g})}f+=1}}return a}async getRecallTotalCount(e){if(!Ie.test(e))return 0;let t=await this.getArchiveLineCounts(e),n=0;for(let o of t)n+=o.lineCount;let r=0;for await(let o of this.streamFile(C.historyFile(e)))r+=1;return n+r}async load(e,t={}){if(!Ie.test(e))return[];let n=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await J.readFile(C.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let i=[];for(let f of o.split(`
138
+ `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let g=p;typeof g.method=="string"&&typeof g.recordedAt=="number"&&i.push({method:g.method,params:g.params,recordedAt:g.recordedAt})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!n)return d;let c=new Map,u=async f=>{let p=c.get(f);if(p!==void 0)return p;let g=await Tt(e,f);return c.set(f,g),g},l=[];for(let f of d)l.push(await br(f,u));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Ie.test(e))return this.enqueue(e,async()=>{try{await J.unlink(C.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}let t=await this.listArchiveIndices(e);for(let n of t)await this.unlinkArchive(e,n);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await yo(e);try{await J.rmdir(C.sessionDir(e))}catch(n){let r=n;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw n}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};K();import{promises as aa}from"fs";import*as da from"path";async function ca(s,e){await aa.mkdir(da.dirname(s),{recursive:!0});let t=e.map(n=>JSON.stringify(n));await aa.writeFile(s,t.length>0?t.join(`
137
139
  `)+`
138
- `:"")}import{z as q}from"zod";var rf=q.object({method:q.string(),params:q.unknown(),recordedAt:q.number()}),of=q.object({sessionId:q.string(),lineageId:q.string(),upstreamSessionId:q.string().optional(),agentId:q.string(),cwd:q.string(),title:q.string().optional(),synopsis:jt.optional(),summarizedThroughEntry:q.number().int().nonnegative().optional(),currentModel:q.string().optional(),currentMode:q.string().optional(),currentUsage:rr.optional(),agentCommands:q.array(nr).optional(),agentModes:q.array(sr).optional(),interactive:q.boolean().optional(),originatingClient:or.optional(),priority:q.number().int().nonnegative().optional(),createdAt:q.string(),updatedAt:q.string()}),af=q.object({version:q.literal(1),exportedAt:q.string(),exportedFrom:q.object({hydraVersion:q.string(),machine:q.string(),hydraHost:q.string().optional()}),session:of,history:q.array(rf),promptHistory:q.array(q.string()).optional(),toolBlobs:q.record(q.string()).optional()});function qt(s){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:s.hydraVersion,machine:s.machine,...s.hydraHost!==void 0&&s.hydraHost.length>0?{hydraHost:s.hydraHost}:{}},session:{sessionId:s.record.sessionId,lineageId:s.record.lineageId,...s.record.upstreamSessionId?{upstreamSessionId:s.record.upstreamSessionId}:{},agentId:s.record.agentId,cwd:s.record.cwd,...s.record.title!==void 0?{title:s.record.title}:{},...s.record.synopsis!==void 0?{synopsis:s.record.synopsis}:{},...s.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:s.record.summarizedThroughEntry}:{},...s.record.currentModel!==void 0?{currentModel:s.record.currentModel}:{},...s.record.currentMode!==void 0?{currentMode:s.record.currentMode}:{},...s.record.currentUsage!==void 0?{currentUsage:s.record.currentUsage}:{},...s.record.agentCommands!==void 0?{agentCommands:s.record.agentCommands}:{},...s.record.agentModes!==void 0?{agentModes:s.record.agentModes}:{},...s.record.interactive!==void 0?{interactive:s.record.interactive}:{},...s.record.originatingClient!==void 0?{originatingClient:s.record.originatingClient}:{},...s.record.priority!==void 0&&s.record.priority>0?{priority:s.record.priority}:{},createdAt:s.record.createdAt,updatedAt:s.record.updatedAt},history:s.history};return s.promptHistory!==void 0&&(e.promptHistory=s.promptHistory),s.toolBlobs!==void 0&&Object.keys(s.toolBlobs).length>0&&(e.toolBlobs=s.toolBlobs),e}function aa(s){return af.parse(s)}function vr(s){if(s&&!(s.costAmount===void 0&&s.cumulativeCost===void 0))return(s.cumulativeCost??0)+(s.costAmount??0)}function zt(s){if(!s)return;let e={};s.used!==void 0&&(e.used=s.used),s.size!==void 0&&(e.size=s.size);let t=vr(s);return t&&(e.costAmount=t),s.costCurrency!==void 0&&(e.costCurrency=s.costCurrency),e}var da=900*1e3,cf=12,uf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",It=df(uf,16),Dn=class s{constructor(e,t,n,r={}){this.registry=e;this.spawner=t??(a=>ze.spawn(a)),this.store=n??new vn,this.tombstones=r.tombstones??new _n,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new jn({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=r.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new On({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,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)},onSynthesisUnavailable:async(a,d,u)=>{let c=await this.store.read(a).catch(()=>{});if(c?.synopsis&&c.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${u}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,c.synopsis,c.summarizedThroughEntry,d);return}let l=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${u}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,l,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=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,n,r){let o=this.get(e);if(t===void 0&&r===void 0)return;if(!o){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:n});return}let i=this.compactionTailK;try{if(await o.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(o,t,i,n,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=o.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 n=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):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,n,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,n,o.summarizedThroughEntry,i)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,n,r,o){try{let i=o?Math.min(t===void 0?cf:5,n):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:n,tailFloor:i,summarizedThroughEntry:r,...o?{newAgentId:o}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await ot(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let n=Y(t.provider);if(n===void 0){let c=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${c}`);return this.logger?.warn?.(`session workspace: ${c}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:c}}let r=t.label??`s-${It().slice(0,8)}`,o=await n.createWorkspace({sourceCwd:e.cwd,label:r,...t.from!==void 0?{from:t.from}:{}}).catch(c=>({ok:!1,reason:String(c)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;n.capabilities().locking&&await n.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await Mn(i.sourceCwd).catch(()=>({})),d,u=await this.materializeNestedTrees(i);if(u!==void 0&&this.logger?.info?.(`session workspace: ${u} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let c=await hr(i.sourceCwd,i.path,a.carry).catch(()=>{});c!==void 0&&c.copied.length>0&&this.logger?.info?.(`session workspace: carried ${c.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let c=await Tn(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});c.ok||(d=`postCreate failed: ${c.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await n.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let n=`${Me}${It()}`,r=await this.resolveWorkspace(e),o=r.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:n});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let u of e.transformChain)if(u.intercepts.has("agent:initialize"))try{let c=await u.connection.request("hydra-acp/transformer/message",{token:`t_${It()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});c.action==="stop"&&c.payload&&(d=c.payload)}catch{}i.agentCapabilities=d}let a=new wt({sessionId:n,cwd:o,...r.workspace!==void 0?{workspace:r.workspace}:{},...r.isolationError!==void 0?{workspaceError:r.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:n}),loadExistingAgentSession:(d,u)=>this.bootstrapAgentLoad(d,{...u,mcpServers:u.mcpServers??[],selfSessionId:n}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.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(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,u,c)=>this.runWorkspaceAction(a.sessionId,d,u,c),onCompactionSwapHook:d=>{this.mutateRecord(a.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(r.workspace!==void 0){let d=Y(r.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:r.workspace.path,sourceCwd:r.workspace.sourceCwd,label:r.workspace.label,provider:r.workspace.provider,...r.workspace.snapshot!==void 0?{snapshot:r.workspace.snapshot}:{},...r.workspace.vcs!==void 0?{vcs:r.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=C.AlreadyAttached,o}return t}let n=this.resurrectionInflight.get(e.hydraSessionId);if(n)return n;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 n=await this.registry.getAgent(e.agentId);if(!n){let y=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw y.code=C.AgentNotInstalled,y}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await ye(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=an(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...o?{extraEnv:o}:{}}),a;try{let y=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}});a=y.agentCapabilities,i.authMethods=Jt(y.authMethods)}catch(y){throw await i.kill().catch(()=>{}),Ve(y,i)}let d;try{let y=ua(e.agentId,e.currentModel);d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...y&&{_meta:y}})}catch(y){if(y&&typeof y=="object"&&y.code===C.AuthRequired)throw await i.kill().catch(()=>{}),Ve(y,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${y.message}); recovering via import-reseed
139
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let u=Rr(d??{}),c=e.agentModes??Ar(xr(d??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(u)} advertisedModes=${JSON.stringify(c?.map(y=>y.id))}`);let l=await ut({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:u,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let p=Ir(d??{}),f=Ar(Cr(d??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(p)} advertisedModels=${JSON.stringify(f?.map(y=>y.modelId))}`),e.pendingHistorySync!==!0){let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=ct(d),g=await lt({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:p,...h?{modelVerb:h}:{},logger:this.logger});if(e.pendingHistorySync!==!0){let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new wt({sessionId:e.hydraSessionId,cwd:e.cwd,...e.workspace!==void 0?{workspace:e.workspace}:{},agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:d?._meta,agentCapabilities:a,...h?{modelVerb:h}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:y=>this.bootstrapAgent({...y,mcpServers:y.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(y,k)=>this.bootstrapAgentLoad(y,{...k,mcpServers:k.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:g,currentMode:l,currentUsage:e.currentUsage,reloadsUpstreamLedger:!0,agentCommands:e.agentCommands,agentModes:c,agentModels:f,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(m),scheduleCompaction:y=>this.scheduleCompaction(m.sessionId,y),resolveAgentId:async y=>(await this.registry.getAgent(y))?.id,getCompactionState:()=>this.getCompactionState(m.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),forkHook:y=>this.forkSession(m.sessionId,y??{}),workspaceHook:(y,k,w)=>this.runWorkspaceAction(m.sessionId,y,k,w),onCompactionSwapHook:y=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:y}).catch(()=>{})},persistWatermarkHook:y=>{this.mutateRecord(m.sessionId,{summarizedThroughEntry:y}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let t=await this.resolveResurrectTarget(e.cwd,e.workspace),n=t.cwd,r=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),o=e.agentModes??r.initialModes,i=await ut({agent:r.agent,upstreamSessionId:r.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:r.initialMode,advertisedModes:o,logger:this.logger}),a=e.agentModels??r.initialModels,d=await lt({agent:r.agent,upstreamSessionId:r.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:r.initialModel,...r.modelVerb?{modelVerb:r.modelVerb}:{},logger:this.logger});r.agent.connection.drainBuffered("session/update");let u=new wt({sessionId:e.hydraSessionId,cwd:n,...t.workspace!==void 0?{workspace:t.workspace}:{},agentId:e.agentId,agent:r.agent,upstreamSessionId:r.upstreamSessionId,agentMeta:r.agentMeta,agentCapabilities:r.agentCapabilities,...r.modelVerb?{modelVerb:r.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:c.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(c,l)=>this.bootstrapAgentLoad(c,{...l,mcpServers:l.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:d,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:o,agentModels:a,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(u.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(u),scheduleCompaction:c=>this.scheduleCompaction(u.sessionId,c),resolveAgentId:async c=>(await this.registry.getAgent(c))?.id,getCompactionState:()=>this.getCompactionState(u.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(u.sessionId),uncompactHook:()=>this.performUncompact(u.sessionId),forkHook:c=>this.forkSession(u.sessionId,c??{}),workspaceHook:(c,l,p)=>this.runWorkspaceAction(u.sessionId,c,l,p),onCompactionSwapHook:c=>{this.mutateRecord(u.sessionId,{rollbackBreadcrumb:c}).catch(()=>{})},persistWatermarkHook:c=>{this.mutateRecord(u.sessionId,{summarizedThroughEntry:c}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(u.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(u),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${u.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?u.seedFromFork(e.synopsis).catch(()=>{}):u.seedFromImport().catch(()=>{}),u}async dirExists(e){try{return(await Ye.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);if(!(!t||t.attachedCount>0)&&t.interactive!==!0){if(t.hasWorkInFlight){this.logger?.info(`deferring reap of ${e}: work still in flight after detach`),t.onceIdle(n=>{this.reapIfOrphanedNonInteractive(n.sessionId).catch(()=>{})});return}this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}async resolveResurrectTarget(e,t){if(await this.dirExists(e))return t!==void 0?{cwd:e,workspace:t}:{cwd:e};if(t!==void 0){let n=await this.recoverWorkspace(t);if(n!==void 0)return{cwd:n.path,workspace:n}}return{cwd:de(this.defaultCwd)}}async releaseWorkspace(e,t){let n=Y(e.provider);if(n===void 0){this.logger?.warn?.(`session workspace: no provider "${e.provider}" to release ${e.path}; leaving it in place`);return}return this.enqueueKeyed(this.workspaceQueues,e.path,async()=>{let r=this.liveSessionsIn(e.path,t);if(r.length>0){this.logger?.info?.(`session workspace: keeping ${e.path} \u2014 ${r.length} live session(s) still in it`);return}await this.tearDownWorkspace(n,e,t)})}async syncWorkspaceFromSource(e,t,n){let r=this.liveSessionsIn(t.path,e.sessionId);if(r.length>0)throw new Error(`${P(t.path)} is shared with ${r.map(p=>He(p.sessionId)).join(", ")}, and a sync would move files under them. Sync it from a session that has it to itself.`);if(!await e.isQuiescedForSwap())throw new Error("the agent is still working; wait for the current turn to finish, then try again");let o=Y(t.provider);if(t.line===void 0||o?.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which has no history to merge from \u2014 a sync needs a common base, and a copied directory has none. Land its work with \`/hydra workspace merge\` instead, or start a git-backed workspace if you need to track the source.`);let[i,a]=await Promise.all([o.currentState(t.sourceCwd),o.currentState(t.path)]);if(i===void 0||a===void 0)throw new Error("could not read the state of the source or the workspace");if(await o.contains(t.path,{state:i,within:a}))return{ok:!0,message:`Already up to date with ${P(t.sourceCwd)} (${i.slice(0,8)}).`};let d=await o.divergence(t.path,a,i),u=String(d?.behind??0),c=await o.integrate({into:t.path,from:i,message:`hydra: sync ${t.label} with the source`});if(!c.ok){let p=c.conflicts,f=await o.integrationInProgress(t.path);if(p.length===0&&!f){let g=await this.syncOverDirtyTree(t,{provider:o,before:a,sourceHead:i,incoming:u});if(g!==void 0)return g}let h=p.length>0?`
140
- ${p.map(g=>` ${g}`).join(`
141
- `)}`:` (${c.reason??"the integration failed"})`;return p.length===0?{ok:!1,message:`the source could not be merged into ${P(t.path)}; nothing changed.${h}
142
- `+(f?"A merge is already in progress there. Finish it \u2014 resolve, commit \u2014 then `/hydra workspace sync` again.":"Clear that in the workspace, then `/hydra workspace sync` again.")}:n.onConflict==="abort"?(await o.abortIntegration(t.path).catch(()=>{}),{ok:!1,message:`${p.length} file(s) conflict between the source and this workspace:${h}`}):{ok:!1,message:`Synced with conflicts. ${p.length} file(s) need resolving in ${P(t.path)}:${h}
143
- The merge is left in progress deliberately: fix the markers, commit, then \`/hydra workspace stop\`. To back it out instead: git -C ${t.path} merge --abort`}}let l=(await o.changedPathsBetween(t.path,a,c.snapshot)).length;return{ok:!0,message:`Synced ${P(t.path)} with ${P(t.sourceCwd)}: ${u} commit(s), ${l} file(s) changed. Your uncommitted work is untouched.`}}async syncOverDirtyTree(e,t){let{provider:n,before:r,sourceHead:o,incoming:i}=t;if(n?.capabilities().supports.captureWorkingState!==!0)return;let a=this.asWorkspace(e),d=await n.status(a).catch(()=>{});if(d===void 0||d.changedPaths.length===0)return;let u=await n.captureWorkingState(e.path,`hydra: work set aside to sync ${e.label}`).catch(()=>{});if(u===void 0)return;let c=Oi(e.label);if(await n.retainSnapshot(a,c,u).then(()=>n.resolveRetained(a,c)).catch(()=>{})===void 0)return;let p={clean:!1,snapshot:u,base:r},f=`git -C ${e.path} cherry-pick --no-commit ${c} # the snapshot's parent is ${r.slice(0,8)}, so this replays exactly your work`;if(!(await n.resetTo(e.path,r)).ok){let b=await Ke({source:e.path,capture:p,provider:n});return{ok:!1,message:`Could not clear ${P(e.path)} to merge into it, so nothing was synced. ${b?"Your uncommitted work is back in place.":`Your uncommitted work is at ${c}: ${f}`}`}}if(!(await n.integrate({into:e.path,from:o,message:`hydra: sync ${e.label} with the source`})).ok){await n.abortIntegration(e.path).catch(()=>{});let b=await Ke({source:e.path,capture:p,provider:n});return b&&await n.dropSnapshotRef(a,c).catch(()=>{}),{ok:!1,message:`The source's commits and this workspace's commits genuinely conflict, and that has to be resolved with a merge left in progress \u2014 which cannot happen while there is uncommitted work here, since the work has to be set aside for the merge to run at all.
144
- `+(b?`Your uncommitted work is back in place (unstaged) and nothing else changed. Commit it in ${P(e.path)}, then \`/hydra workspace sync\` again to resolve the conflict there.`:`Your uncommitted work could not be put back and is preserved at ${c}. Recover it with:
145
- ${f}`)}}let m=await Ke({source:e.path,capture:p,provider:n}),y=await n.currentState(e.path),k=y===void 0?0:(await n.changedPathsBetween(e.path,r,y)).length,w=`Synced ${P(e.path)} with ${P(e.sourceCwd)}: ${i} commit(s), ${k} file(s) changed.`;return m?(await n.dropSnapshotRef(a,c).catch(()=>{}),{ok:!0,message:`${w} Your uncommitted work was set aside for the merge and restored on top.`}):{ok:!1,message:`${w}
146
- Your uncommitted work touches the same lines as the commits that just arrived, so replaying it left conflict markers where they collide. The whole set is preserved at ${c} if you would rather start over:
147
- ${f}`}}async fastForwardBlocked(e){let n=this.asWorkspace(e).line;if(n===void 0)return"the workspace has no line of work to land from";let r=Y(e.provider);if(r===void 0)return;let o=await r.currentState(e.sourceCwd);if(o===void 0||await r.contains(e.sourceCwd,{state:o,within:n}))return;let i=await r.currentLineName(e.sourceCwd);return`${P(e.sourceCwd)} has moved on since this workspace was created (it is on ${i??"an unknown branch"}). \`/hydra workspace sync\` brings those commits in here and makes the landing possible again, or land it by hand with: git -C ${e.sourceCwd} merge ${n}`}async tearDownWorkspace(e,t,n){let r={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},o=await Mn(t.sourceCwd).catch(()=>({}));if(o.preRemove!==void 0){let a=await Tn(o.preRemove,{workspacePath:t.path,sourceCwd:t.sourceCwd,label:t.label,...n!==void 0?{sessionId:n}:{},...o.hookTimeoutSeconds!==void 0?{timeoutSeconds:o.hookTimeoutSeconds}:{}});a.ok||this.logger?.warn?.(`session workspace: preRemove failed for ${t.path}: ${a.reason??"unknown"}`)}for(let a of ji(t.label))await e.dropSnapshotRef(r,a).catch(()=>{});let i=await e.status(r).catch(()=>({clean:!1,changedPaths:["<unknown>"],hasRecordedWork:!1}));if(i.changedPaths.length>0){this.logger?.warn?.(`session workspace: keeping ${t.path} \u2014 it has ${i.changedPaths.length} uncommitted change(s) that removal would destroy. Remove it by hand once you have salvaged or discarded them.`);return}await e.removeWorkspace(r,{force:!0}).catch(a=>this.logger?.warn?.(`session workspace: could not remove ${t.path}: ${String(a)}`))}snapshotRefFor(e){return Bt(e).autosave}startRefFor(e){return Bt(e).start}baselineRefFor(e){return Bt(e).baseline}scheduleWorkspaceSnapshot(e){if(e.workspace===void 0){this.driftNoticed.delete(e.sessionId);return}if(this.snapshotInFlight.has(e.sessionId)){this.snapshotPending.add(e.sessionId);return}this.snapshotInFlight.add(e.sessionId),this.runWorkspaceSnapshot(e).catch(()=>{}).finally(()=>{this.snapshotInFlight.delete(e.sessionId),this.snapshotPending.delete(e.sessionId)&&this.scheduleWorkspaceSnapshot(e)})}async runWorkspaceSnapshot(e){let t=e.workspace;if(t===void 0)return;let n=Y(t.provider);if(n===void 0||!n.capabilities().supports.captureWorkingState)return;let r={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}};if(await this.noticeSourceDrift(e,t).catch(()=>{}),this.workspaceSnapshotsDisabled)return;let o=await n.status(r).catch(()=>{});if(o!==void 0&&o.changedPaths.length===0)return;let i=await n.captureWorkingState(t.path,`hydra: autosave ${e.sessionId}`);await n.retainSnapshot(r,this.snapshotRefFor(t.label),i)}async noticeSourceDrift(e,t){if(this.asWorkspace(t).line===void 0)return;let r=Y(t.provider);if(r===void 0||!r.capabilities().sharedHistory)return;let o=await r.currentState(t.sourceCwd);if(o===void 0||this.driftNoticed.get(e.sessionId)===o)return;let i=await r.currentState(t.path);if(i===void 0)return;if(await r.contains(t.path,{state:o,within:i})){this.driftNoticed.delete(e.sessionId);return}let d=(await r.divergence(t.path,i,o))?.behind??0;d<=0||(this.driftNoticed.set(e.sessionId,o),e.broadcastWorkspacePhase({phase:"drift",label:t.label,sourceCwd:t.sourceCwd,behind:d}),e.broadcastSyntheticText(`
148
- ${P(t.sourceCwd)} has moved on: ${d} commit(s) are there and not in this workspace. Landing is fast-forward-only, so \`/hydra workspace sync\` now is what keeps \`stop\` from refusing later.
149
- `))}async runWorkspaceAction(e,t,n,r){let o=this.get(e);if(o===void 0)throw new Error("session is not live");if(t==="status"){let a=o.workspace;if(a===void 0)return`Not isolated. Working directly in ${P(o.cwd)}.
150
- Use \`/hydra workspace start\` to move into an isolated workspace.`;let d=this.liveSessionsIn(a.path,o.sessionId).map(f=>He(f.sessionId)),u=a.line,c=[`Isolated in ${P(a.path)}`,` source: ${P(a.sourceCwd)}`,` provider: ${a.provider}${u!==void 0?` (${u})`:""}`];d.length>0&&c.push(` shared with: ${d.join(", ")}`);let p=await Y(a.provider)?.statusReport({path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.vcs!==void 0?{vcs:a.vcs}:{}}).catch(()=>{});for(let f of p??[])c.push(` ${f}`);return c.push(d.length>0?`\`stop\` behaves as \`detach\` while ${d.length===1?"that session is":"those sessions are"} still here; the work lands when the last one leaves.`:"Use `/hydra workspace stop` to merge and return, `discard` to throw the work away, `detach` to return and leave it here, or `clean` to wipe it and keep working here."),c.join(`
151
- `)}if(t==="start")return this.startWorkspace(o,n,{clean:r?.clean===!0});let i=o.workspace;if(i===void 0)throw new Error("this session is not in a workspace. Use `/hydra workspace start` first.");if(t==="sync")return(await this.syncWorkspaceFromSource(o,i,{onConflict:"keep"})).message;if(t==="clean")return await this.cleanWorkspace(o,i,{deep:r?.deep===!0});if(t==="merge"){o.broadcastWorkspacePhase({phase:"landing"});let a;try{a=await this.mergeWorkspaceIntoSource(i,o.sessionId)}catch(d){let u=d instanceof Error?d.message:String(d);throw o.broadcastWorkspacePhase({phase:"failed",error:u}),d}return o.broadcastWorkspacePhase({phase:"entered",cwd:o.cwd,sourceCwd:i.sourceCwd,label:i.label}),[`${a.merged}; still working in ${P(i.path)}.`,...a.warnings].join(`
152
- `)}if(t==="apply"){o.broadcastWorkspacePhase({phase:"applying"});let a;try{a=await this.applyWorkspaceToSource(i,o.sessionId)}catch(d){let u=d instanceof Error?d.message:String(d);throw o.broadcastWorkspacePhase({phase:"failed",error:u}),d}return o.broadcastWorkspacePhase({phase:"entered",cwd:o.cwd,sourceCwd:i.sourceCwd,label:i.label}),[a.applied,...a.warnings].join(`
153
- `)}if(t==="stop"){let a=this.liveSessionsIn(i.path,o.sessionId);if(a.length>0){o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"detached"});let u=a.map(p=>He(p.sessionId)).join(", "),c=[`Left ${P(i.path)} and returned to ${P(i.sourceCwd)}.`,`Nothing landed yet: ${u} still working there. It lands when the last session leaves.`],l=await this.fastForwardBlocked(i);return l!==void 0&&c.push(`WARNING: that merge will not fast-forward as things stand \u2014 ${l}`),c.join(`
154
- `)}o.broadcastWorkspacePhase({phase:"landing"});let d;try{d=await this.mergeWorkspaceIntoSource(i,o.sessionId)}catch(u){let c=u instanceof Error?u.message:String(u);throw o.broadcastWorkspacePhase({phase:"failed",error:c}),u}o.broadcastWorkspacePhase({phase:"returning"});try{await this.leaveWorkspace(o,i,{exit:"landed"})}catch(u){let c=u instanceof Error?u.message:String(u);throw new Error(`${d.merged}, but the session could not leave the workspace: ${c}`)}return[`${d.merged} and returned there; workspace removed.`,...d.warnings].join(`
155
- `)}if(t==="discard"){let a=this.liveSessionsIn(i.path,o.sessionId);if(a.length>0)throw new Error(`${P(i.path)} is shared with ${a.map(c=>He(c.sessionId)).join(", ")}, so its work is not yours alone to discard. Use \`/hydra workspace detach\` to leave it to them.`);o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"discarded"});let d=await this.retireAutosave(i),u=[`Discarded ${P(i.path)} and its branch ${i.line??"(none)"}; returned to ${P(i.sourceCwd)}.`];return d!==void 0&&u.push(`The last autosave is kept at ${d} if you want it back: git -C ${i.sourceCwd} checkout ${d}`),u.join(`
156
- `)}return o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"detached"}),[`Returned to ${P(i.sourceCwd)} WITHOUT merging.`,`The workspace is still at ${P(i.path)} and its branch ${i.line??"(none)"} is intact, so nothing is lost. Land it later with \`hydra workspace merge\`, or drop it with \`/hydra workspace discard\`.`].join(`
157
- `)}asWorkspace(e){return{path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.line!==void 0?{line:e.line}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}}}async retireAutosave(e){let t=Y(e.provider);if(t===void 0)return;let n=this.asWorkspace(e),r=this.snapshotRefFor(e.label),o=await t.resolveRetained(n,r).catch(()=>{});if(o===void 0)return;let i=Hi(e.label,o);return await t.retainSnapshot(n,i,o).then(()=>!0).catch(()=>!1)?(await t.dropSnapshotRef(n,r).catch(()=>{}),i):r}async cleanWorkspace(e,t,n){return await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let r=this.liveSessionsIn(t.path,e.sessionId);if(r.length>0)throw new Error(`${P(t.path)} is shared with ${r.map(k=>He(k.sessionId)).join(", ")}, and a clean would destroy their work too. Clean it from a session that has it to itself.`);if(!await e.isQuiescedForSwap())throw new Error("the agent is still working; wait for the current turn to finish, then try again");let o=Y(t.provider);if(o===void 0)throw new Error(`no provider "${t.provider}" available to clean this workspace`);if(t.snapshot===void 0||o.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which records no base state to return to, so there is nothing to clean back to. Use \`/hydra workspace discard\` to throw it away instead.`);let i=this.asWorkspace(t),a=t.snapshot,u=(await o.status(i).catch(()=>{}))?.changedPaths.length??0,l=(await o.divergence(t.path,a,"HEAD").catch(()=>{}))?.behind??0,p=await o.currentState(t.path)??"",f=await this.retireAutosave(t);e.broadcastWorkspacePhase({phase:"cleaning",label:t.label});let h=await o.resetTo(t.path,a,{purgeIgnored:n.deep});if(!h.ok)throw new Error(`could not return ${P(t.path)} to its base: ${h.reason??"unknown error"}. Nothing was changed.`);let g=n.deep?await this.applyWorkspaceSetup(t,e.sessionId):void 0;await o.retainSnapshot(i,this.startRefFor(t.label),t.snapshot).catch(()=>{});let m={...t,clean:!0};e.workspace=m,await this.mutateRecord(e.sessionId,{workspace:m}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:t.sourceCwd,label:t.label,...i.line!==void 0?{branch:i.line}:{}});let y=[`Cleaned ${P(t.path)} back to the state it was created in.`];if(u>0||l>0){let k=[];u>0&&k.push(`${u} uncommitted change(s)`),l>0&&k.push(`${l} commit(s)`),y.push(` discarded ${k.join(" and ")}`)}else y.push(" nothing to discard; it was already at its base");return g!==void 0&&y.push(` ${g}`),f!==void 0&&y.push(` last autosave kept at ${f}: git -C ${t.sourceCwd} checkout ${f}`),l>0&&p.length>0&&y.push(` discarded commits are still at ${p.slice(0,12)} (and in the reflog for ${t.line??"this branch"})`),y.push(`Your uncommitted work in ${P(t.sourceCwd)} was never touched by this.`),y.join(`
158
- `)})}async mergeWorkspaceIntoSource(e,t){let n=e.sourceCwd,r=e.line;if(r===void 0)throw new Error(`workspace ${e.label} has no line of work to land from`);if(!await this.dirExists(n))throw new Error(`source tree ${P(n)} no longer exists`);let i=Y(e.provider),a=this.asWorkspace(e),d=await gr({source:n,ws:a,startSnapshotRef:this.startRefFor(e.label),baselineRef:this.baselineRefFor(e.label),retainRef:pr(t),provider:i});if(i===void 0)throw new Error(`no provider "${e.provider}" available to land this workspace`);let u=await i.currentState(n);if(u===void 0)throw new Error(`could not read the state of ${P(n)}`);let c=await i.contains(n,{state:u,within:r}),l=[];if(!c){let S=this.get(t),x="";if(S!==void 0)try{let R=await this.syncWorkspaceFromSource(S,e,{onConflict:"abort"});R.ok?(l.push(`
159
- synced with the source first: ${R.message}`),c=await i.contains(n,{state:u,within:r})):x=`
160
- A sync was attempted first and could not complete: ${R.message}`}catch(R){x=`
161
- A sync was attempted first but was refused: ${R instanceof Error?R.message:String(R)}`}if(!c){let R=await i.currentLineName(n)??"the source";throw new Error(`cannot fast-forward ${R} in ${P(n)} to ${r}. The source has moved on since this workspace was created. The source is untouched.${x}
162
- `+(x.length>0?`Or land it by hand with: git -C ${n} merge ${r}`:`Resolve it in the workspace with \`/hydra workspace sync\` (which leaves the conflict there to fix), or land it by hand with: git -C ${n} merge ${r}`))}}let p=i!==void 0&&i.capabilities().supports.nestedTrees?await i.captureNested(e.path,await i.listNested(e.path)).catch(()=>[]):[],f,h=await i.status(a).catch(()=>{});if(h!==void 0&&h.changedPaths.length>0&&(f=await i.captureWorkingState(e.path,`hydra: uncommitted work in ${e.label}`).catch(()=>{}),f===void 0))throw new Error(`could not capture the uncommitted work in ${P(e.path)}; nothing was changed`);if(!d.clean&&!(await i.resetTo(n,u)).ok)throw new Error(`could not clear ${P(n)} for the merge; your work is preserved at ${d.retainedRef}. Nothing was merged.`);let g=await i.integrate({into:n,from:r,fastForwardOnly:!0});if(!g.ok)throw new Error(`merge failed: ${g.reason??"unknown error"}`);let m=!0;if(f!==void 0){let S=await i.captureDelta(n,g.snapshot,f);S!==void 0&&(m=(await i.applyDelta(n,S)).ok)}let y=await Ke({source:n,capture:d,provider:i});y&&await Ut({source:n,ws:a,capture:d,provider:i});let k={applied:[],failed:[]},w=i!==void 0&&i.capabilities().supports.nestedTrees?await i.integrateNested(n,e.path,p).catch(()=>k):k,b=await i.captureWorkingState(n,`hydra: source state after landing ${e.label}`).catch(()=>{});b!==void 0&&await i.retainSnapshot({...a,path:n},this.baselineRefFor(e.label),b).catch(()=>{});let v=[];m||v.push(` WARNING: the workspace's uncommitted changes could not be replayed; they remain reachable from ${r}.`),y||v.push(e.clean===!0?` WARNING: this workspace started clean, so your uncommitted work was never copied in. The whole of it is being replayed now and it overlaps what the agent changed. All of it is preserved at ${d.retainedRef}; recover with: git -C ${n} diff ${d.base} ${d.retainedRef}`:` WARNING: your own edits to ${P(n)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${d.retainedRef}; recover with: git -C ${n} diff ${d.base} ${d.retainedRef}`);for(let S of w.failed)v.push(` WARNING: nested tree ${S.path} was NOT reconciled: ${S.reason}. ${P(n)} now records a different state for it, so it will report it as modified until you resolve that.`);return{merged:`Merged ${r} into ${P(n)}${l.join("")}`,warnings:v}}async applyWorkspaceToSource(e,t){let n=e.sourceCwd;if(!await this.dirExists(n))throw new Error(`source tree ${P(n)} no longer exists`);let r=Y(e.provider);if(r===void 0)throw new Error(`no provider "${e.provider}" available to apply this workspace`);if(!r.capabilities().supports.captureWorkingState)throw new Error(`provider "${e.provider}" cannot snapshot a working tree, so there is no change set to apply. Use \`/hydra workspace stop\` to land this workspace instead.`);let o=this.asWorkspace(e);if((await r.status({...o,path:n}).catch(()=>{}))?.hasStagedWork===!0)throw new Error(`${P(n)} already has changes staged for its next commit, and \`apply\` delivers into that same index: the two sets would be indistinguishable, and unstaging one would unstage both. Commit or unstage them first, or use \`/hydra workspace merge\`, which lands the work as commits and does not touch the index.`);let a=await r.currentState(n);if(a===void 0)throw new Error(`could not read the state of ${P(n)}`);let d=e.line,u=d!==void 0&&await r.contains(n,{state:a,within:d}).catch(()=>!1),c=u?a:e.snapshot??"";if(c.length===0)throw new Error(`workspace ${e.label} has no recorded base to measure its changes against, so there is no way to tell its work apart from what the source already had`);let l=await gr({source:n,ws:o,startSnapshotRef:this.startRefFor(e.label),baselineRef:this.baselineRefFor(e.label),retainRef:pr(t),provider:r}),p=r.capabilities().supports.nestedTrees?(await r.listNested(e.path).catch(()=>[])).filter(w=>w.changedPaths.length>0||w.recorded!==void 0&&w.recorded!==w.actual):[],f=await r.captureWorkingState(e.path,`hydra: apply from ${e.label}`).catch(()=>{});if(f===void 0)throw new Error(`could not snapshot the work in ${P(e.path)}; nothing was changed`);let h=await r.captureDelta(n,c,f);if(h===void 0)throw new Error(`could not work out what ${e.label} changed; ${P(n)} was not touched`);if(h.trim().length===0)return await Ut({source:n,ws:o,capture:l,provider:r}),{applied:`Nothing to apply: ${e.label} holds no changes ${P(n)} does not already have.`,warnings:[]};if(!l.clean&&!(await r.resetTo(n,a)).ok)throw new Error(`could not clear ${P(n)} to apply onto; your work is preserved at ${l.retainedRef}. Nothing was applied.`);let g=await r.applyDelta(n,h,{stage:!0,tolerant:!u});if(!g.ok){await r.resetTo(n,a).catch(()=>{});let w=await Ke({source:n,capture:l,provider:r});throw w&&await Ut({source:n,ws:o,capture:l,provider:r}),new Error(`could not apply ${e.label} into ${P(n)}: ${g.reason??"the change set did not apply"}.`+(u?"":" The source has moved on since this workspace was created; `/hydra workspace sync` brings those commits in here, which is what lets the change set apply against them.")+(w?` ${P(n)} is as you left it.`:` Your uncommitted work there is preserved at ${l.retainedRef}.`))}let m=await Ke({source:n,capture:l,provider:r});m&&await Ut({source:n,ws:o,capture:l,provider:r});let y=await r.captureWorkingState(n,`hydra: source state after applying ${e.label}`).catch(()=>{});y!==void 0&&await r.retainSnapshot({...o,path:n},this.baselineRefFor(e.label),y).catch(()=>{});let k=[];g.alreadyPresent===!0&&k.push(` Nothing was staged: ${P(n)} already had every one of those changes.`),m||k.push(` WARNING: your own edits to ${P(n)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${l.retainedRef}; recover with: git -C ${n} diff ${l.base} ${l.retainedRef}`);for(let w of p)k.push(` WARNING: nested tree ${w.relPath} was NOT included: a change set can only move the pointer to it, not what is inside. Land it with \`/hydra workspace stop\`, or copy that work across by hand.`);return{applied:`Applied ${e.label} into ${P(n)} as staged changes; still working in ${P(e.path)}.
163
- Nothing was committed: review it with \`git -C ${n} diff --cached\` and commit it however you like. The workspace and its history are untouched.`,warnings:k}}async leaveWorkspace(e,t,n){let r=n.exit!=="detached",o=Y(t.provider),i={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},a=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:t.sourceCwd,workspace:void 0,historyLength:a.length,note:`Returned to the source tree at ${t.sourceCwd}`+(n.exit==="landed"?" after merging the workspace.":n.exit==="discarded"?" after discarding the workspace and its work.":" without merging."),...await this.recordSynopsisFor(e.sessionId),left:{path:t.path,removed:r}}),await this.mutateRecord(e.sessionId,{cwd:e.cwd},["workspace"]),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"left",cwd:e.cwd,sourceCwd:t.sourceCwd,integrated:n.exit==="landed"}),o!==void 0&&await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let d=this.liveSessionsIn(t.path,e.sessionId);if(d.length>0){this.logger?.info?.(`session workspace: ${e.sessionId} left ${t.path}; ${d.length} live session(s) remain, so it stays`);return}await this.reclaimAfterLastLeaver(o,i,t,e.sessionId,n)})}async reclaimAfterLastLeaver(e,t,n,r,o){await e.unlock(t).catch(()=>{});for(let i of[this.startRefFor(n.label),this.baselineRefFor(n.label)])await e.dropSnapshotRef(t,i).catch(()=>{});o.exit!=="detached"&&(o.exit==="landed"&&await e.dropSnapshotRef(t,this.snapshotRefFor(n.label)).catch(()=>{}),await e.removeWorkspace(t,{force:!0,discardLine:!0}).catch(()=>{}))}async joinDivergence(e,t,n){let[r,o]=await Promise.all([e.captureWorkingState(t,"hydra: source state at join").catch(()=>{}),e.captureWorkingState(n.path,"hydra: workspace state at join").catch(()=>{})]);if(r===void 0||o===void 0)return`could not compare ${P(t)} with ${P(n.path)}, so refusing to join a workspace that may not match your tree`;let i=await Promise.all([r,o].map(a=>e.contentId(t,a).catch(()=>{})));if(!(i[0]!==void 0&&i[0]===i[1]))return`${P(t)} and ${P(n.path)} have diverged, and joining does not carry work across \u2014 whichever side you are not in would be left behind. Land or stash one of them first: \`git -C ${t} stash\` if the difference is yours, or \`/hydra workspace merge\` from the session already in there if it is theirs.`}liveSessionsWithLabel(e,t){let n=[];for(let r of this.sessions.values()){let o=r.workspace;o===void 0||o.sourceCwd!==e||(o.label===t||o.requestedLabel===t)&&n.push(r)}return n}async joinWorkspace(e,t,n,r){let o=Y(n.provider);if(o===void 0)throw new Error(`no provider "${n.provider}" to join that workspace with`);if(o.capabilities().supports.captureWorkingState){let i=await this.joinDivergence(o,r,n);if(i!==void 0)throw new Error(i)}return await this.enqueueKeyed(this.workspaceQueues,n.path,async()=>{if(this.sessions.get(t.sessionId)?.workspace?.path!==n.path)throw new Error(`${P(n.path)} was released while joining it; run the command again`);e.broadcastWorkspacePhase({phase:"swapping"});let i=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:n.path,workspace:{path:n.path,sourceCwd:n.sourceCwd,label:n.label,...n.requestedLabel!==void 0?{requestedLabel:n.requestedLabel}:{},provider:n.provider,...n.snapshot!==void 0?{snapshot:n.snapshot}:{},...n.line!==void 0?{line:n.line}:{},...n.vcs!==void 0?{vcs:{...n.vcs}}:{}},historyLength:i.length,note:`Continuing in an isolated workspace at ${n.path}, derived from ${r}, shared with another session.`,...await this.recordSynopsisFor(e.sessionId)}),await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache();let a=n.line;e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:n.sourceCwd,label:n.label,...a!==void 0?{branch:a}:{}});let d=this.liveSessionsIn(n.path,e.sessionId).map(c=>He(c.sessionId)),u=[`Joined workspace ${P(n.path)}`,` source: ${P(n.sourceCwd)}`];return a!==void 0&&u.push(` branch: ${a}`),u.push(` shared with: ${d.join(", ")}`),u.push(" your edits will interleave with that session's"),u.push("Use `/hydra workspace stop` to leave; the work lands when the last session leaves."),u.join(`
164
- `)})}async startWorkspace(e,t,n){if(e.workspace!==void 0)throw new Error(`already isolated in ${P(e.workspace.path)}. Use \`/hydra workspace stop\` to merge and return first, or \`detach\` to leave it behind.`);let r=e.cwd,o=Y();if(o===void 0)throw new Error("no workspace provider available");if(!await e.isQuiescedForSwap())throw new Error("the agent is still working; wait for the current turn to finish, then try again");let i=o.capabilities();if(t!==void 0){let v=this.liveSessionsWithLabel(r,t)[0];if(v!==void 0&&v.workspace!==void 0)return await this.joinWorkspace(e,v,v.workspace,r)}let a,d=[],u=!1,c=!1,l=[],p=[],f=n?.clean===!0;if(i.supports.captureWorkingState){let v=await o.status({path:r,sourceCwd:r,label:"source",provider:o.kind}).catch(()=>{});c=v!==void 0;let S=i.supports.nestedTrees&&v!==void 0&&v.changedPaths.length>0?await o.listNested(r).catch(()=>[]):[];if(v!==void 0&&v.changedPaths.length>0&&f)l=dr(v.changedPaths,S);else if(v!==void 0&&v.changedPaths.length>0&&(d=dr(v.changedPaths,S),p=await o.captureNested(r,S).catch(()=>[]),u=v.hasStagedWork===!0,a=await o.captureWorkingState(r,"hydra: work carried into workspace").catch(()=>{}),a===void 0))throw new Error("could not snapshot your uncommitted work, so refusing to move it. Commit or stash first.")}e.broadcastWorkspacePhase({phase:"provisioning"});let h=await o.createWorkspace({sourceCwd:r,label:t??`s-${e.sessionId.slice(-8)}`});if(!h.ok)throw e.broadcastWorkspacePhase({phase:"failed",error:h.reason}),new Error(h.reason);let g=h.workspace,m=this.startRefFor(g.label),y,k=!1,w=[];try{i.locking&&await o.lock(g,`session ${e.sessionId}`).catch(()=>{});let v=a??g.snapshot;if(v===void 0)throw new Error(`provider "${g.provider}" gave the workspace no base to anchor landing against`);await o.retainSnapshot(g,m,v),e.broadcastWorkspacePhase({phase:"setup"}),k=a!==void 0?await this.copyCarriedWork(g,a,r):!0;let S=await this.materializeNestedTrees(g);if(p.length>0){let R=await o.reproduceNested(g.path,r,p).catch(M=>({applied:[],failed:p.map(H=>({path:H.relPath,reason:M instanceof Error?M.message:String(M)}))}));R.failed.length>0&&(k=!1,w=R.failed)}y=await this.applyWorkspaceSetup(g,e.sessionId),S!==void 0&&(y=y===void 0?S:`${S}; ${y}`),e.broadcastWorkspacePhase({phase:"swapping"});let x=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:g.path,workspace:{path:g.path,sourceCwd:g.sourceCwd,label:g.label,...t!==void 0&&t!==g.label?{requestedLabel:t}:{},provider:g.provider,...g.snapshot!==void 0?{snapshot:g.snapshot}:{},...g.line!==void 0?{line:g.line}:{},...g.vcs!==void 0?{vcs:{...g.vcs}}:{},...a===void 0?{clean:!0}:{}},historyLength:x.length,note:`Continuing in an isolated workspace at ${g.path}, derived from ${r}.`,...await this.recordSynopsisFor(e.sessionId)})}catch(v){let S=await this.unwindStartWorkspace({provider:o,ws:g,startRef:m,carried:a}),x=v instanceof Error?v.message:String(v);throw e.broadcastWorkspacePhase({phase:"failed",error:x}),new Error(S===void 0?x:`${x}
165
- ${S}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:g.sourceCwd,label:g.label,...g.line!==void 0?{branch:g.line}:{}});let b=[`Moved into workspace ${P(g.path)}`,` source: ${P(r)}`];if(g.line!==void 0&&b.push(` branch: ${g.line}`),t!==void 0&&t!==g.label&&b.push(` note: "${t}" was already taken by a surviving branch, so this is "${g.label}"`),a!==void 0){b.push(k?` carried ${d.length} uncommitted file(s) in; the source tree is untouched:`:` WARNING: could not copy ${d.length} uncommitted file(s); the workspace starts from HEAD. They are untouched in the source tree:`);for(let v of Ge(d))b.push(` ${v}`);k&&u&&b.push(" staging did not come along; everything above is unstaged here");for(let v of w)b.push(` nested tree ${v.path}: ${v.reason}`)}else if(l.length>0){b.push(` started clean: ${l.length} uncommitted file(s) stayed in the source and did NOT come along:`);for(let v of Ge(l))b.push(` ${v}`)}else c&&b.push(" source tree was clean; nothing carried in");return y!==void 0&&b.push(` ${y}`),b.push("Use `/hydra workspace stop` to merge back and return."),b.join(`
166
- `)}async copyCarriedWork(e,t,n){let r=await this.patchFromSnapshot(n,t,e.provider);if(r===void 0)return!1;if(r.length===0)return!0;let o=Y(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,r)).ok}async patchFromSnapshot(e,t,n){let r=Y(n);if(r===void 0)return;let o=await r.currentState(e);if(o!==void 0)return await r.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:n,startRef:r,carried:o}=e;await t.unlock(n).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(n,r).catch(()=>{}),await t.removeWorkspace(n,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let n=Y(e.provider);if(n?.capabilities().supports.nestedTrees!==!0)return;let r=await n.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:n.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return r.ok?r.count>0?`populated ${r.count} nested tree(s)`:void 0:`nested trees FAILED: ${r.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let n=await Mn(e.sourceCwd).catch(()=>({})),r=[];if(n.carry!==void 0&&n.carry.length>0){let o=await hr(e.sourceCwd,e.path,n.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&r.push(`carried ${o.copied.length} config file(s)`)}if(n.postCreate!==void 0){let o=await Tn(n.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...n.hookTimeoutSeconds!==void 0?{timeoutSeconds:n.hookTimeoutSeconds}:{}});r.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return r.length>0?r.join("; "):void 0}async deriveForkWorkspace(e,t){let n=Y(e.provider);if(n===void 0)return;let r=n.capabilities(),o=r.sharedHistory?await n.currentState(e.path)??"":"",i=await n.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&r.supports.captureWorkingState){let d=await n.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,n,r,o){let i=Y(o);if(i===void 0)return!1;let a=await i.captureDelta(e,n,r).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=Y(e.provider);if(t===void 0)return;let n={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(n).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let r=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(r.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${r.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:r.workspace.path,sourceCwd:r.workspace.sourceCwd,label:r.workspace.label,provider:r.workspace.provider,...r.workspace.snapshot!==void 0?{snapshot:r.workspace.snapshot}:{},...r.workspace.vcs!==void 0?{vcs:{...r.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let f=new Error(`agent ${e} not found in registry`);throw f.code=C.AgentNotInstalled,f}let n=await ye(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:ga.homedir(),plan:n}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}})}catch(f){throw await r.kill().catch(()=>{}),Ve(f,r)}if(r.authMethods=Jt(o.authMethods),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(f){throw await r.kill().catch(()=>{}),f}await r.kill().catch(()=>{});let d=new Set;for(let f of this.sessions.values())d.add(`${f.agentId}::${f.upstreamSessionId}`);let u=await this.store.list().catch(()=>[]);for(let f of u){d.add(`${f.agentId}::${f.upstreamSessionId}`);for(let h of f.upstreamGenerations??[])d.add(`${h.agentId}::${h.upstreamSessionId}`)}let c=A.sessionsDir(),l=[],p=0;for(let f of a){let h=`${e}::${f.sessionId}`;if(d.has(h)){p+=1;continue}if(lf(f.cwd,c)){p+=1;continue}let g=await this.tombstones.read(e,f.sessionId).catch(()=>{});if(g){if(!Di(g,f.updatedAt)){p+=1;continue}await this.tombstones.remove(e,f.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${f.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}d.add(h);let m=`${Me}${It()}`,y=new Date().toISOString(),k=f.updatedAt??y,w={sessionId:m,lineageId:Dt(),upstreamSessionId:f.sessionId,agentId:e,cwd:f.cwd,pendingHistorySync:!0,interactive:!0,createdAt:k,updatedAt:k};f.title!==void 0&&(w.title=f.title);let b=ir(w);await this.store.write(b),l.push({version:1,...b})}return{synced:l,skipped:p}}async collectAgentSessions(e){let t=[],n,r=new Set;for(let o=0;o<100;o+=1){let i={};n!==void 0&&(i.cursor=n);let a=await e.connection.request("session/list",i),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),n=a.nextCursor}return t}async applySeedModel(e,t,n,r,o){try{let{verb:i}=await Je({request:(a,d)=>e.connection.request(a,d),sessionId:t,modelId:n,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${r}: ${i} 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=C.AgentNotInstalled,i}let n=await ye(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=an(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:n,...r?{extraEnv:r}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}}),a=i.agentCapabilities;o.authMethods=Jt(i.authMethods);let d=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),u=d.sessionId;if(typeof u!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=Ir(d),l=Cr(d),p=ct(d),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let m=gt(f,l),y=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(o,u,f,y,p)&&(c=f);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(o,u,m.modelId,`${y} resolved to ${JSON.stringify(m.modelId)}`,p))&&(c=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${y} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let k=l.map(w=>w.modelId).join(", ");this.logger?.warn(`${y} not in agent's availableModels ([${k}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let h=xr(d),g=Rr(d);return{agent:o,upstreamSessionId:u,agentMeta:d._meta,agentCapabilities:a,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:h.length>0?h:void 0,initialMode:g,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Ve(fa(i,o,e.agentId,{command:n.command,args:n.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let n=await this.registry.getAgent(t.agentId);if(!n){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=C.AgentNotInstalled,a}let r=await ye(n,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=an(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}}),d=a.agentCapabilities;i.authMethods=Jt(a.authMethods);let u=ua(t.agentId,void 0),c=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...u&&{_meta:u}}),l=Ir(c),p=Ar(Cr(c)),f=xr(c),h=Rr(c);return{agent:i,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:d,initialModel:l,initialModels:p,initialModes:f.length>0?f:void 0,initialMode:h,modelVerb:ct(c)}}catch(a){throw await i.kill().catch(()=>{}),Ve(fa(a,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 n=await this.store.read(e);if(!n)throw new Error("session record not found");let r=n.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=n.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let n=this.pendingAuthAgents.get(e);if(n&&n.isAlive())return n;let r=await this.registry.getAgent(e);if(!r){let d=new Error(`agent ${e} not found in registry`);throw d.code=C.AgentNotInstalled,d}let o=await ye(r,[],{npmRegistry:this.npmRegistry}),i=t??de(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}});a.authMethods=Jt(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ve(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 n=new Error(`agent ${e} not found in registry`);throw n.code=C.AgentNotInstalled,n}return ye(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.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let r=At({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...r!==void 0?{interactive:r}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let n=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===n&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,n);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:n,retiredCost:r})=>{this.persistAgentChange(e.sessionId,t,n,r).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:ha(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(n=>({name:n.name,...n.description!==void 0?{description:n.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(n=>({id:n.id,...n.name!==void 0?{name:n.name}:{},...n.description!==void 0?{description:n.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(n=>({modelId:n.modelId,...n.name!==void 0?{name:n.name}:{},...n.description!==void 0?{description:n.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),n=ff(e,t);await this.store.write(n)}).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,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return Tt(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let n=t.title;return n||(n=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:n,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:pf(t.currentUsage),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,workspace:t.workspace,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 n=this.sessions.get(e);n&&(n.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let n={...t};delete n.pendingHistorySync,await this.store.write(n)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let n of t){let r=n.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=mt(r.update.prompt),i=Xs(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let n=t.agent.agentId,r=t.agent.version,o=e.get(n);o||(o=new Set,e.set(n,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Me))return;let t=Me+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let n=new Error(`session ${e} not found`);throw n.code=C.SessionNotFound,n}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,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,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Vt(t.sessionId),d=At({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,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let n=await this.store.read(e).catch(()=>{});if(!n)return;let r=await Vt(n.sessionId),o=At(n,r.hasContent),i=r.mtime??n.updatedAt;return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:zt(n.currentUsage),importedFromMachine:n.importedFromMachine,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:o,priority:n.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,n=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>n)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:n+s.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],n=new Set,r=c=>e.includeNonInteractive?!0:c===!0,o=[...this.sessions.values()].filter(c=>ca(e.cwd,c));if(e.status==="cold")for(let c of o)n.add(c.sessionId);let i=e.status==="cold"?[]:await Promise.all(o.map(c=>Vt(c.sessionId)));for(let c=0;c<i.length;c+=1){let l=o[c],p=i[c];n.add(l.sessionId);let f=At({interactive:l.interactive,...l.originatingClient?{originatingClient:l.originatingClient}:{}},p.hasContent);if(!r(f))continue;let h=p.mtime??new Date(l.updatedAt).toISOString();t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,workspace:l.workspace,workspaceError:l.workspaceError,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:h,attachedClients:l.attachedCount,status:"warm",agentPid:l.agentPid,busy:l.turnStartedAt!==void 0,armedTasks:l.armedBackgroundTasks.length,...l.armedSince!==void 0?{armedSince:l.armedSince}:{},awaitingInput:l.awaitingInput,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}if(e.status==="warm")return t;let d=(await this.store.list().catch(c=>{throw this.logger?.warn(`session list: store.list() failed: ${c?.message??String(c)}`),c})).filter(c=>!n.has(c.sessionId)&&ca(e.cwd,c)),u=await Promise.all(d.map(c=>Vt(c.sessionId)));for(let c=0;c<d.length;c+=1){let l=d[c],p=u[c],f=At(l,p.hasContent);if(!r(f))continue;let h=p.mtime??l.updatedAt;t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,workspace:l.workspace,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:zt(l.currentUsage),importedFromMachine:l.importedFromMachine,importedFromUpstreamSessionId:l.importedFromUpstreamSessionId,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}return t.sort((c,l)=>c.updatedAt<l.updatedAt?1:-1),t}async exportBundle(e,t={}){let n=await this.store.read(e);if(!n)return;let r;if(n.lineageId)r=n;else{let u=Dt(),c={...n,lineageId:u};await this.enqueueMetaWrite(e,async()=>{let l=await this.store.read(e);l&&(l.lineageId||await this.store.write({...l,lineageId:u}))}).catch(()=>{}),r=c}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await pa(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let d={};for(let u of ta(i)){let c=await go(e,u);c&&(d[u]=c.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let n=await this.store.findByLineageId(e.session.lineageId);if(n){if(!t.replace){let i=new Error(`bundle already imported as ${n.sessionId}`);throw i.code=C.BundleAlreadyImported,i.existingSessionId=n.sessionId,i}let o=this.sessions.get(n.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:n.sessionId,bundle:e,preservedCreatedAt:n.createdAt,cwd:t.cwd}),{sessionId:n.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Me}${It()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let n=await this.store.read(e);if(!n){let v=new Error(`source session not found: ${e}`);throw v.code=C.SessionNotFound,v}let r=t.agentId??n.agentId,o=r!==n.agentId;if(o&&!await this.registry.getAgent(r)){let S=new Error(`agent ${r} not found in registry`);throw S.code=C.AgentNotInstalled,S}let i=await this.histories.load(e).catch(()=>[]),a=i,d,u=t.mode??"synthesis",c,l,p,f=12e4;if(u==="verbatim")if(t.forkAt!==void 0){let v=bn(i,t.forkAt);if(v<0){let S=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw S.code=C.InvalidParams,S}d=t.forkAt,a=i.slice(0,v+1)}else{let v=hf(i);v?(d=v.messageId,a=i.slice(0,v.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let S=bn(i,t.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw x.code=C.InvalidParams,x}d=t.forkAt,a=i.slice(0,S+1)}else d="",a=i;let v=await this.registry.getAgent(r);if(!v){let S=new Error(`agent ${r} not found in registry`);throw S.code=C.AgentNotInstalled,S}p=v,l=n.currentModel,c="running"}let h=await pa(e),g=u==="synthesis",m={...n,lineageId:Dt(),agentId:r,interactive:!1,...c!==void 0?{forkSynthesisState:c}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=qt({record:m,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:ie,machine:$t()}),k=`${Me}${It()}`,w=t.cwd,b;if(t.cwd===void 0&&n.workspace!==void 0){let v=await this.deriveForkWorkspace(n.workspace,`${n.workspace.label}-fork-${k.slice(-6)}`);v!==void 0?(b=v,w=v.path):(w=n.workspace.sourceCwd,this.logger?.warn?.(`fork ${k}: could not derive an isolated workspace from ${n.workspace.path}; running unisolated in ${w}`))}return await this.writeImportedRecord({sessionId:k,bundle:y,cwd:w,...b!==void 0?{workspace:b}:{},forkedFromSessionId:e,forkedFromMessageId:d,...c!==void 0?{forkSynthesisState:c}:{}}),g&&(async()=>{try{let v=await ye(p,[],{npmRegistry:this.npmRegistry}),S=await Nn({agentId:r,cwd:t.cwd??A.sessionDir(e),plan:v,history:a,modelId:l,sessionId:e,logger:this.logger,timeoutMs:f});S&&S.synopsis?await this.mutateRecord(k,{synopsis:S.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(k,{},["forkSynthesisState"]))}catch(v){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${v.message}`);try{await this.mutateRecord(k,{},["forkSynthesisState"])}catch(S){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${S.message}`)}}})(),{sessionId:k,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await ho(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Ye.utimes(A.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ia(A.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let n=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,workspace:e.workspace,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??n,updatedAt:e.bundle.session.updatedAt})})}async tombstoneAllGenerations(e,t,n){let r=await this.store.read(e).catch(()=>{}),o=new Map;for(let a of r?.upstreamGenerations??[])a.upstreamSessionId&&o.set(`${a.agentId}::${a.upstreamSessionId}`,{agentId:a.agentId,upstreamSessionId:a.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString();for(let a of o.values())await this.tombstones.add({agentId:a.agentId,upstreamSessionId:a.upstreamSessionId,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:n,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let r=await Vt(e),o=At(n,r.hasContent);await this.tombstoneAllGenerations(e,{agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,...n.title!==void 0?{title:n.title}:{},...o!==void 0?{interactive:o}:{}},t)}return n.workspace!==void 0&&await this.releaseWorkspace(n.workspace,e).catch(()=>{}),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 clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let n=t.workspace?.sourceCwd;return await this.mutateRecord(e,n!==void 0?{cwd:n}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let n=await this.store.read(e).catch(()=>{});return n?n.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let n=this.get(e);if(n)return n.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 n=this.get(e);return n?(await n.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,n){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:n})}async persistAgentChange(e,t,n,r){await this.mutateRecord(e,{agentId:t,upstreamSessionId:n},void 0,o=>({upstreamGenerations:ma(o,t,n,void 0,r)}))}async persistSnapshot(e,t){let n={};t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentMode!==void 0&&(n.currentMode=t.currentMode),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(n.agentCommands=t.agentCommands),t.agentModes!==void 0&&(n.agentModes=t.agentModes),t.agentModels!==void 0&&(n.agentModels=t.agentModels),t.interactive!==void 0&&(n.interactive=t.interactive),t.cwd!==void 0&&(n.cwd=t.cwd),await this.mutateRecord(e,n)}async mutateRecord(e,t,n=[],r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...r?r(o):{},updatedAt:new Date().toISOString()};for(let a of n)delete i[a];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,n){return(await this.getExtensionState(e,t))[n]}async setExtensionStateKey(e,t,n,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[n]:r},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>s.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${s.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let u={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(u)})}async deleteExtensionStateKey(e,t,n){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(n in i))return;delete i[n],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,n){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(n),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let n=[];for(let r of this.sessions.values())r.sessionId!==t&&r.workspace?.path===e&&n.push(r);return n}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),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 n=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=${n} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,n)}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,n){let r=this.get(e);if(r){if(t){let o=n.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(n)}}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 n of e){let r=n.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(n.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let n of t){let r=n.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${n.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${n.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(n.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let n=t.pendingAgentSwap;if(n)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=${n} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,n)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${n} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:n}))}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 n=await li(t.sessionId).catch(()=>[]);if(n.length===0)continue;let r=Date.now(),o=n.filter(d=>r-d.enqueuedAt<da),i=n.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${da/1e3}s)`),await Ot(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await Ot(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function lf(s,e){if(typeof s!="string"||s.length===0)return!1;let t=Qt.resolve(s),n=Qt.resolve(e);return t===n||t.startsWith(n+Qt.sep)}function ca(s,e){if(s===void 0||s.length===0)return!0;let t=Sr(s);if(Sr(e.cwd)===t)return!0;let n=e.workspace?.sourceCwd;return n!==void 0&&Sr(n)===t}function Sr(s){return s.length>1&&s.endsWith("/")?s.replace(/\/+$/,""):s}function ff(s,e){let n=(s.mergedAvailableCommands().length>0?s.agentOnlyAdvertisedCommands().map(c=>c.description!==void 0?{name:c.name,description:c.description}:{name:c.name}):void 0)??e?.agentCommands,r=s.availableModes(),i=(r.length>0?r.map(c=>{let l={id:c.id};return c.name!==void 0&&(l.name=c.name),c.description!==void 0&&(l.description=c.description),l}):void 0)??e?.agentModes,a=s.availableModels(),u=(a.length>0?a.map(c=>{let l={modelId:c.modelId};return c.name!==void 0&&(l.name=c.name),c.description!==void 0&&(l.description=c.description),l}):void 0)??e?.agentModels;return ir({sessionId:s.sessionId,lineageId:e?.lineageId??Dt(),upstreamSessionId:s.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:s.agentId,cwd:s.cwd,title:s.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:s.agentArgs,currentModel:s.currentModel??e?.currentModel,currentMode:s.currentMode??e?.currentMode,currentUsage:ha(s.persistableUsage)??e?.currentUsage,agentCommands:n,agentModes:i,agentModels:u,parentSessionId:s.parentSessionId??e?.parentSessionId,forkedFromSessionId:s.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:s.originatingClient??e?.originatingClient,interactive:s.interactive??e?.interactive,priority:s.priority??e?.priority,forwardedEnv:s.forwardedEnv??e?.forwardedEnv,workspace:s.workspace,attentionFlags:s.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?ma(e,s.agentId,s.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(s.createdAt).toISOString()})}function ha(s){if(!s)return;let e={};return s.used!==void 0&&(e.used=s.used),s.size!==void 0&&(e.size=s.size),s.costAmount!==void 0&&(e.costAmount=s.costAmount),s.costCurrency!==void 0&&(e.costCurrency=s.costCurrency),s.cumulativeCost!==void 0&&(e.cumulativeCost=s.cumulativeCost),Object.keys(e).length>0?e:void 0}function pf(s){return s?{...s}:void 0}function ua(s,e){if(e&&s==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ln(s,e){let t=e.fromObject(s);if(t!==void 0)return t;let n=s[e.nestedKey];if(n&&typeof n=="object"&&!Array.isArray(n)){let i=e.fromObject(n);if(i!==void 0)return i}let r=s._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=gf(s,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Ir(s){return Ln(s,{nestedKey:"models",configId:"model",fromObject:e=>$e(e.currentModelId)??$e(e.currentModel)??$e(e.modelId)??$e(e.model),fromConfig:e=>$e(e.currentValue)})}function Ve(s,e){if(!s||typeof s!="object")return s;let t=s;if(t.code!==C.AuthRequired)return s;let n=u=>!!u&&typeof u=="object"&&!Array.isArray(u),r=n(t.data)?t.data:{},o=n(r._meta)?r._meta:{},i=n(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=C.AuthRequired,d.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function la(s){return/^[A-Za-z0-9_\-./=:@]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`}function fa(s,e,t,n){if(s&&typeof s=="object"&&s.code===C.AuthRequired)return s;let r=s instanceof Error?s.message:String(s),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=n?`to reproduce: (cd ${la(n.cwd)} && ${[n.command,...n.args].map(la).join(" ")})`:"";if(!i&&!a)return s;let d=[o?r:`agent ${t} failed to start: ${r}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let u=new Error(d.join(`
167
- `));if(s&&typeof s=="object"){let c=s;typeof c.code=="number"&&(u.code=c.code),c.data!==void 0&&(u.data=c.data)}return u}function Jt(s){if(!Array.isArray(s))return;let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string")continue;let r=typeof n.description=="string"?n.description:"",o=n.type==="agent"||n.type==="terminal"?n.type:void 0,i=typeof n.name=="string"?n.name:void 0,a=n._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:n.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...d&&{_meta:d}})}return e.length>0?e:void 0}function $e(s){if(typeof s!="string")return;let e=s.trim();return e.length>0?e:void 0}function gf(s,e){let t=s.configOptions;if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;if(r.id===e)return r}}function Ar(s){return s.length>0?s:void 0}function Cr(s){return Ln(s,{nestedKey:"models",configId:"model",fromObject:e=>{let t=yt(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=yt(e.options);return t.length>0?t:void 0}})??[]}function xr(s){return Ln(s,{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 Rr(s){return Ln(s,{nestedKey:"modes",configId:"mode",fromObject:e=>$e(e.currentModeId)??$e(e.currentMode)??$e(e.modeId)??$e(e.mode),fromConfig:e=>$e(e.currentValue)})}function hf(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(!t||t.method!=="session/update")continue;let n=t.params?.update;if(n?.sessionUpdate==="turn_complete"&&!(typeof n.messageId!="string"||n.messageId.length===0))return{index:e,messageId:n.messageId}}}async function pa(s){try{let e=await Ye.readFile(A.tuiHistoryFile(s),"utf8"),t=[];for(let n of e.split(`
168
- `))if(n.length!==0)try{let r=JSON.parse(n);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}function ma(s,e,t,n=new Date().toISOString(),r){let o=s.upstreamGenerations&&s.upstreamGenerations.length>0?[...s.upstreamGenerations]:s.upstreamSessionId?[{upstreamSessionId:s.upstreamSessionId,agentId:s.agentId}]:[],i=o[o.length-1];if(i&&i.upstreamSessionId===t){if(r!==void 0&&o.length>=2){let a=o[o.length-2];a&&a.cost===void 0&&(o[o.length-2]={...a,cost:r})}return o}return i&&i.endedAt===void 0&&(o[o.length-1]={...i,endedAt:n,...r!==void 0?{cost:r}:{}}),o.push({upstreamSessionId:t,agentId:e,startedAt:n}),o}async function Vt(s){try{let e=await Ye.stat(A.historyFile(s));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function At(s,e){return s.interactive!==void 0?s.interactive:s.originatingClient?.name===Fn?!1:e?!0:void 0}import{spawn as mf}from"child_process";import*as Un from"fs";import*as Le from"fs/promises";import*as Wn from"path";import yf from"pino-roll";var Bn=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,n){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${n}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${n}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var wf=1e3,kf=6e4,Er=3e3,Ct=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,n,r={}){this.adapter=t,this.context=n,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??wf,this.restartCapMs=r.restartCapMs??kf;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let n=this.entries.get(e);n&&(n.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Le.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 n=t.child;if(n){try{n.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(n.exitCode!==null||n.signalCode!==null){r();return}let o=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}r()},Er);n.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw Gt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Gt(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 Gt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let n=t.child;return n?(await this.terminate(t,n),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 Gt(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(n=>{t.failureReason=`spawn: ${n.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw Gt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let n=t.child;n&&await this.terminate(t,n);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let n=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Er);typeof r.unref=="function"&&r.unref();try{await n}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 Bn(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Le.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 n=this.adapter.paths.pidFile(t.name),r;try{let o=await Le.readFile(n,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&Pr(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+Er;for(;Date.now()<o&&Pr(r);)await new Promise(i=>setTimeout(i,50));if(Pr(r))try{process.kill(r,"SIGKILL")}catch{}}await Le.unlink(n).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let n=this.context;if(!n)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Wn.dirname(this.adapter.paths.logFile(r.name)),a;try{await Le.mkdir(i,{recursive:!0}),a=await yf({file:Wn.join(i,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",m=>{e.failureReason=`log stream: ${m.message}`})}catch(m){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${m.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})
169
- `);let d=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??n.serviceToken;e.processToken=d,e.version=void 0;let u={...dn(),HYDRA_ACP_DAEMON_URL:n.daemonUrl,HYDRA_ACP_DAEMON_HOST:n.daemonHost,HYDRA_ACP_DAEMON_PORT:String(n.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:n.daemonWsUrl,HYDRA_ACP_HOME:n.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[c,...l]=o;if(c===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
170
- `),a.end();return}let p=de(c),f=[...l,...r.args].map(de),h;try{h=mf(p,f,{env:u,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){a.write(`[hydra-acp] failed to spawn ${r.name}: ${m.message}
171
- `),a.end(),this.scheduleRestart(e,t);return}let g=m=>{try{a.write(typeof m=="string"?m:m.toString())}catch{}};if(h.stdout?.on("data",g),h.stderr?.on("data",g),typeof h.pid=="number")try{Un.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
172
- `,{encoding:"utf8",mode:384})}catch(m){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${m.message}
173
- `)}e.child=h,e.logStream=a,e.pid=typeof h.pid=="number"?h.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,h.on("error",m=>{a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${m.message}
174
- `)}),h.on("exit",(m,y)=>{try{Un.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${y??"null"}
175
- `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof m=="number"?m:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let k=e.exitWaiters.splice(0);for(let b of k)b();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let w=e.breaker.recordExit(m,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}
176
- `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let n=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}`})},n),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Pr(s){try{return process.kill(s,0),!0}catch{return!1}}function Gt(s,e){return s.code=e,s}K();var bf={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:A.extensionsDir,logFile:A.extensionLogFile,pidFile:A.extensionPidFile}},qn=class extends Ct{constructor(e,t,n={}){super(e,bf,t,n)}};K();var vf={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:A.transformersDir,logFile:A.transformerLogFile,pidFile:A.transformerPidFile}},zn=class extends Ct{connected=new Map;constructor(e,t,n={}){super(e,vf,t,n)}registerConnection(e,t,n){this.connected.set(e,{name:e,connection:t,intercepts:new Set(n)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let n of e){let r=this.connected.get(n);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let n of this.connected.values())n.intercepts.has(e)&&t.push(n);return t}};var Jn=class{entries=new Map;changeHandlers=[];register(e,t,n){this.entries.set(e,{connection:t,commands:[...n]}),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,n]of this.entries)for(let r of n.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{}}};K();K();import*as Mr from"fs/promises";async function ya(s){await Mr.writeFile(A.pidFile(),JSON.stringify(s)+`
140
+ `:"")}import{z as q}from"zod";var lp=q.object({method:q.string(),params:q.unknown(),recordedAt:q.number()}),pp=q.object({sessionId:q.string(),lineageId:q.string(),upstreamSessionId:q.string().optional(),agentId:q.string(),cwd:q.string(),title:q.string().optional(),synopsis:jt.optional(),summarizedThroughEntry:q.number().int().nonnegative().optional(),currentModel:q.string().optional(),currentMode:q.string().optional(),currentUsage:rr.optional(),agentCommands:q.array(nr).optional(),agentModes:q.array(sr).optional(),interactive:q.boolean().optional(),originatingClient:or.optional(),priority:q.number().int().nonnegative().optional(),createdAt:q.string(),updatedAt:q.string()}),fp=q.object({version:q.literal(1),exportedAt:q.string(),exportedFrom:q.object({hydraVersion:q.string(),machine:q.string(),hydraHost:q.string().optional()}),session:pp,history:q.array(lp),promptHistory:q.array(q.string()).optional(),toolBlobs:q.record(q.string()).optional()});function qt(s){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:s.hydraVersion,machine:s.machine,...s.hydraHost!==void 0&&s.hydraHost.length>0?{hydraHost:s.hydraHost}:{}},session:{sessionId:s.record.sessionId,lineageId:s.record.lineageId,...s.record.upstreamSessionId?{upstreamSessionId:s.record.upstreamSessionId}:{},agentId:s.record.agentId,cwd:s.record.cwd,...s.record.title!==void 0?{title:s.record.title}:{},...s.record.synopsis!==void 0?{synopsis:s.record.synopsis}:{},...s.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:s.record.summarizedThroughEntry}:{},...s.record.currentModel!==void 0?{currentModel:s.record.currentModel}:{},...s.record.currentMode!==void 0?{currentMode:s.record.currentMode}:{},...s.record.currentUsage!==void 0?{currentUsage:s.record.currentUsage}:{},...s.record.agentCommands!==void 0?{agentCommands:s.record.agentCommands}:{},...s.record.agentModes!==void 0?{agentModes:s.record.agentModes}:{},...s.record.interactive!==void 0?{interactive:s.record.interactive}:{},...s.record.originatingClient!==void 0?{originatingClient:s.record.originatingClient}:{},...s.record.priority!==void 0&&s.record.priority>0?{priority:s.record.priority}:{},createdAt:s.record.createdAt,updatedAt:s.record.updatedAt},history:s.history};return s.promptHistory!==void 0&&(e.promptHistory=s.promptHistory),s.toolBlobs!==void 0&&Object.keys(s.toolBlobs).length>0&&(e.toolBlobs=s.toolBlobs),e}function ua(s){return fp.parse(s)}function vr(s){if(s&&!(s.costAmount===void 0&&s.cumulativeCost===void 0))return(s.cumulativeCost??0)+(s.costAmount??0)}function zt(s){if(!s)return;let e={};s.used!==void 0&&(e.used=s.used),s.size!==void 0&&(e.size=s.size);let t=vr(s);return t&&(e.costAmount=t),s.costCurrency!==void 0&&(e.costCurrency=s.costCurrency),e}var la=900*1e3,mp=12,hp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",It=gp(hp,16),Un=class s{constructor(e,t,n,r={}){this.registry=e;this.spawner=t??(a=>ze.spawn(a)),this.store=n??new vn,this.tombstones=r.tombstones??new _n,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new jn({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=r.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new On({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,d)=>{let c=this.get(a);if(c){await c.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,c)=>this.persistSynopsis(a,d,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,c)=>{if(c.targetAgentId)return;let u=this.get(a);u&&(u.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,c)=>{this.emitSwapPhase(a,c.targetAgentId,d)},onSynthesisArtifact:async(a,d,c,u,l)=>{await this.dispatchSynthesisSwap(a,d,c,u,l)},onSynthesisUnavailable:async(a,d,c)=>{let u=await this.store.read(a).catch(()=>{});if(u?.synopsis&&u.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${c}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,u.synopsis,u.summarizedThroughEntry,d);return}let l=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${c}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,l,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=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,n,r,o){let i=this.get(e);if(t===void 0&&r===void 0)return;if(!i){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:n});return}let a=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,a,n,r,o);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(d){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${d instanceof Error?d.message:String(d)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let n=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):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,n,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,n,o.summarizedThroughEntry,i,o.compactionState?.runId)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,n,r,o,i){try{let a=o?Math.min(t===void 0?mp:5,n):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:n,tailFloor:a,summarizedThroughEntry:r,...o?{newAgentId:o}:{},...i!==void 0?{runId:i}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(a){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await it(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let n=Y(t.provider);if(n===void 0){let u=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${u}`);return this.logger?.warn?.(`session workspace: ${u}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:u}}let r=t.label??`s-${It().slice(0,8)}`,o=await n.createWorkspace({sourceCwd:e.cwd,label:r,...t.from!==void 0?{from:t.from}:{}}).catch(u=>({ok:!1,reason:String(u)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;n.capabilities().locking&&await n.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await Mn(i.sourceCwd).catch(()=>({})),d,c=await this.materializeNestedTrees(i);if(c!==void 0&&this.logger?.info?.(`session workspace: ${c} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let u=await mr(i.sourceCwd,i.path,a.carry).catch(()=>{});u!==void 0&&u.copied.length>0&&this.logger?.info?.(`session workspace: carried ${u.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let u=await Tn(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});u.ok||(d=`postCreate failed: ${u.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await n.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let n=`${Me}${It()}`,r=await this.resolveWorkspace(e),o=r.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:n});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let c of e.transformChain)if(c.intercepts.has("agent:initialize"))try{let u=await c.connection.request("hydra-acp/transformer/message",{token:`t_${It()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});u.action==="stop"&&u.payload&&(d=u.payload)}catch{}i.agentCapabilities=d}let a=new wt({sessionId:n,cwd:o,...r.workspace!==void 0?{workspace:r.workspace}:{},...r.isolationError!==void 0?{workspaceError:r.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:n}),loadExistingAgentSession:(d,c)=>this.bootstrapAgentLoad(d,{...c,mcpServers:c.mcpServers??[],selfSessionId:n}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.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(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,c,u)=>this.runWorkspaceAction(a.sessionId,d,c,u),onCompactionSwapHook:d=>{this.persistRollbackBreadcrumb(a.sessionId,d).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(r.workspace!==void 0){let d=Y(r.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:r.workspace.path,sourceCwd:r.workspace.sourceCwd,label:r.workspace.label,provider:r.workspace.provider,...r.workspace.snapshot!==void 0?{snapshot:r.workspace.snapshot}:{},...r.workspace.vcs!==void 0?{vcs:r.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=x.AlreadyAttached,o}return t}let n=this.resurrectionInflight.get(e.hydraSessionId);if(n)return n;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 n=await this.registry.getAgent(e.agentId);if(!n){let y=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw y.code=x.AgentNotInstalled,y}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await we(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=an(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...o?{extraEnv:o}:{}}),a;try{let y=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}});a=y.agentCapabilities,i.authMethods=Jt(y.authMethods)}catch(y){throw await i.kill().catch(()=>{}),Ve(y,i)}let d;try{let y=Ir(e.agentId,{model:e.currentModel});d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...y&&{_meta:y}})}catch(y){if(y&&typeof y=="object"&&y.code===x.AuthRequired)throw await i.kill().catch(()=>{}),Ve(y,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${y.message}); recovering via import-reseed
141
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Er(d??{}),u=e.agentModes??Cr(Rr(d??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(u?.map(y=>y.id))}`);let l=await ut({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:u,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=Ar(d??{}),p=Cr(xr(d??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(p?.map(y=>y.modelId))}`),e.pendingHistorySync!==!0){let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=ct(d),m=await lt({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,...g?{modelVerb:g}:{},logger:this.logger});if(e.pendingHistorySync!==!0){let y=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${y} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new wt({sessionId:e.hydraSessionId,cwd:e.cwd,...e.workspace!==void 0?{workspace:e.workspace}:{},agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:d?._meta,agentCapabilities:a,...g?{modelVerb:g}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:y=>this.bootstrapAgent({...y,mcpServers:y.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(y,k)=>this.bootstrapAgentLoad(y,{...k,mcpServers:k.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:m,currentMode:l,currentUsage:e.currentUsage,reloadsUpstreamLedger:!0,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(h.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(h),scheduleCompaction:y=>this.scheduleCompaction(h.sessionId,y),resolveAgentId:async y=>(await this.registry.getAgent(y))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),forkHook:y=>this.forkSession(h.sessionId,y??{}),workspaceHook:(y,k,w)=>this.runWorkspaceAction(h.sessionId,y,k,w),onCompactionSwapHook:y=>{this.persistRollbackBreadcrumb(h.sessionId,y).catch(()=>{})},persistWatermarkHook:y=>{this.mutateRecord(h.sessionId,{summarizedThroughEntry:y}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}async doResurrectFromImport(e){let t=await this.resolveResurrectTarget(e.cwd,e.workspace),n=t.cwd,r=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),o=e.agentModes??r.initialModes,i=await ut({agent:r.agent,upstreamSessionId:r.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:r.initialMode,advertisedModes:o,logger:this.logger}),a=e.agentModels??r.initialModels,d=await lt({agent:r.agent,upstreamSessionId:r.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:r.initialModel,...r.modelVerb?{modelVerb:r.modelVerb}:{},logger:this.logger});r.agent.connection.drainBuffered("session/update");let c=new wt({sessionId:e.hydraSessionId,cwd:n,...t.workspace!==void 0?{workspace:t.workspace}:{},agentId:e.agentId,agent:r.agent,upstreamSessionId:r.upstreamSessionId,agentMeta:r.agentMeta,agentCapabilities:r.agentCapabilities,...r.modelVerb?{modelVerb:r.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:u=>this.bootstrapAgent({...u,mcpServers:u.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(u,l)=>this.bootstrapAgentLoad(u,{...l,mcpServers:l.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:d,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:o,agentModels:a,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(c),scheduleCompaction:u=>this.scheduleCompaction(c.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),forkHook:u=>this.forkSession(c.sessionId,u??{}),workspaceHook:(u,l,f)=>this.runWorkspaceAction(c.sessionId,u,l,f),onCompactionSwapHook:u=>{this.persistRollbackBreadcrumb(c.sessionId,u).catch(()=>{})},persistWatermarkHook:u=>{this.mutateRecord(c.sessionId,{summarizedThroughEntry:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Xe.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);if(!(!t||t.attachedCount>0)&&t.interactive!==!0){if(t.hasWorkInFlight){this.logger?.info(`deferring reap of ${e}: work still in flight after detach`),t.onceIdle(n=>{this.reapIfOrphanedNonInteractive(n.sessionId).catch(()=>{})});return}this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}async resolveResurrectTarget(e,t){if(await this.dirExists(e))return t!==void 0?{cwd:e,workspace:t}:{cwd:e};if(t!==void 0){let n=await this.recoverWorkspace(t);if(n!==void 0)return{cwd:n.path,workspace:n}}return{cwd:de(this.defaultCwd)}}async releaseWorkspace(e,t){let n=Y(e.provider);if(n===void 0){this.logger?.warn?.(`session workspace: no provider "${e.provider}" to release ${e.path}; leaving it in place`);return}return this.enqueueKeyed(this.workspaceQueues,e.path,async()=>{let r=this.liveSessionsIn(e.path,t);if(r.length>0){this.logger?.info?.(`session workspace: keeping ${e.path} \u2014 ${r.length} live session(s) still in it`);return}await this.tearDownWorkspace(n,e,t)})}async syncWorkspaceFromSource(e,t,n){let r=this.liveSessionsIn(t.path,e.sessionId);if(r.length>0)throw new Error(`${T(t.path)} is shared with ${r.map(p=>He(p.sessionId)).join(", ")}, and a sync would move files under them. Sync it from a session that has it to itself.`);let o=await e.quiesceBlocker();if(o!==void 0)throw new Error(o);let i=Y(t.provider);if(t.line===void 0||i?.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which has no history to merge from \u2014 a sync needs a common base, and a copied directory has none. Land its work with \`/hydra workspace merge\` instead, or start a git-backed workspace if you need to track the source.`);let[a,d]=await Promise.all([i.currentState(t.sourceCwd),i.currentState(t.path)]);if(a===void 0||d===void 0)throw new Error("could not read the state of the source or the workspace");if(await i.contains(t.path,{state:a,within:d}))return{ok:!0,message:`Already up to date with ${T(t.sourceCwd)} (${a.slice(0,8)}).`};let c=await i.divergence(t.path,d,a),u=String(c?.behind??0),l=await i.integrate({into:t.path,from:a,message:`hydra: sync ${t.label} with the source`});if(!l.ok){let p=l.conflicts,g=await i.integrationInProgress(t.path);if(p.length===0&&!g){let h=await this.syncOverDirtyTree(t,{provider:i,before:d,sourceHead:a,incoming:u});if(h!==void 0)return h}let m=p.length>0?`
142
+ ${p.map(h=>` ${h}`).join(`
143
+ `)}`:` (${l.reason??"the integration failed"})`;return p.length===0?{ok:!1,message:`the source could not be merged into ${T(t.path)}; nothing changed.${m}
144
+ `+(g?"A merge is already in progress there. Finish it \u2014 resolve, commit \u2014 then `/hydra workspace sync` again.":"Clear that in the workspace, then `/hydra workspace sync` again.")}:n.onConflict==="abort"?(await i.abortIntegration(t.path).catch(()=>{}),{ok:!1,message:`${p.length} file(s) conflict between the source and this workspace:${m}`}):{ok:!1,message:`Synced with conflicts. ${p.length} file(s) need resolving in ${T(t.path)}:${m}
145
+ The merge is left in progress deliberately: fix the markers, commit, then \`/hydra workspace stop\`. To back it out instead: git -C ${t.path} merge --abort`}}let f=(await i.changedPathsBetween(t.path,d,l.snapshot)).length;return{ok:!0,message:`Synced ${T(t.path)} with ${T(t.sourceCwd)}: ${u} commit(s), ${f} file(s) changed. Your uncommitted work is untouched.`}}async syncOverDirtyTree(e,t){let{provider:n,before:r,sourceHead:o,incoming:i}=t;if(n?.capabilities().supports.captureWorkingState!==!0)return;let a=this.asWorkspace(e),d=await n.status(a).catch(()=>{});if(d===void 0||d.changedPaths.length===0)return;let c=await n.captureWorkingState(e.path,`hydra: work set aside to sync ${e.label}`).catch(()=>{});if(c===void 0)return;let u=Ui(e.label);if(await n.retainSnapshot(a,u,c).then(()=>n.resolveRetained(a,u)).catch(()=>{})===void 0)return;let f={clean:!1,snapshot:c,base:r},p=`git -C ${e.path} cherry-pick --no-commit ${u} # the snapshot's parent is ${r.slice(0,8)}, so this replays exactly your work`;if(!(await n.resetTo(e.path,r)).ok){let S=await Ye({source:e.path,capture:f,provider:n});return{ok:!1,message:`Could not clear ${T(e.path)} to merge into it, so nothing was synced. ${S?"Your uncommitted work is back in place.":`Your uncommitted work is at ${u}: ${p}`}`}}if(!(await n.integrate({into:e.path,from:o,message:`hydra: sync ${e.label} with the source`})).ok){await n.abortIntegration(e.path).catch(()=>{});let S=await Ye({source:e.path,capture:f,provider:n});return S&&await n.dropSnapshotRef(a,u).catch(()=>{}),{ok:!1,message:`The source's commits and this workspace's commits genuinely conflict, and that has to be resolved with a merge left in progress \u2014 which cannot happen while there is uncommitted work here, since the work has to be set aside for the merge to run at all.
146
+ `+(S?`Your uncommitted work is back in place (unstaged) and nothing else changed. Commit it in ${T(e.path)}, then \`/hydra workspace sync\` again to resolve the conflict there.`:`Your uncommitted work could not be put back and is preserved at ${u}. Recover it with:
147
+ ${p}`)}}let h=await Ye({source:e.path,capture:f,provider:n}),y=await n.currentState(e.path),k=y===void 0?0:(await n.changedPathsBetween(e.path,r,y)).length,w=`Synced ${T(e.path)} with ${T(e.sourceCwd)}: ${i} commit(s), ${k} file(s) changed.`;return h?(await n.dropSnapshotRef(a,u).catch(()=>{}),{ok:!0,message:`${w} Your uncommitted work was set aside for the merge and restored on top.`}):{ok:!1,message:`${w}
148
+ Your uncommitted work touches the same lines as the commits that just arrived, so replaying it left conflict markers where they collide. The whole set is preserved at ${u} if you would rather start over:
149
+ ${p}`}}async fastForwardBlocked(e){let n=this.asWorkspace(e).line;if(n===void 0)return"the workspace has no line of work to land from";let r=Y(e.provider);if(r===void 0)return;let o=await r.currentState(e.sourceCwd);if(o===void 0||await r.contains(e.sourceCwd,{state:o,within:n}))return;let i=await r.currentLineName(e.sourceCwd);return`${T(e.sourceCwd)} has moved on since this workspace was created (it is on ${i??"an unknown branch"}). \`/hydra workspace sync\` brings those commits in here and makes the landing possible again, or land it by hand with: git -C ${e.sourceCwd} merge ${n}`}async tearDownWorkspace(e,t,n){let r={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},o=await Mn(t.sourceCwd).catch(()=>({}));if(o.preRemove!==void 0){let a=await Tn(o.preRemove,{workspacePath:t.path,sourceCwd:t.sourceCwd,label:t.label,...n!==void 0?{sessionId:n}:{},...o.hookTimeoutSeconds!==void 0?{timeoutSeconds:o.hookTimeoutSeconds}:{}});a.ok||this.logger?.warn?.(`session workspace: preRemove failed for ${t.path}: ${a.reason??"unknown"}`)}for(let a of Bi(t.label))await e.dropSnapshotRef(r,a).catch(()=>{});let i=await e.status(r).catch(()=>({clean:!1,changedPaths:["<unknown>"],hasRecordedWork:!1}));if(i.changedPaths.length>0){this.logger?.warn?.(`session workspace: keeping ${t.path} \u2014 it has ${i.changedPaths.length} uncommitted change(s) that removal would destroy. Remove it by hand once you have salvaged or discarded them.`);return}await e.removeWorkspace(r,{force:!0}).catch(a=>this.logger?.warn?.(`session workspace: could not remove ${t.path}: ${String(a)}`))}snapshotRefFor(e){return Bt(e).autosave}startRefFor(e){return Bt(e).start}baselineRefFor(e){return Bt(e).baseline}scheduleWorkspaceSnapshot(e){if(e.workspace===void 0){this.driftNoticed.delete(e.sessionId);return}if(this.snapshotInFlight.has(e.sessionId)){this.snapshotPending.add(e.sessionId);return}this.snapshotInFlight.add(e.sessionId),this.runWorkspaceSnapshot(e).catch(()=>{}).finally(()=>{this.snapshotInFlight.delete(e.sessionId),this.snapshotPending.delete(e.sessionId)&&this.scheduleWorkspaceSnapshot(e)})}async runWorkspaceSnapshot(e){let t=e.workspace;if(t===void 0)return;let n=Y(t.provider);if(n===void 0||!n.capabilities().supports.captureWorkingState)return;let r={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}};if(await this.noticeSourceDrift(e,t).catch(()=>{}),this.workspaceSnapshotsDisabled)return;let o=await n.status(r).catch(()=>{});if(o!==void 0&&o.changedPaths.length===0)return;let i=await n.captureWorkingState(t.path,`hydra: autosave ${e.sessionId}`);await n.retainSnapshot(r,this.snapshotRefFor(t.label),i)}async noticeSourceDrift(e,t){if(this.asWorkspace(t).line===void 0)return;let r=Y(t.provider);if(r===void 0||!r.capabilities().sharedHistory)return;let o=await r.currentState(t.sourceCwd);if(o===void 0||this.driftNoticed.get(e.sessionId)===o)return;let i=await r.currentState(t.path);if(i===void 0)return;if(await r.contains(t.path,{state:o,within:i})){this.driftNoticed.delete(e.sessionId);return}let d=(await r.divergence(t.path,i,o))?.behind??0;d<=0||(this.driftNoticed.set(e.sessionId,o),e.broadcastWorkspacePhase({phase:"drift",label:t.label,sourceCwd:t.sourceCwd,behind:d}),e.broadcastSyntheticText(`
150
+ ${T(t.sourceCwd)} has moved on: ${d} commit(s) are there and not in this workspace. Landing is fast-forward-only, so \`/hydra workspace sync\` now is what keeps \`stop\` from refusing later.
151
+ `))}async runWorkspaceAction(e,t,n,r){let o=this.get(e);if(o===void 0)throw new Error("session is not live");if(t==="status"){let a=o.workspace;if(a===void 0)return`Not isolated. Working directly in ${T(o.cwd)}.
152
+ Use \`/hydra workspace start\` to move into an isolated workspace.`;let d=this.liveSessionsIn(a.path,o.sessionId).map(p=>He(p.sessionId)),c=a.line,u=[`Isolated in ${T(a.path)}`,` source: ${T(a.sourceCwd)}`,` provider: ${a.provider}${c!==void 0?` (${c})`:""}`];d.length>0&&u.push(` shared with: ${d.join(", ")}`);let f=await Y(a.provider)?.statusReport({path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.vcs!==void 0?{vcs:a.vcs}:{}}).catch(()=>{});for(let p of f??[])u.push(` ${p}`);return u.push(d.length>0?`\`stop\` behaves as \`detach\` while ${d.length===1?"that session is":"those sessions are"} still here; the work lands when the last one leaves.`:"Use `/hydra workspace stop` to merge and return, `discard` to throw the work away, `detach` to return and leave it here, or `clean` to wipe it and keep working here."),u.join(`
153
+ `)}if(t==="start")return this.startWorkspace(o,n,{clean:r?.clean===!0});let i=o.workspace;if(i===void 0)throw new Error("this session is not in a workspace. Use `/hydra workspace start` first.");if(t==="sync")return(await this.syncWorkspaceFromSource(o,i,{onConflict:"keep"})).message;if(t==="clean")return await this.cleanWorkspace(o,i,{deep:r?.deep===!0});if(t==="merge"){o.broadcastWorkspacePhase({phase:"landing"});let a;try{a=await this.mergeWorkspaceIntoSource(i,o.sessionId)}catch(d){let c=d instanceof Error?d.message:String(d);throw o.broadcastWorkspacePhase({phase:"failed",error:c}),d}return o.broadcastWorkspacePhase({phase:"entered",cwd:o.cwd,sourceCwd:i.sourceCwd,label:i.label}),[`${a.merged}; still working in ${T(i.path)}.`,...a.warnings].join(`
154
+ `)}if(t==="apply"){o.broadcastWorkspacePhase({phase:"applying"});let a;try{a=await this.applyWorkspaceToSource(i,o.sessionId)}catch(d){let c=d instanceof Error?d.message:String(d);throw o.broadcastWorkspacePhase({phase:"failed",error:c}),d}return o.broadcastWorkspacePhase({phase:"entered",cwd:o.cwd,sourceCwd:i.sourceCwd,label:i.label}),[a.applied,...a.warnings].join(`
155
+ `)}if(t==="stop"){let a=this.liveSessionsIn(i.path,o.sessionId);if(a.length>0){o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"detached"});let c=a.map(f=>He(f.sessionId)).join(", "),u=[`Left ${T(i.path)} and returned to ${T(i.sourceCwd)}.`,`Nothing landed yet: ${c} still working there. It lands when the last session leaves.`],l=await this.fastForwardBlocked(i);return l!==void 0&&u.push(`WARNING: that merge will not fast-forward as things stand \u2014 ${l}`),u.join(`
156
+ `)}o.broadcastWorkspacePhase({phase:"landing"});let d;try{d=await this.mergeWorkspaceIntoSource(i,o.sessionId)}catch(c){let u=c instanceof Error?c.message:String(c);throw o.broadcastWorkspacePhase({phase:"failed",error:u}),c}o.broadcastWorkspacePhase({phase:"returning"});try{await this.leaveWorkspace(o,i,{exit:"landed"})}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`${d.merged}, but the session could not leave the workspace: ${u}`)}return[`${d.merged} and returned there; workspace removed.`,...d.warnings].join(`
157
+ `)}if(t==="discard"){let a=this.liveSessionsIn(i.path,o.sessionId);if(a.length>0)throw new Error(`${T(i.path)} is shared with ${a.map(u=>He(u.sessionId)).join(", ")}, so its work is not yours alone to discard. Use \`/hydra workspace detach\` to leave it to them.`);o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"discarded"});let d=await this.retireAutosave(i),c=[`Discarded ${T(i.path)} and its branch ${i.line??"(none)"}; returned to ${T(i.sourceCwd)}.`];return d!==void 0&&c.push(`The last autosave is kept at ${d} if you want it back: git -C ${i.sourceCwd} checkout ${d}`),c.join(`
158
+ `)}return o.broadcastWorkspacePhase({phase:"returning"}),await this.leaveWorkspace(o,i,{exit:"detached"}),[`Returned to ${T(i.sourceCwd)} WITHOUT merging.`,`The workspace is still at ${T(i.path)} and its branch ${i.line??"(none)"} is intact, so nothing is lost. Land it later with \`hydra workspace merge\`, or drop it with \`/hydra workspace discard\`.`].join(`
159
+ `)}asWorkspace(e){return{path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.line!==void 0?{line:e.line}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}}}async retireAutosave(e){let t=Y(e.provider);if(t===void 0)return;let n=this.asWorkspace(e),r=this.snapshotRefFor(e.label),o=await t.resolveRetained(n,r).catch(()=>{});if(o===void 0)return;let i=Di(e.label,o);return await t.retainSnapshot(n,i,o).then(()=>!0).catch(()=>!1)?(await t.dropSnapshotRef(n,r).catch(()=>{}),i):r}async cleanWorkspace(e,t,n){return await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let r=this.liveSessionsIn(t.path,e.sessionId);if(r.length>0)throw new Error(`${T(t.path)} is shared with ${r.map(w=>He(w.sessionId)).join(", ")}, and a clean would destroy their work too. Clean it from a session that has it to itself.`);let o=await e.quiesceBlocker();if(o!==void 0)throw new Error(o);let i=Y(t.provider);if(i===void 0)throw new Error(`no provider "${t.provider}" available to clean this workspace`);if(t.snapshot===void 0||i.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which records no base state to return to, so there is nothing to clean back to. Use \`/hydra workspace discard\` to throw it away instead.`);let a=this.asWorkspace(t),d=t.snapshot,u=(await i.status(a).catch(()=>{}))?.changedPaths.length??0,f=(await i.divergence(t.path,d,"HEAD").catch(()=>{}))?.behind??0,p=await i.currentState(t.path)??"",g=await this.retireAutosave(t);e.broadcastWorkspacePhase({phase:"cleaning",label:t.label});let m=await i.resetTo(t.path,d,{purgeIgnored:n.deep});if(!m.ok)throw new Error(`could not return ${T(t.path)} to its base: ${m.reason??"unknown error"}. Nothing was changed.`);let h=n.deep?await this.applyWorkspaceSetup(t,e.sessionId):void 0;await i.retainSnapshot(a,this.startRefFor(t.label),t.snapshot).catch(()=>{});let y={...t,clean:!0};e.workspace=y,await this.mutateRecord(e.sessionId,{workspace:y}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:t.sourceCwd,label:t.label,...a.line!==void 0?{branch:a.line}:{}});let k=[`Cleaned ${T(t.path)} back to the state it was created in.`];if(u>0||f>0){let w=[];u>0&&w.push(`${u} uncommitted change(s)`),f>0&&w.push(`${f} commit(s)`),k.push(` discarded ${w.join(" and ")}`)}else k.push(" nothing to discard; it was already at its base");return h!==void 0&&k.push(` ${h}`),g!==void 0&&k.push(` last autosave kept at ${g}: git -C ${t.sourceCwd} checkout ${g}`),f>0&&p.length>0&&k.push(` discarded commits are still at ${p.slice(0,12)} (and in the reflog for ${t.line??"this branch"})`),k.push(`Your uncommitted work in ${T(t.sourceCwd)} was never touched by this.`),k.join(`
160
+ `)})}async mergeWorkspaceIntoSource(e,t){let n=e.sourceCwd,r=e.line;if(r===void 0)throw new Error(`workspace ${e.label} has no line of work to land from`);if(!await this.dirExists(n))throw new Error(`source tree ${T(n)} no longer exists`);let i=Y(e.provider),a=this.asWorkspace(e),d=await gr({source:n,ws:a,startSnapshotRef:this.startRefFor(e.label),baselineRef:this.baselineRefFor(e.label),retainRef:fr(t),provider:i});if(i===void 0)throw new Error(`no provider "${e.provider}" available to land this workspace`);let c=await i.currentState(n);if(c===void 0)throw new Error(`could not read the state of ${T(n)}`);let u=await i.contains(n,{state:c,within:r}),l=[];if(!u){let b=this.get(t),A="";if(b!==void 0)try{let R=await this.syncWorkspaceFromSource(b,e,{onConflict:"abort"});R.ok?(l.push(`
161
+ synced with the source first: ${R.message}`),u=await i.contains(n,{state:c,within:r})):A=`
162
+ A sync was attempted first and could not complete: ${R.message}`}catch(R){A=`
163
+ A sync was attempted first but was refused: ${R instanceof Error?R.message:String(R)}`}if(!u){let R=await i.currentLineName(n)??"the source";throw new Error(`cannot fast-forward ${R} in ${T(n)} to ${r}. The source has moved on since this workspace was created. The source is untouched.${A}
164
+ `+(A.length>0?`Or land it by hand with: git -C ${n} merge ${r}`:`Resolve it in the workspace with \`/hydra workspace sync\` (which leaves the conflict there to fix), or land it by hand with: git -C ${n} merge ${r}`))}}let f=i!==void 0&&i.capabilities().supports.nestedTrees?await i.captureNested(e.path,await i.listNested(e.path)).catch(()=>[]):[],p,g=await i.status(a).catch(()=>{});if(g!==void 0&&g.changedPaths.length>0&&(p=await i.captureWorkingState(e.path,`hydra: uncommitted work in ${e.label}`).catch(()=>{}),p===void 0))throw new Error(`could not capture the uncommitted work in ${T(e.path)}; nothing was changed`);if(!d.clean&&!(await i.resetTo(n,c)).ok)throw new Error(`could not clear ${T(n)} for the merge; your work is preserved at ${d.retainedRef}. Nothing was merged.`);let m=await i.integrate({into:n,from:r,fastForwardOnly:!0});if(!m.ok)throw new Error(`merge failed: ${m.reason??"unknown error"}`);let h=!0;if(p!==void 0){let b=await i.captureDelta(n,m.snapshot,p);b!==void 0&&(h=(await i.applyDelta(n,b)).ok)}let y=await Ye({source:n,capture:d,provider:i});y&&await Lt({source:n,ws:a,capture:d,provider:i});let k={applied:[],failed:[]},w=i!==void 0&&i.capabilities().supports.nestedTrees?await i.integrateNested(n,e.path,f).catch(()=>k):k,S=await i.captureWorkingState(n,`hydra: source state after landing ${e.label}`).catch(()=>{});S!==void 0&&await i.retainSnapshot({...a,path:n},this.baselineRefFor(e.label),S).catch(()=>{});let I=[];h||I.push(` WARNING: the workspace's uncommitted changes could not be replayed; they remain reachable from ${r}.`),y||I.push(e.clean===!0?` WARNING: this workspace started clean, so your uncommitted work was never copied in. The whole of it is being replayed now and it overlaps what the agent changed. All of it is preserved at ${d.retainedRef}; recover with: git -C ${n} diff ${d.base} ${d.retainedRef}`:` WARNING: your own edits to ${T(n)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${d.retainedRef}; recover with: git -C ${n} diff ${d.base} ${d.retainedRef}`);for(let b of w.failed)I.push(` WARNING: nested tree ${b.path} was NOT reconciled: ${b.reason}. ${T(n)} now records a different state for it, so it will report it as modified until you resolve that.`);return{merged:`Merged ${r} into ${T(n)}${l.join("")}`,warnings:I}}async applyWorkspaceToSource(e,t){let n=e.sourceCwd;if(!await this.dirExists(n))throw new Error(`source tree ${T(n)} no longer exists`);let r=Y(e.provider);if(r===void 0)throw new Error(`no provider "${e.provider}" available to apply this workspace`);if(!r.capabilities().supports.captureWorkingState)throw new Error(`provider "${e.provider}" cannot snapshot a working tree, so there is no change set to apply. Use \`/hydra workspace stop\` to land this workspace instead.`);let o=this.asWorkspace(e);if((await r.status({...o,path:n}).catch(()=>{}))?.hasStagedWork===!0)throw new Error(`${T(n)} already has changes staged for its next commit, and \`apply\` delivers into that same index: the two sets would be indistinguishable, and unstaging one would unstage both. Commit or unstage them first, or use \`/hydra workspace merge\`, which lands the work as commits and does not touch the index.`);let a=await r.currentState(n);if(a===void 0)throw new Error(`could not read the state of ${T(n)}`);let d=e.line,c=d!==void 0&&await r.contains(n,{state:a,within:d}).catch(()=>!1),u=c?a:e.snapshot??"";if(u.length===0)throw new Error(`workspace ${e.label} has no recorded base to measure its changes against, so there is no way to tell its work apart from what the source already had`);let l=await gr({source:n,ws:o,startSnapshotRef:this.startRefFor(e.label),baselineRef:this.baselineRefFor(e.label),retainRef:fr(t),provider:r}),f=r.capabilities().supports.nestedTrees?(await r.listNested(e.path).catch(()=>[])).filter(w=>w.changedPaths.length>0||w.recorded!==void 0&&w.recorded!==w.actual):[],p=await r.captureWorkingState(e.path,`hydra: apply from ${e.label}`).catch(()=>{});if(p===void 0)throw new Error(`could not snapshot the work in ${T(e.path)}; nothing was changed`);let g=await r.captureDelta(n,u,p);if(g===void 0)throw new Error(`could not work out what ${e.label} changed; ${T(n)} was not touched`);if(g.trim().length===0)return await Lt({source:n,ws:o,capture:l,provider:r}),{applied:`Nothing to apply: ${e.label} holds no changes ${T(n)} does not already have.`,warnings:[]};if(!l.clean&&!(await r.resetTo(n,a)).ok)throw new Error(`could not clear ${T(n)} to apply onto; your work is preserved at ${l.retainedRef}. Nothing was applied.`);let m=await r.applyDelta(n,g,{stage:!0,tolerant:!c});if(!m.ok){await r.resetTo(n,a).catch(()=>{});let w=await Ye({source:n,capture:l,provider:r});throw w&&await Lt({source:n,ws:o,capture:l,provider:r}),new Error(`could not apply ${e.label} into ${T(n)}: ${m.reason??"the change set did not apply"}.`+(c?"":" The source has moved on since this workspace was created; `/hydra workspace sync` brings those commits in here, which is what lets the change set apply against them.")+(w?` ${T(n)} is as you left it.`:` Your uncommitted work there is preserved at ${l.retainedRef}.`))}let h=await Ye({source:n,capture:l,provider:r});h&&await Lt({source:n,ws:o,capture:l,provider:r});let y=await r.captureWorkingState(n,`hydra: source state after applying ${e.label}`).catch(()=>{});y!==void 0&&await r.retainSnapshot({...o,path:n},this.baselineRefFor(e.label),y).catch(()=>{});let k=[];m.alreadyPresent===!0&&k.push(` Nothing was staged: ${T(n)} already had every one of those changes.`),h||k.push(` WARNING: your own edits to ${T(n)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${l.retainedRef}; recover with: git -C ${n} diff ${l.base} ${l.retainedRef}`);for(let w of f)k.push(` WARNING: nested tree ${w.relPath} was NOT included: a change set can only move the pointer to it, not what is inside. Land it with \`/hydra workspace stop\`, or copy that work across by hand.`);return{applied:`Applied ${e.label} into ${T(n)} as staged changes; still working in ${T(e.path)}.
165
+ Nothing was committed: review it with \`git -C ${n} diff --cached\` and commit it however you like. The workspace and its history are untouched.`,warnings:k}}async leaveWorkspace(e,t,n){let r=n.exit!=="detached",o=Y(t.provider),i={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},a=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:t.sourceCwd,workspace:void 0,historyLength:a.length,note:`Returned to the source tree at ${t.sourceCwd}`+(n.exit==="landed"?" after merging the workspace.":n.exit==="discarded"?" after discarding the workspace and its work.":" without merging."),...await this.recordSynopsisFor(e.sessionId),left:{path:t.path,removed:r}}),await this.mutateRecord(e.sessionId,{cwd:e.cwd},["workspace"]),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"left",cwd:e.cwd,sourceCwd:t.sourceCwd,integrated:n.exit==="landed"}),o!==void 0&&await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let d=this.liveSessionsIn(t.path,e.sessionId);if(d.length>0){this.logger?.info?.(`session workspace: ${e.sessionId} left ${t.path}; ${d.length} live session(s) remain, so it stays`);return}await this.reclaimAfterLastLeaver(o,i,t,e.sessionId,n)})}async reclaimAfterLastLeaver(e,t,n,r,o){await e.unlock(t).catch(()=>{});for(let i of[this.startRefFor(n.label),this.baselineRefFor(n.label)])await e.dropSnapshotRef(t,i).catch(()=>{});o.exit!=="detached"&&(o.exit==="landed"&&await e.dropSnapshotRef(t,this.snapshotRefFor(n.label)).catch(()=>{}),await e.removeWorkspace(t,{force:!0,discardLine:!0}).catch(()=>{}))}async joinDivergence(e,t,n){let[r,o]=await Promise.all([e.captureWorkingState(t,"hydra: source state at join").catch(()=>{}),e.captureWorkingState(n.path,"hydra: workspace state at join").catch(()=>{})]);if(r===void 0||o===void 0)return`could not compare ${T(t)} with ${T(n.path)}, so refusing to join a workspace that may not match your tree`;let i=await Promise.all([r,o].map(a=>e.contentId(t,a).catch(()=>{})));if(!(i[0]!==void 0&&i[0]===i[1]))return`${T(t)} and ${T(n.path)} have diverged, and joining does not carry work across \u2014 whichever side you are not in would be left behind. Land or stash one of them first: \`git -C ${t} stash\` if the difference is yours, or \`/hydra workspace merge\` from the session already in there if it is theirs.`}liveSessionsWithLabel(e,t){let n=[];for(let r of this.sessions.values()){let o=r.workspace;o===void 0||o.sourceCwd!==e||(o.label===t||o.requestedLabel===t)&&n.push(r)}return n}async joinWorkspace(e,t,n,r){let o=Y(n.provider);if(o===void 0)throw new Error(`no provider "${n.provider}" to join that workspace with`);if(o.capabilities().supports.captureWorkingState){let i=await this.joinDivergence(o,r,n);if(i!==void 0)throw new Error(i)}return await this.enqueueKeyed(this.workspaceQueues,n.path,async()=>{if(this.sessions.get(t.sessionId)?.workspace?.path!==n.path)throw new Error(`${T(n.path)} was released while joining it; run the command again`);e.broadcastWorkspacePhase({phase:"swapping"});let i=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:n.path,workspace:{path:n.path,sourceCwd:n.sourceCwd,label:n.label,...n.requestedLabel!==void 0?{requestedLabel:n.requestedLabel}:{},provider:n.provider,...n.snapshot!==void 0?{snapshot:n.snapshot}:{},...n.line!==void 0?{line:n.line}:{},...n.vcs!==void 0?{vcs:{...n.vcs}}:{}},historyLength:i.length,note:`Continuing in an isolated workspace at ${n.path}, derived from ${r}, shared with another session.`,...await this.recordSynopsisFor(e.sessionId)}),await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache();let a=n.line;e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:n.sourceCwd,label:n.label,...a!==void 0?{branch:a}:{}});let d=this.liveSessionsIn(n.path,e.sessionId).map(u=>He(u.sessionId)),c=[`Joined workspace ${T(n.path)}`,` source: ${T(n.sourceCwd)}`];return a!==void 0&&c.push(` branch: ${a}`),c.push(` shared with: ${d.join(", ")}`),c.push(" your edits will interleave with that session's"),c.push("Use `/hydra workspace stop` to leave; the work lands when the last session leaves."),c.join(`
166
+ `)})}async startWorkspace(e,t,n){if(e.workspace!==void 0)throw new Error(`already isolated in ${T(e.workspace.path)}. Use \`/hydra workspace stop\` to merge and return first, or \`detach\` to leave it behind.`);let r=e.cwd,o=Y();if(o===void 0)throw new Error("no workspace provider available");let i=await e.quiesceBlocker();if(i!==void 0)throw new Error(i);let a=o.capabilities();if(t!==void 0){let b=this.liveSessionsWithLabel(r,t)[0];if(b!==void 0&&b.workspace!==void 0)return await this.joinWorkspace(e,b,b.workspace,r)}let d,c=[],u=!1,l=!1,f=[],p=[],g=n?.clean===!0;if(a.supports.captureWorkingState){let b=await o.status({path:r,sourceCwd:r,label:"source",provider:o.kind}).catch(()=>{});l=b!==void 0;let A=a.supports.nestedTrees&&b!==void 0&&b.changedPaths.length>0?await o.listNested(r).catch(()=>[]):[];if(b!==void 0&&b.changedPaths.length>0&&g)f=dr(b.changedPaths,A);else if(b!==void 0&&b.changedPaths.length>0&&(c=dr(b.changedPaths,A),p=await o.captureNested(r,A).catch(()=>[]),u=b.hasStagedWork===!0,d=await o.captureWorkingState(r,"hydra: work carried into workspace").catch(()=>{}),d===void 0))throw new Error("could not snapshot your uncommitted work, so refusing to move it. Commit or stash first.")}e.broadcastWorkspacePhase({phase:"provisioning"});let m=await o.createWorkspace({sourceCwd:r,label:t??`s-${e.sessionId.slice(-8)}`});if(!m.ok)throw e.broadcastWorkspacePhase({phase:"failed",error:m.reason}),new Error(m.reason);let h=m.workspace,y=this.startRefFor(h.label),k,w=!1,S=[];try{a.locking&&await o.lock(h,`session ${e.sessionId}`).catch(()=>{});let b=d??h.snapshot;if(b===void 0)throw new Error(`provider "${h.provider}" gave the workspace no base to anchor landing against`);await o.retainSnapshot(h,y,b),e.broadcastWorkspacePhase({phase:"setup"}),w=d!==void 0?await this.copyCarriedWork(h,d,r):!0;let A=await this.materializeNestedTrees(h);if(p.length>0){let E=await o.reproduceNested(h.path,r,p).catch($=>({applied:[],failed:p.map(_=>({path:_.relPath,reason:$ instanceof Error?$.message:String($)}))}));E.failed.length>0&&(w=!1,S=E.failed)}k=await this.applyWorkspaceSetup(h,e.sessionId),A!==void 0&&(k=k===void 0?A:`${A}; ${k}`),e.broadcastWorkspacePhase({phase:"swapping"});let R=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:h.path,workspace:{path:h.path,sourceCwd:h.sourceCwd,label:h.label,...t!==void 0&&t!==h.label?{requestedLabel:t}:{},provider:h.provider,...h.snapshot!==void 0?{snapshot:h.snapshot}:{},...h.line!==void 0?{line:h.line}:{},...h.vcs!==void 0?{vcs:{...h.vcs}}:{},...d===void 0?{clean:!0}:{}},historyLength:R.length,note:`Continuing in an isolated workspace at ${h.path}, derived from ${r}.`,...await this.recordSynopsisFor(e.sessionId)})}catch(b){let A=await this.unwindStartWorkspace({provider:o,ws:h,startRef:y,carried:d}),R=b instanceof Error?b.message:String(b);throw e.broadcastWorkspacePhase({phase:"failed",error:R}),new Error(A===void 0?R:`${R}
167
+ ${A}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:h.sourceCwd,label:h.label,...h.line!==void 0?{branch:h.line}:{}});let I=[`Moved into workspace ${T(h.path)}`,` source: ${T(r)}`];if(h.line!==void 0&&I.push(` branch: ${h.line}`),t!==void 0&&t!==h.label&&I.push(` note: "${t}" was already taken by a surviving branch, so this is "${h.label}"`),d!==void 0){I.push(w?` carried ${c.length} uncommitted file(s) in; the source tree is untouched:`:` WARNING: could not copy ${c.length} uncommitted file(s); the workspace starts from HEAD. They are untouched in the source tree:`);for(let b of Ke(c))I.push(` ${b}`);w&&u&&I.push(" staging did not come along; everything above is unstaged here");for(let b of S)I.push(` nested tree ${b.path}: ${b.reason}`)}else if(f.length>0){I.push(` started clean: ${f.length} uncommitted file(s) stayed in the source and did NOT come along:`);for(let b of Ke(f))I.push(` ${b}`)}else l&&I.push(" source tree was clean; nothing carried in");return k!==void 0&&I.push(` ${k}`),I.push("Use `/hydra workspace stop` to merge back and return."),I.join(`
168
+ `)}async copyCarriedWork(e,t,n){let r=await this.patchFromSnapshot(n,t,e.provider);if(r===void 0)return!1;if(r.length===0)return!0;let o=Y(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,r)).ok}async patchFromSnapshot(e,t,n){let r=Y(n);if(r===void 0)return;let o=await r.currentState(e);if(o!==void 0)return await r.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:n,startRef:r,carried:o}=e;await t.unlock(n).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(n,r).catch(()=>{}),await t.removeWorkspace(n,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let n=Y(e.provider);if(n?.capabilities().supports.nestedTrees!==!0)return;let r=await n.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:n.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return r.ok?r.count>0?`populated ${r.count} nested tree(s)`:void 0:`nested trees FAILED: ${r.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let n=await Mn(e.sourceCwd).catch(()=>({})),r=[];if(n.carry!==void 0&&n.carry.length>0){let o=await mr(e.sourceCwd,e.path,n.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&r.push(`carried ${o.copied.length} config file(s)`)}if(n.postCreate!==void 0){let o=await Tn(n.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...n.hookTimeoutSeconds!==void 0?{timeoutSeconds:n.hookTimeoutSeconds}:{}});r.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return r.length>0?r.join("; "):void 0}async deriveForkWorkspace(e,t){let n=Y(e.provider);if(n===void 0)return;let r=n.capabilities(),o=r.sharedHistory?await n.currentState(e.path)??"":"",i=await n.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&r.supports.captureWorkingState){let d=await n.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,n,r,o){let i=Y(o);if(i===void 0)return!1;let a=await i.captureDelta(e,n,r).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=Y(e.provider);if(t===void 0)return;let n={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(n).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let r=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(r.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${r.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:r.workspace.path,sourceCwd:r.workspace.sourceCwd,label:r.workspace.label,provider:r.workspace.provider,...r.workspace.snapshot!==void 0?{snapshot:r.workspace.snapshot}:{},...r.workspace.vcs!==void 0?{vcs:{...r.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=x.AgentNotInstalled,p}let n=await we(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:ha.homedir(),plan:n}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}})}catch(p){throw await r.kill().catch(()=>{}),Ve(p,r)}if(r.authMethods=Jt(o.authMethods),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c){d.add(`${p.agentId}::${p.upstreamSessionId}`);for(let g of p.upstreamGenerations??[])d.add(`${g.agentId}::${g.upstreamSessionId}`)}let u=C.sessionsDir(),l=[],f=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){f+=1;continue}if(yp(p.cwd,u)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Li(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${Me}${It()}`,y=new Date().toISOString(),k=p.updatedAt??y,w={sessionId:h,lineageId:Ut(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:k,updatedAt:k};p.title!==void 0&&(w.title=p.title);let S=ir(w);await this.store.write(S),l.push({version:1,...S})}return{synced:l,skipped:f}}async collectAgentSessions(e){let t=[],n,r=new Set;for(let o=0;o<100;o+=1){let i={};n!==void 0&&(i.cursor=n);let a=await e.connection.request("session/list",i),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let u={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(u.title=c.title),typeof c.updatedAt=="string"&&(u.updatedAt=c.updatedAt),t.push(u)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),n=a.nextCursor}return t}async applySeedModel(e,t,n,r,o){try{let{verb:i}=await Je({request:(a,d)=>e.connection.request(a,d),sessionId:t,modelId:n,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${r}: ${i} 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=x.AgentNotInstalled,i}let n=await we(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=an(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:n,...r?{extraEnv:r}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}}),a=i.agentCapabilities;o.authMethods=Jt(i.authMethods);let d=Ir(e.agentId),c=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[],...d&&{_meta:d}}),u=c.sessionId;if(typeof u!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let l=Ar(c),f=xr(c),p=ct(c),g=e.model??this.defaultModels[e.agentId];if(g&&g!==l){let y=gt(g,f),k=e.model!==void 0?`model=${JSON.stringify(g)}`:`defaultModels[${e.agentId}]=${JSON.stringify(g)}`;if(y.kind==="exact"||y.kind==="none")await this.applySeedModel(o,u,g,k,p)&&(l=g);else if(y.kind==="resolved")(y.modelId===l||await this.applySeedModel(o,u,y.modelId,`${k} resolved to ${JSON.stringify(y.modelId)}`,p))&&(l=y.modelId);else if(y.kind==="ambiguous")this.logger?.warn(`${k} is ambiguous (trailing-segment matches [${y.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(l)}`);else{let w=f.map(S=>S.modelId).join(", ");this.logger?.warn(`${k} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(l)}`)}}let m=Rr(c),h=Er(c);return{agent:o,upstreamSessionId:u,agentMeta:c._meta,agentCapabilities:a,initialModel:l,initialModels:f.length>0?f:void 0,initialModes:m.length>0?m:void 0,initialMode:h,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Ve(ga(i,o,e.agentId,{command:n.command,args:n.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let n=await this.registry.getAgent(t.agentId);if(!n){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=x.AgentNotInstalled,a}let r=await we(n,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=an(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}}),d=a.agentCapabilities;i.authMethods=Jt(a.authMethods);let c=Ir(t.agentId),u=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),l=Ar(u),f=Cr(xr(u)),p=Rr(u),g=Er(u);return{agent:i,upstreamSessionId:e,agentMeta:u._meta,agentCapabilities:d,initialModel:l,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:g,modelVerb:ct(u)}}catch(a){throw await i.kill().catch(()=>{}),Ve(ga(a,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 n=await this.store.read(e);if(!n)throw new Error("session record not found");let r=n.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=n.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let n=this.pendingAuthAgents.get(e);if(n&&n.isAlive())return n;let r=await this.registry.getAgent(e);if(!r){let d=new Error(`agent ${e} not found in registry`);throw d.code=x.AgentNotInstalled,d}let o=await we(r,[],{npmRegistry:this.npmRegistry}),i=t??de(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:at,clientInfo:{name:"hydra",version:ie}});a.authMethods=Jt(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ve(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 n=new Error(`agent ${e} not found in registry`);throw n.code=x.AgentNotInstalled,n}return we(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.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let r=At({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...r!==void 0?{interactive:r}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let n=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===n&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,n);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:n,retiredCost:r,reason:o,runId:i})=>{this.persistAgentChange(e.sessionId,t,n,r,o,i).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:ya(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(n=>({name:n.name,...n.description!==void 0?{description:n.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(n=>({id:n.id,...n.name!==void 0?{name:n.name}:{},...n.description!==void 0?{description:n.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(n=>({modelId:n.modelId,...n.name!==void 0?{name:n.name}:{},...n.description!==void 0?{description:n.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),n=wp(e,t);await this.store.write(n)}).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,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return Tt(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let n=t.title;return n||(n=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:n,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:kp(t.currentUsage),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,workspace:t.workspace,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 n=this.sessions.get(e);n&&(n.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let n={...t};delete n.pendingHistorySync,await this.store.write(n)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let n of t){let r=n.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=ht(r.update.prompt),i=Xs(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let n=t.agent.agentId,r=t.agent.version,o=e.get(n);o||(o=new Set,e.set(n,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Me))return;let t=Me+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let n=new Error(`session ${e} not found`);throw n.code=x.SessionNotFound,n}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,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,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Vt(t.sessionId),d=At({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let n=await this.store.read(e).catch(()=>{});if(!n)return;let r=await Vt(n.sessionId),o=At(n,r.hasContent),i=r.mtime??n.updatedAt;return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:zt(n.currentUsage),importedFromMachine:n.importedFromMachine,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:o,priority:n.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,n=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>n)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:n+s.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],n=new Set,r=u=>e.includeNonInteractive?!0:u===!0,o=[...this.sessions.values()].filter(u=>pa(e.cwd,u));if(e.status==="cold")for(let u of o)n.add(u.sessionId);let i=e.status==="cold"?[]:await Promise.all(o.map(u=>Vt(u.sessionId)));for(let u=0;u<i.length;u+=1){let l=o[u],f=i[u];n.add(l.sessionId);let p=At({interactive:l.interactive,...l.originatingClient?{originatingClient:l.originatingClient}:{}},f.hasContent);if(!r(p))continue;let g=f.mtime??new Date(l.updatedAt).toISOString();t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,workspace:l.workspace,workspaceError:l.workspaceError,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:p,priority:l.priority,updatedAt:g,attachedClients:l.attachedCount,status:"warm",agentPid:l.agentPid,busy:l.turnStartedAt!==void 0,armedTasks:l.armedBackgroundTasks.length,...l.armedSince!==void 0?{armedSince:l.armedSince}:{},awaitingInput:l.awaitingInput,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}if(e.status==="warm")return t;let d=(await this.store.list().catch(u=>{throw this.logger?.warn(`session list: store.list() failed: ${u?.message??String(u)}`),u})).filter(u=>!n.has(u.sessionId)&&pa(e.cwd,u)),c=await Promise.all(d.map(u=>Vt(u.sessionId)));for(let u=0;u<d.length;u+=1){let l=d[u],f=c[u],p=At(l,f.hasContent);if(!r(p))continue;let g=f.mtime??l.updatedAt;t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,workspace:l.workspace,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:zt(l.currentUsage),importedFromMachine:l.importedFromMachine,importedFromUpstreamSessionId:l.importedFromUpstreamSessionId,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:p,priority:l.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}return t.sort((u,l)=>u.updatedAt<l.updatedAt?1:-1),t}async exportBundle(e,t={}){let n=await this.store.read(e);if(!n)return;let r;if(n.lineageId)r=n;else{let c=Ut(),u={...n,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let l=await this.store.read(e);l&&(l.lineageId||await this.store.write({...l,lineageId:c}))}).catch(()=>{}),r=u}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await ma(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let d={};for(let c of ra(i)){let u=await mo(e,c);u&&(d[c]=u.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let n=await this.store.findByLineageId(e.session.lineageId);if(n){if(!t.replace){let i=new Error(`bundle already imported as ${n.sessionId}`);throw i.code=x.BundleAlreadyImported,i.existingSessionId=n.sessionId,i}let o=this.sessions.get(n.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:n.sessionId,bundle:e,preservedCreatedAt:n.createdAt,cwd:t.cwd}),{sessionId:n.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Me}${It()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let n=await this.store.read(e);if(!n){let I=new Error(`source session not found: ${e}`);throw I.code=x.SessionNotFound,I}let r=t.agentId??n.agentId,o=r!==n.agentId;if(o&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=x.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,d,c=t.mode??"synthesis",u,l,f,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let I=bn(i,t.forkAt);if(I<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=x.InvalidParams,b}d=t.forkAt,a=i.slice(0,I+1)}else{let I=vp(i);I?(d=I.messageId,a=i.slice(0,I.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let b=bn(i,t.forkAt);if(b<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=x.InvalidParams,A}d=t.forkAt,a=i.slice(0,b+1)}else d="",a=i;let I=await this.registry.getAgent(r);if(!I){let b=new Error(`agent ${r} not found in registry`);throw b.code=x.AgentNotInstalled,b}f=I,l=n.currentModel,u="running"}let g=await ma(e),m=c==="synthesis",h={...n,lineageId:Ut(),agentId:r,interactive:!1,...u!==void 0?{forkSynthesisState:u}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=qt({record:h,history:a,promptHistory:g.length>0?g:void 0,hydraVersion:ie,machine:$t()}),k=`${Me}${It()}`,w=t.cwd,S;if(t.cwd===void 0&&n.workspace!==void 0){let I=await this.deriveForkWorkspace(n.workspace,`${n.workspace.label}-fork-${k.slice(-6)}`);I!==void 0?(S=I,w=I.path):(w=n.workspace.sourceCwd,this.logger?.warn?.(`fork ${k}: could not derive an isolated workspace from ${n.workspace.path}; running unisolated in ${w}`))}return await this.writeImportedRecord({sessionId:k,bundle:y,cwd:w,...S!==void 0?{workspace:S}:{},forkedFromSessionId:e,forkedFromMessageId:d,...u!==void 0?{forkSynthesisState:u}:{}}),m&&(async()=>{try{let I=await we(f,[],{npmRegistry:this.npmRegistry}),b=await Nn({agentId:r,cwd:t.cwd??C.sessionDir(e),plan:I,history:a,modelId:l,sessionId:e,logger:this.logger,timeoutMs:p});b&&b.synopsis?await this.mutateRecord(k,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(k,{},["forkSynthesisState"]))}catch(I){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${I.message}`);try{await this.mutateRecord(k,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:k,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await ho(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Xe.utimes(C.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ca(C.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let n=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,workspace:e.workspace,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??n,updatedAt:e.bundle.session.updatedAt})})}async tombstoneAllGenerations(e,t,n){let r=await this.store.read(e).catch(()=>{}),o=new Map;for(let a of r?.upstreamGenerations??[])a.upstreamSessionId&&o.set(`${a.agentId}::${a.upstreamSessionId}`,{agentId:a.agentId,upstreamSessionId:a.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString();for(let a of o.values())await this.tombstones.add({agentId:a.agentId,upstreamSessionId:a.upstreamSessionId,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:n,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let r=await Vt(e),o=At(n,r.hasContent);await this.tombstoneAllGenerations(e,{agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,...n.title!==void 0?{title:n.title}:{},...o!==void 0?{interactive:o}:{}},t)}return n.workspace!==void 0&&await this.releaseWorkspace(n.workspace,e).catch(()=>{}),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 clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let n=t.workspace?.sourceCwd;return await this.mutateRecord(e,n!==void 0?{cwd:n}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let n=await this.store.read(e).catch(()=>{});return n?n.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let n=this.get(e);if(n)return n.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 n=this.get(e);return n?(await n.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,n){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:n})}async persistAgentChange(e,t,n,r,o,i){await this.mutateRecord(e,{agentId:t,upstreamSessionId:n},void 0,a=>({upstreamGenerations:wa(a,t,n,void 0,r,o,i)}))}async persistSnapshot(e,t){let n={};t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentMode!==void 0&&(n.currentMode=t.currentMode),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(n.agentCommands=t.agentCommands),t.agentModes!==void 0&&(n.agentModes=t.agentModes),t.agentModels!==void 0&&(n.agentModels=t.agentModels),t.interactive!==void 0&&(n.interactive=t.interactive),t.cwd!==void 0&&(n.cwd=t.cwd),await this.mutateRecord(e,n)}async mutateRecord(e,t,n=[],r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...r?r(o):{},updatedAt:new Date().toISOString()};for(let a of n)delete i[a];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,n){return(await this.getExtensionState(e,t))[n]}async setExtensionStateKey(e,t,n,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[n]:r},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>s.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${s.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,n){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(n in i))return;delete i[n],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,n){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(n),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let n=[];for(let r of this.sessions.values())r.sessionId!==t&&r.workspace?.path===e&&n.push(r);return n}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),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 n=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=${n} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,n)}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 persistRollbackBreadcrumb(e,t){await this.mutateRecord(e,{},void 0,n=>{let r=n.rollbackBreadcrumb;return r!==void 0&&t.runId!==void 0&&r.runId===t.runId?(this.logger?.info(`compaction: keeping rollback breadcrumb pinned at ${r.previousUpstreamSessionId} for runId=${t.runId} sessionId=${e} (later swap of the same run)`),{}):{rollbackBreadcrumb:t}})}async getUpstreamGenerations(e){return(await this.store.read(e).catch(()=>{}))?.upstreamGenerations??[]}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,n){let r=this.get(e);if(r){if(t){let o=n.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(n)}}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 n of e){let r=n.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(n.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let n of t){let r=n.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${n.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${n.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(n.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let n=t.pendingAgentSwap;if(n)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=${n} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,n)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${n} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:n}))}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 n=await gi(t.sessionId).catch(()=>[]);if(n.length===0)continue;let r=Date.now(),o=n.filter(d=>r-d.enqueuedAt<la),i=n.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${la/1e3}s)`),await Ot(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await Ot(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function yp(s,e){if(typeof s!="string"||s.length===0)return!1;let t=Gt.resolve(s),n=Gt.resolve(e);return t===n||t.startsWith(n+Gt.sep)}function pa(s,e){if(s===void 0||s.length===0)return!0;let t=Sr(s);if(Sr(e.cwd)===t)return!0;let n=e.workspace?.sourceCwd;return n!==void 0&&Sr(n)===t}function Sr(s){return s.length>1&&s.endsWith("/")?s.replace(/\/+$/,""):s}function wp(s,e){let n=(s.mergedAvailableCommands().length>0?s.agentOnlyAdvertisedCommands().map(u=>u.description!==void 0?{name:u.name,description:u.description}:{name:u.name}):void 0)??e?.agentCommands,r=s.availableModes(),i=(r.length>0?r.map(u=>{let l={id:u.id};return u.name!==void 0&&(l.name=u.name),u.description!==void 0&&(l.description=u.description),l}):void 0)??e?.agentModes,a=s.availableModels(),c=(a.length>0?a.map(u=>{let l={modelId:u.modelId};return u.name!==void 0&&(l.name=u.name),u.description!==void 0&&(l.description=u.description),l}):void 0)??e?.agentModels;return ir({sessionId:s.sessionId,lineageId:e?.lineageId??Ut(),upstreamSessionId:s.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:s.agentId,cwd:s.cwd,title:s.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:s.agentArgs,currentModel:s.currentModel??e?.currentModel,currentMode:s.currentMode??e?.currentMode,currentUsage:ya(s.persistableUsage)??e?.currentUsage,agentCommands:n,agentModes:i,agentModels:c,parentSessionId:s.parentSessionId??e?.parentSessionId,forkedFromSessionId:s.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:s.originatingClient??e?.originatingClient,interactive:s.interactive??e?.interactive,priority:s.priority??e?.priority,forwardedEnv:s.forwardedEnv??e?.forwardedEnv,workspace:s.workspace,attentionFlags:s.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?wa(e,s.agentId,s.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(s.createdAt).toISOString()})}function ya(s){if(!s)return;let e={};return s.used!==void 0&&(e.used=s.used),s.size!==void 0&&(e.size=s.size),s.costAmount!==void 0&&(e.costAmount=s.costAmount),s.costCurrency!==void 0&&(e.costCurrency=s.costCurrency),s.cumulativeCost!==void 0&&(e.cumulativeCost=s.cumulativeCost),Object.keys(e).length>0?e:void 0}function kp(s){return s?{...s}:void 0}function Ir(s,e={}){if(s!=="claude-acp")return;let t={extraArgs:{"thinking-display":"summarized"}};return e.model&&(t.model=e.model),{claudeCode:{options:t}}}function Dn(s,e){let t=e.fromObject(s);if(t!==void 0)return t;let n=s[e.nestedKey];if(n&&typeof n=="object"&&!Array.isArray(n)){let i=e.fromObject(n);if(i!==void 0)return i}let r=s._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=bp(s,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Ar(s){return Dn(s,{nestedKey:"models",configId:"model",fromObject:e=>$e(e.currentModelId)??$e(e.currentModel)??$e(e.modelId)??$e(e.model),fromConfig:e=>$e(e.currentValue)})}function Ve(s,e){if(!s||typeof s!="object")return s;let t=s;if(t.code!==x.AuthRequired)return s;let n=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=n(t.data)?t.data:{},o=n(r._meta)?r._meta:{},i=n(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=x.AuthRequired,d.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function fa(s){return/^[A-Za-z0-9_\-./=:@]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`}function ga(s,e,t,n){if(s&&typeof s=="object"&&s.code===x.AuthRequired)return s;let r=s instanceof Error?s.message:String(s),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=n?`to reproduce: (cd ${fa(n.cwd)} && ${[n.command,...n.args].map(fa).join(" ")})`:"";if(!i&&!a)return s;let d=[o?r:`agent ${t} failed to start: ${r}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let c=new Error(d.join(`
169
+ `));if(s&&typeof s=="object"){let u=s;typeof u.code=="number"&&(c.code=u.code),u.data!==void 0&&(c.data=u.data)}return c}function Jt(s){if(!Array.isArray(s))return;let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string")continue;let r=typeof n.description=="string"?n.description:"",o=n.type==="agent"||n.type==="terminal"?n.type:void 0,i=typeof n.name=="string"?n.name:void 0,a=n._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:n.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...d&&{_meta:d}})}return e.length>0?e:void 0}function $e(s){if(typeof s!="string")return;let e=s.trim();return e.length>0?e:void 0}function bp(s,e){let t=s.configOptions;if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;if(r.id===e)return r}}function Cr(s){return s.length>0?s:void 0}function xr(s){return Dn(s,{nestedKey:"models",configId:"model",fromObject:e=>{let t=yt(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=yt(e.options);return t.length>0?t:void 0}})??[]}function Rr(s){return Dn(s,{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 Er(s){return Dn(s,{nestedKey:"modes",configId:"mode",fromObject:e=>$e(e.currentModeId)??$e(e.currentMode)??$e(e.modeId)??$e(e.mode),fromConfig:e=>$e(e.currentValue)})}function vp(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(!t||t.method!=="session/update")continue;let n=t.params?.update;if(n?.sessionUpdate==="turn_complete"&&!(typeof n.messageId!="string"||n.messageId.length===0))return{index:e,messageId:n.messageId}}}async function ma(s){try{let e=await Xe.readFile(C.tuiHistoryFile(s),"utf8"),t=[];for(let n of e.split(`
170
+ `))if(n.length!==0)try{let r=JSON.parse(n);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}function wa(s,e,t,n=new Date().toISOString(),r,o,i){let a=s.upstreamGenerations&&s.upstreamGenerations.length>0?[...s.upstreamGenerations]:s.upstreamSessionId?[{upstreamSessionId:s.upstreamSessionId,agentId:s.agentId}]:[],d=a[a.length-1];if(d&&d.upstreamSessionId===t){if(r!==void 0&&a.length>=2){let c=a[a.length-2];c&&c.cost===void 0&&(a[a.length-2]={...c,cost:r})}return o!==void 0&&d.reason===void 0&&(a[a.length-1]={...d,reason:o,...i!==void 0?{runId:i}:{}}),a}return d&&d.endedAt===void 0&&(a[a.length-1]={...d,endedAt:n,...r!==void 0?{cost:r}:{}}),a.push({upstreamSessionId:t,agentId:e,startedAt:n,...o!==void 0?{reason:o}:{},...i!==void 0?{runId:i}:{}}),a}async function Vt(s){try{let e=await Xe.stat(C.historyFile(s));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function At(s,e){return s.interactive!==void 0?s.interactive:s.originatingClient?.name===Fn?!1:e?!0:void 0}import{spawn as Sp}from"child_process";import*as Ln from"fs";import*as De from"fs/promises";import*as Wn from"path";import Ip from"pino-roll";var Bn=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,n){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${n}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${n}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Ap=1e3,Cp=6e4,Pr=3e3,Ct=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,n,r={}){this.adapter=t,this.context=n,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Ap,this.restartCapMs=r.restartCapMs??Cp;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let n=this.entries.get(e);n&&(n.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await De.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 n=t.child;if(n){try{n.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(n.exitCode!==null||n.signalCode!==null){r();return}let o=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}r()},Pr);n.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw Qt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Qt(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 Qt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let n=t.child;return n?(await this.terminate(t,n),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 Qt(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(n=>{t.failureReason=`spawn: ${n.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw Qt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let n=t.child;n&&await this.terminate(t,n);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let n=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Pr);typeof r.unref=="function"&&r.unref();try{await n}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 Bn(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await De.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 n=this.adapter.paths.pidFile(t.name),r;try{let o=await De.readFile(n,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&Mr(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+Pr;for(;Date.now()<o&&Mr(r);)await new Promise(i=>setTimeout(i,50));if(Mr(r))try{process.kill(r,"SIGKILL")}catch{}}await De.unlink(n).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let n=this.context;if(!n)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Wn.dirname(this.adapter.paths.logFile(r.name)),a;try{await De.mkdir(i,{recursive:!0}),a=await Ip({file:Wn.join(i,`${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})
171
+ `);let d=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??n.serviceToken;e.processToken=d,e.version=void 0;let c={...dn(),HYDRA_ACP_DAEMON_URL:n.daemonUrl,HYDRA_ACP_DAEMON_HOST:n.daemonHost,HYDRA_ACP_DAEMON_PORT:String(n.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:n.daemonWsUrl,HYDRA_ACP_HOME:n.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[u,...l]=o;if(u===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
172
+ `),a.end();return}let f=de(u),p=[...l,...r.args].map(de),g;try{g=Sp(f,p,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
173
+ `),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{Ln.writeFileSync(this.adapter.paths.pidFile(r.name),`${g.pid}
174
+ `,{encoding:"utf8",mode:384})}catch(h){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
175
+ `)}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}
176
+ `)}),g.on("exit",(h,y)=>{try{Ln.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${y??"null"}
177
+ `),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 k=e.exitWaiters.splice(0);for(let S of k)S();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}
178
+ `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let n=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}`})},n),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Mr(s){try{return process.kill(s,0),!0}catch{return!1}}function Qt(s,e){return s.code=e,s}K();var xp={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:C.extensionsDir,logFile:C.extensionLogFile,pidFile:C.extensionPidFile}},qn=class extends Ct{constructor(e,t,n={}){super(e,xp,t,n)}};K();var Rp={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:C.transformersDir,logFile:C.transformerLogFile,pidFile:C.transformerPidFile}},zn=class extends Ct{connected=new Map;constructor(e,t,n={}){super(e,Rp,t,n)}registerConnection(e,t,n){this.connected.set(e,{name:e,connection:t,intercepts:new Set(n)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let n of e){let r=this.connected.get(n);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let n of this.connected.values())n.intercepts.has(e)&&t.push(n);return t}};var Jn=class{entries=new Map;changeHandlers=[];register(e,t,n){this.entries.set(e,{connection:t,commands:[...n]}),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,n]of this.entries)for(let r of n.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{}}};K();K();import*as Tr from"fs/promises";async function ka(s){await Tr.writeFile(C.pidFile(),JSON.stringify(s)+`
177
179
  `,{encoding:"utf8",mode:384})}K();import*as Yt from"fs/promises";import*as Vn from"path";var Kt=s=>{process.stderr.write(s+`
178
- `)};function Tr(s){Kt=s??(e=>process.stderr.write(e+`
179
- `))}async function wa(s,e){let t=Ce();if(!t)return;let n=await s.load(),r=new Map;for(let d of n.agents)r.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=Vn.join(A.agentsDir(),t),a;try{a=await Yt.readdir(i,{withFileTypes:!0})}catch(d){let u=d;if(u.code==="ENOENT")return;Kt(`hydra-acp: prune: failed to read ${i}: ${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 l=o.get(u)??new Set,p=Vn.join(i,u),f;try{f=await Yt.readdir(p,{withFileTypes:!0})}catch(h){Kt(`hydra-acp: prune: failed to read ${p}: ${h.message}`);continue}for(let h of f){if(!h.isDirectory())continue;let g=h.name;if(g===c||l.has(g)||g.includes(".partial-"))continue;let m=Vn.join(p,g);try{await Yt.rm(m,{recursive:!0,force:!0}),Kt(`hydra-acp: pruned stale ${u} ${g} (${m})`)}catch(y){Kt(`hydra-acp: prune: failed to remove ${m}: ${y.message}`)}}}}function ka(s){let e,t=!1,n=0,r=(a,d)=>{s.logger&&s.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let c=await s.registry.load();for(let l of c.agents)await _s(l)==="yes"&&a.push(l.id)}catch(c){return r("warn",`registry load failed: ${c.message}`),s.intervalMs}if(a.length===0)return s.intervalMs;let d=n%a.length;n=(n+1)%a.length;let u=a[d];try{let{synced:c,skipped:l}=await s.manager.syncFromAgent(u);r("info",`${u}: synced ${c.length}, skipped ${l}`)}catch(c){r("warn",`${u}: ${c.message}`)}return Math.max(1,Math.floor(s.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),i(s.intervalMs)})},a),e.unref())};return i(s.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function _r(s){let e=s.maxDeletions??200,t=(f,h)=>{s.logger&&s.logger[f](`session-gc: ${h}`)},n=Date.now(),r=s.maxAgeMs>0?n-s.maxAgeMs:Number.POSITIVE_INFINITY,o=await s.manager.list({includeNonInteractive:!0}).catch(f=>(t("warn",`manager.list failed: ${f.message}`),[])),i=[];for(let f of o){if(f.status!=="cold")continue;if((s.selection??"explicit")==="explicit"){if(f.interactive!==!1)continue}else if(f.interactive===!0)continue;let g=Date.parse(f.updatedAt);Number.isFinite(g)&&(s.maxAgeMs>0&&g>r||i.push({sessionId:f.sessionId,lastUsedMs:g}))}if(i.length===0)return s.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((f,h)=>f.lastUsedMs-h.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,u=0,c=0;for(let{sessionId:f}of a)try{await s.manager.deleteRecord(f,"expired")&&(u+=1)}catch(h){c+=1,t("warn",`delete ${f} failed: ${h.message}`)}let l=i.length-a.length;if(s.verbose||u>0||c>0){let f=(s.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${u} ${f} session(s) older than ${Sf(s.maxAgeMs)}`+(c>0?`; ${c} failed`:"")+(l>0?`; ${l} deferred to next sweep`:""))}let p={considered:i.length,deleted:u,failed:c,deferred:l};return d!==void 0&&(p.oldestLastUsedMs=d),p}function ba(s){let e,t=!1,n=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!n){n=!0;try{await _r({manager:s.manager,maxAgeMs:s.maxAgeMs,selection:"unpromoted",...s.maxDeletionsPerSweep!==void 0?{maxDeletions:s.maxDeletionsPerSweep}:{},...s.logger?{logger:s.logger}:{}})}finally{n=!1}}})().catch(a=>{s.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(s.intervalMs)})},o),e.unref())};return r(s.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Sf(s){if(s<=0)return"any age";let e=s/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=s/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as If}from"crypto";function $r(s){if(Array.isArray(s))return s.map($r);if(s!==null&&typeof s=="object"){let e={};for(let t of Object.keys(s).sort())e[t]=$r(s[t]);return e}return s}function va(s){let{tui:e,...t}=s,n=JSON.stringify($r(t));return If("sha256").update(n).digest("hex").slice(0,16)}K();Oe();import*as Aa from"path";import{createHash as Af,randomBytes as Cf,timingSafeEqual as xf}from"crypto";var Ca="hydra_session_",Rf=3600*24*30,Sa=12,Ef=32,Pf=50;function Mf(){return Aa.join(A.home(),"session-tokens.json")}function Ia(s){return Af("sha256").update(s).digest("hex")}function xa(s){return Cf(s).toString("hex")}function Tf(){return xa(Sa).slice(0,Sa*2)}function _f(){return`${Ca}${xa(Ef)}`}var Qn=class s{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let n of e)this.records.set(n.hash,n)}static async load(){let e=[],t=Mf(),n=await ee(t);n&&Array.isArray(n.records)&&(e=n.records.filter($f));let r=new s(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=_f(),n=Ia(t),r=Tf(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:Rf,a=new Date(o.getTime()+i*1e3),d={id:r,hash:n,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(n,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Ca))return;let t=Ia(e),n=this.records.get(t);if(!n)return;let r=Buffer.from(n.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!xf(r,o))return;let i=new Date;if(new Date(n.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return n.lastUsedAt=i.toISOString(),this.scheduleWrite(),n.id}async revoke(e){for(let[t,n]of this.records)if(n.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:n,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:n,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[n,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(n),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(()=>{})},Pf))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>fe(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 $f(s){if(!s||typeof s!="object")return!1;let e=s;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 Ra="Bearer ",Gn=class{constructor(e){this.token=e}token;async validate(e){return Ff(e,this.token)?"service":void 0}},Kn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Yn=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let n=await t.validate(e);if(n!==void 0)return n}}};function Ea(s){return async function(t,n){let r=t.headers.authorization;if(!r||!r.startsWith(Ra)){n.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Ra.length).trim(),i=await s.validator.validate(o);if(!i){n.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function Pa(s){let e=s.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let n of t.split(",")){let r=n.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(s.url)try{let r=new URL(s.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Xn=class{tokens=new Map;mint(e,t){let n=ys();return this.tokens.set(n,{name:e,kind:t}),n}revoke(e){for(let[t,n]of this.tokens)n.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 Ff(s,e){if(s.length!==e.length)return!1;let t=0;for(let n=0;n<s.length;n+=1)t|=s.charCodeAt(n)^e.charCodeAt(n);return t===0}var Zn=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(),n=this.entries.get(e);if(!n||t-n.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}n.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,n]of this.entries)e-n.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Dr from"fs";import*as sd from"os";import*as os from"path";import*as Lr from"readline";K();function Fr(s){return Math.floor(s/4)}function Ma(s){let e=0,t=new Map;for(let n of s){let r=n.params;if(!r||typeof r!="object")continue;let o=r.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=Xe(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=Nf(i),u=t.get(a)??0;d>u&&t.set(a,d);break}default:break}}for(let n of t.values())e+=n;return e}function Nf(s){let e=0;return typeof s.title=="string"&&(e+=s.title.length),e+=es(s.rawInput),e+=Xe(s.content),e+=es(s.rawOutput),e}function es(s){if(s==null)return 0;if(typeof s=="string")return s.length;if(typeof s=="number"||typeof s=="boolean")return String(s).length;if(Array.isArray(s)){let e=0;for(let t of s)e+=es(t);return e}if(typeof s=="object"){let e=s.bytes;if(typeof s.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let n of Object.values(s))t+=es(n);return t}return 0}function Xe(s){if(s==null)return 0;if(typeof s=="string")return s.length;if(Array.isArray(s)){let t=0;for(let n of s)t+=Xe(n);return t}if(typeof s!="object")return 0;let e=s;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?Xe(e.text):e.type==="diff"?Xe(e.oldText)+Xe(e.newText):e.content!==void 0?Xe(e.content):0}function Ta(s){if(s.compactionInFlight||s.totalEntries===0)return!1;let e,t;if(typeof s.agentReportedUsed=="number"&&typeof s.agentReportedSize=="number"&&s.agentReportedSize>0)e=s.agentReportedUsed/s.agentReportedSize,t=!0;else{let r=Fr(s.unsummarizedChars),o=s.currentModel!==void 0?s.config.modelContextWindows[s.currentModel]??s.config.absoluteFallback:s.config.absoluteFallback;e=r/o,t=!1}if(t&&e>=s.config.hardCeilingFraction)return!0;let n=s.nowMs-s.lastActivityMs;return e>=s.config.contextFraction&&n>=s.config.idleBeforePromptMs}K();import{posix as Of}from"path";import Hf from"strip-ansi";function Xt(s){if(!s||typeof s!="object")return;let e=s;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var jf=/[\x00-\x08\x0b-\x1f\x7f]/g;function we(s){return Hf(s).replace(jf,"")}function Z(s){return we(s).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Na(s,e={}){if(!s||typeof s!="object")return null;let t=s,n=t.sessionUpdate??t.kind;if(typeof n!="string")return null;switch(n){case"agent_message_chunk":return zf(t);case"agent_thought_chunk":case"agent_thought":return Jf(t);case"user_message_chunk":return Vf(t);case"prompt_received":return Qf(t);case"tool_call":return Gf(t,e);case"tool_call_update":return ep(t,e);case"plan":return rp(t);case"current_mode_update":return op(t);case"current_model_update":return ip(t);case"turn_complete":return ap(t);case"turn_started":return Fa(t,"turn-started");case"turn_ended":return Fa(t,"turn-ended");case"usage_update":return qf(t);case"available_commands_update":return Uf(t);case"available_modes_update":return Wf(t);case"session_info_update":return Lf(t);case"config_option_update":return Df(t);default:return{kind:"unknown",sessionUpdate:n,raw:s}}}function Df(s){let e=s.configOptions;if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Lf(s){let e=X(s,"title"),t=e!==void 0?Z(e):void 0,n=s._meta,r,o;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=n["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"?o=u:u===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function Bf(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t;if(typeof n.name!="string"||n.name.length===0)continue;let r=n.name.startsWith("/")?n.name:`/${n.name}`,o={name:Z(r)};typeof n.description=="string"&&(o.description=Z(n.description)),e.push(o)}return e}function Uf(s){let e=s.availableCommands??s.commands;return Array.isArray(e)?{kind:"available-commands",commands:Bf(e)}:null}function Wf(s){let e=s.availableModes;if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:Z(r.id)};typeof r.name=="string"&&(o.name=Z(r.name)),typeof r.description=="string"&&(o.description=Z(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function qf(s){let e={kind:"usage-update"};if(typeof s.used=="number"&&(e.used=s.used),typeof s.size=="number"&&(e.size=s.size),s.cost&&typeof s.cost=="object"){let t=s.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function zf(s){let e=Zt(s.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Xt(s)}}function Jf(s){let e=typeof s.text=="string"?we(s.text):Zt(s.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Xt(s)}}function Vf(s){let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e["hydra-acp"];if(n&&typeof n=="object"&&!Array.isArray(n)&&n.compatFor==="prompt_received")return null}let t=Zt(s.content);return t===null?null:{kind:"user-text",text:t}}function Qf(s){let e=dp(s.prompt);return e===null?null:{kind:"user-text",text:e}}function Oa(s){return s?s.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function _a(s){if(typeof s=="string")return{text:s};if(s&&typeof s=="object"&&!Array.isArray(s)){let e=s;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function ts(s){let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="diff")continue;let o=_a(r.oldText),i=_a(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=s.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t,r=typeof n.file_path=="string"?n.file_path:typeof n.path=="string"?n.path:void 0;if(typeof n.old_string=="string"&&typeof n.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:n.old_string,newText:n.new_string};if(typeof n.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:n.content}}return null}function Ha(s){let e=s.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:we(t)}function Gf(s,e={}){let t=X(s,"toolCallId")??X(s,"id");if(!t)return null;let n=X(s,"title")??X(s,"name")??X(s,"label")??"tool call",r=X(s,"name")??X(s,"title");if(Oa(r)){let h=Ha(s);if(h!==null){let g=X(s,"status"),m={kind:"exit-plan-mode",toolCallId:t,plan:h};return g!==void 0&&(m.status=g),m}}let o=La(Z(n),s,e),i=X(s,"status"),a=X(s,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let u=ts(s);u!==null&&(d.editDiff=u);let c=Da(s);c!==void 0&&(d.detail=c);let l=Nr(s);l!==void 0&&(d.detailFull=l);let p=ja(s);p!==void 0&&(d.locations=p);let f=Xt(s);return f!==void 0&&(d.workerTaskId=f),d}function ja(s){let e=s.locations;if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var $a=64;function Da(s){let e=Nr(s);if(e===void 0)return;let t=Z(e),n=s.rawInput;return n&&typeof n.command=="string"?Xf(t,$a):Zf(t,$a)}function Nr(s){let e=s.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return we(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let n=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(n!==void 0&&n.length>0)return P(Z(n))}if(Array.isArray(s.locations)){for(let t of s.locations)if(t&&typeof t=="object"){let n=t.path;if(typeof n=="string"&&n.length>0)return P(Z(n))}}}var Kf=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Yf(s){for(let e of Kf)if(s.startsWith(e))return!0;return!1}function La(s,e,t={}){if(s.length===0)return s;if(s.startsWith("/"))return P(s);if(s.startsWith("~")||!s.includes("/")||/\s/.test(s))return s;let n=e.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${s}`||i.endsWith(`/${s}`)||i===s))return P(i)}return Yf(s)?P(`/${s}`):t.cwd&&t.cwd.length>0?P(Of.resolve(t.cwd,s)):s}function Xf(s,e){return s.length>e?`${s.slice(0,e-1)}\u2026`:s}function Zf(s,e){if(s.length<=e)return s;let t=s.slice(-(e-1)),n=t.indexOf("/");return n>=0&&n<e/2?`\u2026${t.slice(n)}`:`\u2026${t}`}function ep(s,e={}){let t=X(s,"toolCallId")??X(s,"id");if(!t)return null;let n=X(s,"title"),r=n!==void 0?La(Z(n),s,e):void 0,o=X(s,"status"),i=ts(s),a=Da(s),d=tp(s);if(!(r!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let c=X(s,"name")??n;if(Oa(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Ha(s);return m!==null&&(g.plan=m),o!==void 0&&(g.status=o),g}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let p=Nr(s);p!==void 0&&(l.detailFull=p);let f=ja(s);if(f!==void 0&&(l.locations=f),d!==void 0&&(l.resultSummary=d),o!==void 0&&(l.status=o),i!==null&&(l.editDiff=i),o==="failed"){let g=np(s);g!==null&&(l.errorText=g),sp(s,g)&&(l.upstreamInterrupted=!0)}let h=Xt(s);return h!==void 0&&(l.workerTaskId=h),l}function tp(s){if(!s||typeof s!="object")return;let e=s.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=c=>{let l=t[c];return typeof l=="number"&&Number.isFinite(l)?l:void 0},r=(c,l,p=`${l}s`)=>`${c} ${c===1?l:p}`,o=[],i=n("totalMatches");i!==void 0&&o.push(r(i,"match","matches"));let a=n("totalFiles");a!==void 0&&o.push(r(a,"file"));let d=n("referenceCount");d!==void 0&&o.push(r(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let u=n("exitCode");return u!==void 0&&u!==0&&o.push(`exit ${u}`),o.length>0?o.join(", "):void 0}function np(s){let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let o=Zt(n.content);if(o!==null&&o.length>0)return o}let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.error;if(typeof n=="string"&&n.length>0)return we(n)}return null}function sp(s,e){let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.metadata;if(n&&typeof n=="object"&&n.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function rp(s){let e=s.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=typeof r.content=="string"?Z(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function op(s){let e=X(s,"currentModeId")??X(s,"currentMode")??X(s,"mode");return e?{kind:"mode-changed",mode:Z(e)}:null}function ip(s){let e=X(s,"currentModel")??X(s,"model");if(!e)return null;let t=s.availableModels,n=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:Z(e),...n&&n.length>0?{availableModels:n}:{}}}function ap(s){let e=X(s,"stopReason"),t=s._meta,n=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),n&&(r.amended=!0),r}function Fa(s,e){let n=s._meta?.["hydra-acp"],r=n?.unsolicited===!0;if(e==="turn-started"){let i=n?.cause?.label,a={kind:e,unsolicited:r};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:r};return typeof n?.reason=="string"&&(o.reason=n.reason),o}function Zt(s){if(typeof s=="string")return we(s);if(!s||typeof s!="object")return null;let e=s;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?we(e.text):null}function dp(s){if(!Array.isArray(s))return null;let e=[];for(let t of s){let n=Zt(t);n!==null&&e.push(n)}return e.length===0?null:e.join("")}function X(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Ba(s){let e=new Map,t=new Map;for(let r of s){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,u=up(i);if(u.length===0)continue;let c=u;if(d!==void 0){let l=e.get(d)??[],p=[];for(let f of u)l.some(h=>h.path===f.path&&h.oldText===f.oldText&&h.newText===f.newText)||p.push(f);if(p.length===0)continue;e.set(d,[...l,...p]),c=p}for(let l of c)cp(t,l)}let n=[];for(let[r,o]of t)n.push({path:r,hunks:o.hunks,created:o.created});return n}function Ua(s){let e=[];for(let t of s){let n=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){n=o;break}if(n===-1){e.push(t);continue}let r=e[n];e.splice(n,1,{oldText:r.oldText,newText:t.newText})}return e}function cp(s,e){let t={oldText:e.oldText,newText:e.newText},n=s.get(e.path);if(n===void 0){s.set(e.path,{hunks:[t],created:e.oldText.length===0});return}n.hunks.push(t)}function up(s){let e=[],t=s.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let u=d,c=typeof u.old_string=="string"?u.old_string:void 0,l=typeof u.new_string=="string"?u.new_string:void 0;c===void 0||l===void 0||e.push({path:i,oldText:c,newText:l})}if(e.length>0)return e}}let n=s.content;if(Array.isArray(n)){for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",u=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:u})}if(e.length>0)return e}let r=ts(s);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function qa(s,e={}){let t=fp(s),{events:n,window:r}=lp(t,e),o=pp(n),i=[];gp(i,s),r&&(r.from>1||r.to<r.total)&&(i.push(`_Showing turns ${r.from}-${r.to} of ${r.total}._`),i.push("")),hp(i,n,o,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let a=i.join(`
180
+ `)};function _r(s){Kt=s??(e=>process.stderr.write(e+`
181
+ `))}async function ba(s,e){let t=Ce();if(!t)return;let n=await s.load(),r=new Map;for(let d of n.agents)r.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=Vn.join(C.agentsDir(),t),a;try{a=await Yt.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;Kt(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,u=r.get(c);if(u===void 0)continue;let l=o.get(c)??new Set,f=Vn.join(i,c),p;try{p=await Yt.readdir(f,{withFileTypes:!0})}catch(g){Kt(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===u||l.has(m)||m.includes(".partial-"))continue;let h=Vn.join(f,m);try{await Yt.rm(h,{recursive:!0,force:!0}),Kt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){Kt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function va(s){let e,t=!1,n=0,r=(a,d)=>{s.logger&&s.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let u=await s.registry.load();for(let l of u.agents)await _s(l)==="yes"&&a.push(l.id)}catch(u){return r("warn",`registry load failed: ${u.message}`),s.intervalMs}if(a.length===0)return s.intervalMs;let d=n%a.length;n=(n+1)%a.length;let c=a[d];try{let{synced:u,skipped:l}=await s.manager.syncFromAgent(c);r("info",`${c}: synced ${u.length}, skipped ${l}`)}catch(u){r("warn",`${c}: ${u.message}`)}return Math.max(1,Math.floor(s.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),i(s.intervalMs)})},a),e.unref())};return i(s.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function $r(s){let e=s.maxDeletions??200,t=(p,g)=>{s.logger&&s.logger[p](`session-gc: ${g}`)},n=Date.now(),r=s.maxAgeMs>0?n-s.maxAgeMs:Number.POSITIVE_INFINITY,o=await s.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((s.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(s.maxAgeMs>0&&m>r||i.push({sessionId:p.sessionId,lastUsedMs:m}))}if(i.length===0)return s.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,c=0,u=0;for(let{sessionId:p}of a)try{await s.manager.deleteRecord(p,"expired")&&(c+=1)}catch(g){u+=1,t("warn",`delete ${p} failed: ${g.message}`)}let l=i.length-a.length;if(s.verbose||c>0||u>0){let p=(s.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Ep(s.maxAgeMs)}`+(u>0?`; ${u} failed`:"")+(l>0?`; ${l} deferred to next sweep`:""))}let f={considered:i.length,deleted:c,failed:u,deferred:l};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Sa(s){let e,t=!1,n=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!n){n=!0;try{await $r({manager:s.manager,maxAgeMs:s.maxAgeMs,selection:"unpromoted",...s.maxDeletionsPerSweep!==void 0?{maxDeletions:s.maxDeletionsPerSweep}:{},...s.logger?{logger:s.logger}:{}})}finally{n=!1}}})().catch(a=>{s.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(s.intervalMs)})},o),e.unref())};return r(s.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Ep(s){if(s<=0)return"any age";let e=s/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=s/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as Pp}from"crypto";function Fr(s){if(Array.isArray(s))return s.map(Fr);if(s!==null&&typeof s=="object"){let e={};for(let t of Object.keys(s).sort())e[t]=Fr(s[t]);return e}return s}function Ia(s){let{tui:e,...t}=s,n=JSON.stringify(Fr(t));return Pp("sha256").update(n).digest("hex").slice(0,16)}K();Oe();import*as xa from"path";import{createHash as Mp,randomBytes as Tp,timingSafeEqual as _p}from"crypto";var Ra="hydra_session_",$p=3600*24*30,Aa=12,Fp=32,Np=50;function Op(){return xa.join(C.home(),"session-tokens.json")}function Ca(s){return Mp("sha256").update(s).digest("hex")}function Ea(s){return Tp(s).toString("hex")}function Hp(){return Ea(Aa).slice(0,Aa*2)}function jp(){return`${Ra}${Ea(Fp)}`}var Gn=class s{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let n of e)this.records.set(n.hash,n)}static async load(){let e=[],t=Op(),n=await ee(t);n&&Array.isArray(n.records)&&(e=n.records.filter(Up));let r=new s(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=jp(),n=Ca(t),r=Hp(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:$p,a=new Date(o.getTime()+i*1e3),d={id:r,hash:n,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(n,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Ra))return;let t=Ca(e),n=this.records.get(t);if(!n)return;let r=Buffer.from(n.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!_p(r,o))return;let i=new Date;if(new Date(n.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return n.lastUsedAt=i.toISOString(),this.scheduleWrite(),n.id}async revoke(e){for(let[t,n]of this.records)if(n.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:n,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:n,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[n,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(n),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(()=>{})},Np))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>fe(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 Up(s){if(!s||typeof s!="object")return!1;let e=s;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 Pa="Bearer ",Qn=class{constructor(e){this.token=e}token;async validate(e){return Dp(e,this.token)?"service":void 0}},Kn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Yn=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let n=await t.validate(e);if(n!==void 0)return n}}};function Ma(s){return async function(t,n){let r=t.headers.authorization;if(!r||!r.startsWith(Pa)){n.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Pa.length).trim(),i=await s.validator.validate(o);if(!i){n.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function Ta(s){let e=s.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let n of t.split(",")){let r=n.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(s.url)try{let r=new URL(s.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Xn=class{tokens=new Map;mint(e,t){let n=ys();return this.tokens.set(n,{name:e,kind:t}),n}revoke(e){for(let[t,n]of this.tokens)n.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 Dp(s,e){if(s.length!==e.length)return!1;let t=0;for(let n=0;n<s.length;n+=1)t|=s.charCodeAt(n)^e.charCodeAt(n);return t===0}var Zn=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(),n=this.entries.get(e);if(!n||t-n.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}n.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,n]of this.entries)e-n.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Dr from"fs";import*as od from"os";import*as os from"path";import*as Br from"readline";K();function Nr(s){return Math.floor(s/4)}function _a(s){let e=0,t=new Map;for(let n of s){let r=n.params;if(!r||typeof r!="object")continue;let o=r.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=Ze(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=Bp(i),c=t.get(a)??0;d>c&&t.set(a,d);break}default:break}}for(let n of t.values())e+=n;return e}function Bp(s){let e=0;return typeof s.title=="string"&&(e+=s.title.length),e+=es(s.rawInput),e+=Ze(s.content),e+=es(s.rawOutput),e}function es(s){if(s==null)return 0;if(typeof s=="string")return s.length;if(typeof s=="number"||typeof s=="boolean")return String(s).length;if(Array.isArray(s)){let e=0;for(let t of s)e+=es(t);return e}if(typeof s=="object"){let e=s.bytes;if(typeof s.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let n of Object.values(s))t+=es(n);return t}return 0}function Ze(s){if(s==null)return 0;if(typeof s=="string")return s.length;if(Array.isArray(s)){let t=0;for(let n of s)t+=Ze(n);return t}if(typeof s!="object")return 0;let e=s;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?Ze(e.text):e.type==="diff"?Ze(e.oldText)+Ze(e.newText):e.content!==void 0?Ze(e.content):0}function $a(s){if(s.compactionInFlight||s.totalEntries===0)return!1;let e,t;if(typeof s.agentReportedUsed=="number"&&typeof s.agentReportedSize=="number"&&s.agentReportedSize>0)e=s.agentReportedUsed/s.agentReportedSize,t=!0;else{let r=Nr(s.unsummarizedChars),o=s.currentModel!==void 0?s.config.modelContextWindows[s.currentModel]??s.config.absoluteFallback:s.config.absoluteFallback;e=r/o,t=!1}if(t&&e>=s.config.hardCeilingFraction)return!0;let n=s.nowMs-s.lastActivityMs;return e>=s.config.contextFraction&&n>=s.config.idleBeforePromptMs}K();import{posix as Lp}from"path";import Wp from"strip-ansi";function Xt(s){if(!s||typeof s!="object")return;let e=s;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var qp=/[\x00-\x08\x0b-\x1f\x7f]/g;function ke(s){return Wp(s).replace(qp,"")}function Z(s){return ke(s).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Ha(s,e={}){if(!s||typeof s!="object")return null;let t=s,n=t.sessionUpdate??t.kind;if(typeof n!="string")return null;switch(n){case"agent_message_chunk":return Yp(t);case"agent_thought_chunk":case"agent_thought":return Xp(t);case"user_message_chunk":return Zp(t);case"prompt_received":return ef(t);case"tool_call":return tf(t,e);case"tool_call_update":return af(t,e);case"plan":return lf(t);case"current_mode_update":return pf(t);case"current_model_update":return ff(t);case"turn_complete":return gf(t);case"turn_started":return Oa(t,"turn-started");case"turn_ended":return Oa(t,"turn-ended");case"usage_update":return Kp(t);case"available_commands_update":return Gp(t);case"available_modes_update":return Qp(t);case"session_info_update":return Jp(t);case"config_option_update":return zp(t);default:return{kind:"unknown",sessionUpdate:n,raw:s}}}function zp(s){let e=s.configOptions;if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Jp(s){let e=X(s,"title"),t=e!==void 0?Z(e):void 0,n=s._meta,r,o;if(n&&typeof n=="object"&&!Array.isArray(n)){let a=n["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(r=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function Vp(s){if(!Array.isArray(s))return[];let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t;if(typeof n.name!="string"||n.name.length===0)continue;let r=n.name.startsWith("/")?n.name:`/${n.name}`,o={name:Z(r)};typeof n.description=="string"&&(o.description=Z(n.description)),e.push(o)}return e}function Gp(s){let e=s.availableCommands??s.commands;return Array.isArray(e)?{kind:"available-commands",commands:Vp(e)}:null}function Qp(s){let e=s.availableModes;if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:Z(r.id)};typeof r.name=="string"&&(o.name=Z(r.name)),typeof r.description=="string"&&(o.description=Z(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function Kp(s){let e={kind:"usage-update"};if(typeof s.used=="number"&&(e.used=s.used),typeof s.size=="number"&&(e.size=s.size),s.cost&&typeof s.cost=="object"){let t=s.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function Yp(s){let e=Zt(s.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Xt(s)}}function Xp(s){let e=typeof s.text=="string"?ke(s.text):Zt(s.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Xt(s)}}function Zp(s){let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e["hydra-acp"];if(n&&typeof n=="object"&&!Array.isArray(n)&&n.compatFor==="prompt_received")return null}let t=Zt(s.content);return t===null?null:{kind:"user-text",text:t}}function ef(s){let e=mf(s.prompt);return e===null?null:{kind:"user-text",text:e}}function ja(s){return s?s.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Fa(s){if(typeof s=="string")return{text:s};if(s&&typeof s=="object"&&!Array.isArray(s)){let e=s;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function ts(s){let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="diff")continue;let o=Fa(r.oldText),i=Fa(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=s.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t,r=typeof n.file_path=="string"?n.file_path:typeof n.path=="string"?n.path:void 0;if(typeof n.old_string=="string"&&typeof n.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:n.old_string,newText:n.new_string};if(typeof n.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:n.content}}return null}function Ua(s){let e=s.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:ke(t)}function tf(s,e={}){let t=X(s,"toolCallId")??X(s,"id");if(!t)return null;let n=X(s,"title")??X(s,"name")??X(s,"label")??"tool call",r=X(s,"name")??X(s,"title");if(ja(r)){let g=Ua(s);if(g!==null){let m=X(s,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let o=La(Z(n),s,e),i=X(s,"status"),a=X(s,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=ts(s);c!==null&&(d.editDiff=c);let u=Ba(s);u!==void 0&&(d.detail=u);let l=Or(s);l!==void 0&&(d.detailFull=l);let f=Da(s);f!==void 0&&(d.locations=f);let p=Xt(s);return p!==void 0&&(d.workerTaskId=p),d}function Da(s){let e=s.locations;if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Na=64;function Ba(s){let e=Or(s);if(e===void 0)return;let t=Z(e),n=s.rawInput;return n&&typeof n.command=="string"?rf(t,Na):of(t,Na)}function Or(s){let e=s.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ke(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let n=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(n!==void 0&&n.length>0)return T(Z(n))}if(Array.isArray(s.locations)){for(let t of s.locations)if(t&&typeof t=="object"){let n=t.path;if(typeof n=="string"&&n.length>0)return T(Z(n))}}}var nf=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function sf(s){for(let e of nf)if(s.startsWith(e))return!0;return!1}function La(s,e,t={}){if(s.length===0)return s;if(s.startsWith("/"))return T(s);if(s.startsWith("~")||!s.includes("/")||/\s/.test(s))return s;let n=e.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${s}`||i.endsWith(`/${s}`)||i===s))return T(i)}return sf(s)?T(`/${s}`):t.cwd&&t.cwd.length>0?T(Lp.resolve(t.cwd,s)):s}function rf(s,e){return s.length>e?`${s.slice(0,e-1)}\u2026`:s}function of(s,e){if(s.length<=e)return s;let t=s.slice(-(e-1)),n=t.indexOf("/");return n>=0&&n<e/2?`\u2026${t.slice(n)}`:`\u2026${t}`}function af(s,e={}){let t=X(s,"toolCallId")??X(s,"id");if(!t)return null;let n=X(s,"title"),r=n!==void 0?La(Z(n),s,e):void 0,o=X(s,"status"),i=ts(s),a=Ba(s),d=df(s);if(!(r!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let u=X(s,"name")??n;if(ja(u)){let m={kind:"exit-plan-mode",toolCallId:t},h=Ua(s);return h!==null&&(m.plan=h),o!==void 0&&(m.status=o),m}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=Or(s);f!==void 0&&(l.detailFull=f);let p=Da(s);if(p!==void 0&&(l.locations=p),d!==void 0&&(l.resultSummary=d),o!==void 0&&(l.status=o),i!==null&&(l.editDiff=i),o==="failed"){let m=cf(s);m!==null&&(l.errorText=m),uf(s,m)&&(l.upstreamInterrupted=!0)}let g=Xt(s);return g!==void 0&&(l.workerTaskId=g),l}function df(s){if(!s||typeof s!="object")return;let e=s.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=u=>{let l=t[u];return typeof l=="number"&&Number.isFinite(l)?l:void 0},r=(u,l,f=`${l}s`)=>`${u} ${u===1?l:f}`,o=[],i=n("totalMatches");i!==void 0&&o.push(r(i,"match","matches"));let a=n("totalFiles");a!==void 0&&o.push(r(a,"file"));let d=n("referenceCount");d!==void 0&&o.push(r(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=n("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function cf(s){let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let o=Zt(n.content);if(o!==null&&o.length>0)return o}let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.error;if(typeof n=="string"&&n.length>0)return ke(n)}return null}function uf(s,e){let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.metadata;if(n&&typeof n=="object"&&n.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function lf(s){let e=s.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=typeof r.content=="string"?Z(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function pf(s){let e=X(s,"currentModeId")??X(s,"currentMode")??X(s,"mode");return e?{kind:"mode-changed",mode:Z(e)}:null}function ff(s){let e=X(s,"currentModel")??X(s,"model");if(!e)return null;let t=s.availableModels,n=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:Z(e),...n&&n.length>0?{availableModels:n}:{}}}function gf(s){let e=X(s,"stopReason"),t=s._meta,n=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),n&&(r.amended=!0),r}function Oa(s,e){let n=s._meta?.["hydra-acp"],r=n?.unsolicited===!0;if(e==="turn-started"){let i=n?.cause?.label,a={kind:e,unsolicited:r};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:r};return typeof n?.reason=="string"&&(o.reason=n.reason),o}function Zt(s){if(typeof s=="string")return ke(s);if(!s||typeof s!="object")return null;let e=s;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ke(e.text):null}function mf(s){if(!Array.isArray(s))return null;let e=[];for(let t of s){let n=Zt(t);n!==null&&e.push(n)}return e.length===0?null:e.join("")}function X(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Wa(s){let e=new Map,t=new Map;for(let r of s){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=yf(i);if(c.length===0)continue;let u=c;if(d!==void 0){let l=e.get(d)??[],f=[];for(let p of c)l.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...l,...f]),u=f}for(let l of u)hf(t,l)}let n=[];for(let[r,o]of t)n.push({path:r,hunks:o.hunks,created:o.created});return n}function qa(s){let e=[];for(let t of s){let n=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){n=o;break}if(n===-1){e.push(t);continue}let r=e[n];e.splice(n,1,{oldText:r.oldText,newText:t.newText})}return e}function hf(s,e){let t={oldText:e.oldText,newText:e.newText},n=s.get(e.path);if(n===void 0){s.set(e.path,{hunks:[t],created:e.oldText.length===0});return}n.hunks.push(t)}function yf(s){let e=[],t=s.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,u=typeof c.old_string=="string"?c.old_string:void 0,l=typeof c.new_string=="string"?c.new_string:void 0;u===void 0||l===void 0||e.push({path:i,oldText:u,newText:l})}if(e.length>0)return e}}let n=s.content;if(Array.isArray(n)){for(let o of n){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=ts(s);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Ja(s,e={}){let t=kf(s),{events:n,window:r}=wf(t,e),o=bf(n),i=[];vf(i,s),r&&(r.from>1||r.to<r.total)&&(i.push(`_Showing turns ${r.from}-${r.to} of ${r.total}._`),i.push("")),Sf(i,n,o,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let a=i.join(`
180
182
  `);return a.endsWith(`
181
183
  `)||(a+=`
182
- `),a}function Or(s,e){let t=s<0?e+s+1:s;return t<1?1:t>e?e:t}function lp(s,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:s};let n=[],r=0;for(let{event:f}of s)f.kind==="user-text"&&(r+=1),n.push(r===0?1:r);let o=Math.max(r,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=Or(o-e.last+1,o):(e.from!==void 0&&(i=Or(e.from,o)),e.to!==void 0&&(a=Or(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,u=new Set;d!==void 0&&s.forEach((f,h)=>{f.recordedAt>=d&&u.add(n[h])});let c=[],l,p;return s.forEach((f,h)=>{let g=n[h];g<i||g>a||d!==void 0&&!u.has(g)||(c.push(f),l??=g,p=g)}),{events:c,window:{from:l??i,to:p??a,total:o}}}function fp(s){let e=[];for(let t of s.history){if(t.method!=="session/update")continue;let n=t.params;if(!n||typeof n!="object")continue;let r=Na(n.update,{cwd:s.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function pp(s){let e=new Map;for(let{event:t}of s){if(t.kind==="tool-call"){let n=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??n?.status??"pending"});continue}if(t.kind==="tool-call-update"){let n=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??n.title,status:t.status??n.status})}}return e}function gp(s,e){let t=e.session,n=He(t.sessionId),r=t.title?.trim()||`Hydra session ${n}`;s.push(`# ${en(r)}`),s.push("");let o=[];o.push(`- **Session:** \`${n}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0||a.cumulativeCost!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Hr(a.size)}`:void 0;d.push(c?`${Hr(a.used)} / ${c} tokens`:`${Hr(a.used)} tokens`)}let u=vr(a);if(u!==void 0){let c=a.costCurrency??"USD";d.push(`$${u.toFixed(2)} ${c}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}s.push(o.join(`
183
- `)),s.push("")}function hp(s,e,t,n){let{includeTools:r,includeThoughts:o}=n;if(!e.some(g=>mp(g.event,o))){s.push("_No conversation history recorded._"),s.push("");return}let i=0,a="",d="",u=[],c=new Set,l=!1,p=()=>{if(u.length!==0){for(let g of u)s.push(g);s.push(""),u=[]}},f=()=>{p(),d.length>0&&(Wa(s,d.trimEnd(),"*"),s.push(""),d=""),a.length!==0&&(s.push(a.trimEnd()),s.push(""),a="")},h=()=>{l||(l=!0)};for(let{event:g}of e)switch(g.kind){case"user-text":{f(),s.push("---"),s.push(""),i+=1,Wa(s,g.text,"**"),s.push(""),l=!0;break}case"agent-text":h(),a+=g.text;break;case"agent-thought":{if(!o)break;h(),a.length>0&&(s.push(a.trimEnd()),s.push(""),a=""),d+=g.text;break}case"tool-call":{if(!r||(h(),(a.length>0||d.length>0)&&f(),c.has(g.toolCallId)))break;c.add(g.toolCallId);let m=t.get(g.toolCallId)??{title:g.title,status:g.status??"pending"};u.push(`- ${wp(m.status)} ${yp(m)}`);break}case"tool-call-update":break;case"plan":{h(),f(),s.push("**Plan:**"),s.push("");for(let m of g.entries){let y=m.status==="completed"?"[x]":"[ ]";s.push(`- ${y} ${en(m.content)}`)}s.push("");break}case"mode-changed":h(),f(),s.push(`_mode: ${en(g.mode)}_`),s.push("");break;case"model-changed":h(),f(),s.push(`_model: ${en(g.model)}_`),s.push("");break;case"turn-complete":f();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}f()}function mp(s,e){switch(s.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 yp(s){let e=s.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${en(s.title)}${t}`}function wp(s){switch(s){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}var za=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,kp=new RegExp(za);function Wa(s,e,t){if(kp.test(e)){bp(s,e);return}let n=e.split(/\n\s*\n/);for(let r=0;r<n.length;r++){let o=n[r];if(o.trim().length===0)continue;let i=o.split(`
184
- `);for(let a=0;a<i.length;a++){let d=i[a];s.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}r<n.length-1&&s.push("")}}function bp(s,e){let t=e.replace(/\s+$/,"");if(t.length===0)return;let n=0;for(let o of t.match(/`+/g)??[])n=Math.max(n,o.length);let r="`".repeat(Math.max(3,n+1));s.push(r);for(let o of t.split(`
185
- `))s.push(o);s.push(r)}function en(s){return s.replace(new RegExp(za,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function Hr(s){return s.toLocaleString("en-US")}function Ja(s){return s==="127.0.0.1"||s==="::1"||s==="localhost"||s==="[::1]"}function vp(s){let e=s.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[0]);let o="OR",i=!1,a=!1,d=[];for(let c of n){let l=c.toUpperCase();l==="AND"?i=!0:l==="OR"?a=!0:d.push(c)}i?o="AND":a&&(o="OR");let u=d.map(c=>Sp(c)).filter(c=>c.term.length>0);return{operator:o,terms:u}}function Sp(s){let e=/^(\w+):"([^"]*)"$/.exec(s);if(e)return{scope:Va(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(s);if(t)return{scope:"all",term:t[1]};let n=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(s);return n?{scope:Va(n[1]),term:n[2].trim()}:{scope:"all",term:s.trim()}}function Va(s){switch(s.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function Ip(s,e){return e==="edit"?s==="edit":s==="edit"?!1:s==="all"?!0:s==="user"?e==="user":s==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Ap=5,Cp=200,ss=72,xp=24,Rp=512;function Xa(s){return Number.isFinite(s)?Math.max(xp,Math.min(Rp,Math.floor(s))):ss}async function Za(s,e,t={}){let n=vp(e);if(n.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Ap,o=t.maxSessions??Cp,i=Xa(t.snippetWidth??ss),a=t.sessionIds?new Set(t.sessionIds):null,d=await s.list(),u=a?d.filter(p=>a.has(p.sessionId)):d,c=[],l=!1;for(let p of u){if(c.length>=o){l=!0;break}let f=await s.loadHistory(p.sessionId,{tools:"references"}).catch(()=>[]),h=Pp(f,n,r,i,Ep(p));if(h.snippets.length===0)continue;let g={sessionId:p.sessionId,cwd:p.cwd,status:p.status,updatedAt:p.updatedAt,totalMatches:h.totalMatches,snippets:h.snippets};p.title!==void 0&&(g.title=p.title),c.push(g)}return{query:e,truncated:l,results:c}}function Ep(s){let e=s.workspace?.sourceCwd;if(e===void 0||e.length===0||s.cwd.length===0)return;let t=s.cwd.endsWith("/")?s.cwd:s.cwd+"/";return n=>n.startsWith(t)?e.replace(/\/+$/,"")+"/"+n.slice(t.length):n}function Pp(s,e,t,n=ss,r){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:u,term:c}of e.terms){let l=Mp(s,c,u,t,n,r);if(e.operator==="AND"&&l.totalMatches===0)return{totalMatches:0,snippets:[]};o+=l.totalMatches,i.push(...l.snippets.slice(0,a)),d.push(...l.snippets.slice(a))}for(let u of d){if(i.length>=t)break;i.push(u)}return{totalMatches:o,snippets:i.slice(0,t)}}function Mp(s,e,t,n,r,o){let i=e.toLowerCase(),a=0,d=[],u=new Set;for(let c of s){let l=Tp(c).filter(p=>Ip(t,p.kind));for(let p of l){let f=p.text.toLowerCase();if(p.kind==="edit"){let m=o?.(p.text);if(!(Qa(p.text,e)||(m!==void 0&&m!==p.text?Qa(m,e):!1))||u.has(p.text))continue;if(u.add(p.text),a+=1,d.length<n){let k={kind:"edit",text:p.text,recordedAt:c.recordedAt};p.toolName!==void 0&&(k.toolName=p.toolName),d.push(k)}continue}let h=f.indexOf(i);if(h===-1)continue;let g=0;for(;h!==-1;)g++,h=f.indexOf(i,h+i.length);if(a+=g,d.length<n){let m=f.indexOf(i),y={kind:p.kind,text:jp(p.text,m,i.length,r),recordedAt:c.recordedAt};p.toolName!==void 0&&(y.toolName=p.toolName),d.push(y)}}}return{totalMatches:a,snippets:d}}function Tp(s){if(s.method!=="session/update")return[];let e=s.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,r=typeof n.sessionUpdate=="string"?n.sessionUpdate:n.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=ns(n.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof n.text=="string"?we(n.text):ns(n.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(Op(n))return[];let o=ns(n.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=Hp(n.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return _p(n);default:return[]}}function _p(s){let e=Ka(s,"name"),t=Ka(s,"title"),n=[];if(t!==void 0){let a=Z(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),n.push(d)}}if(e!==void 0&&e!==t){let a=Z(e);a.length>0&&n.push({kind:"tool",toolName:e,text:a})}let r=s.rawInput;if(r&&typeof r=="object"){let a=Ya(r);if(a.length>0){let d={kind:"tool-input",text:Z(a)};e!==void 0&&(d.toolName=e),n.push(d)}}for(let a of $p(s)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),n.push(d)}let o=s.locations;if(Array.isArray(o)&&o.length>0){let a=Ya(o);if(a.length>0){let d={kind:"tool-input",text:Z(a)};e!==void 0&&(d.toolName=e),n.push(d)}}let i=Fp(s);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),n.push(a)}return n}function $p(s){let e=[],t=new Set,n=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},r=s.content;if(Array.isArray(r))for(let i of r){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&n(a.path)}let o=s.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&n(typeof i.file_path=="string"?i.file_path:i.path)}return e}function Qa(s,e){let t=Ga(s.toLowerCase()),n=Ga(e.toLowerCase());if(n.length===0)return!1;if(n.startsWith("/"))return t===n||t.startsWith(n+"/");let r="/"+n,o=t.indexOf(r);for(;o!==-1;){let i=o+r.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(r,o+1)}return t===n||t.startsWith(n+"/")}function Ga(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Fp(s){if(!Np(s.status))return null;let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let o=n.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=Z(i.text);if(a.length>0)return a}}let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.error;if(typeof n=="string"){let r=Z(n);if(r.length>0)return r}}return null}function Np(s){return s==="failed"||s==="rejected"||s==="cancelled"}function Op(s){let e=s._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 ns(s){if(typeof s=="string")return we(s);if(!s||typeof s!="object"||Array.isArray(s))return"";let e=s;return typeof e.text=="string"?we(e.text):""}function Hp(s){if(!Array.isArray(s))return"";let e=[];for(let t of s){let n=ns(t);n.length>0&&e.push(n)}return e.join("")}function Ka(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Ya(s){try{return JSON.stringify(s)}catch{return""}}function jp(s,e,t,n=ss){let r=s.replace(/\s+/g," ").trim();if(r.length===0)return"";let o=r.toLowerCase(),i=s.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=Xa(n),u=Math.max(0,d-i.length),c=Math.floor(u/2),l=Math.min(c,a),p=Math.min(u-l,r.length-(a+i.length)),f=Math.max(0,a-(u-p)),h=Math.min(r.length,a+i.length+p),g=f>0?"\u2026":"",m=h<r.length?"\u2026":"";return`${g}${r.slice(f,h)}${m}`}import{randomBytes as td}from"crypto";function ed(s){let e=td(32).toString("hex");return s.tokenRegistry.reserve(e).complete(s.session),s.session.onClose(()=>{s.tokenRegistry.unbind(e)}),{name:s.name,type:"http",url:`${s.getOrigin()}/mcp/${s.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function jr(s){if(s.deps.mcpTokenRegistry===void 0||s.deps.getDaemonOrigin===void 0)return;let e=s.deps.mcpTokenRegistry,t=s.deps.getDaemonOrigin;return async n=>{let r=[...s.baselineMcpServers??[]];s.stdinEnabled&&r.push(ed({name:"hydra-acp-stdin",session:n,tokenRegistry:e,getOrigin:t})),r.push(ed({name:"hydra-acp-recall",session:n,tokenRegistry:e,getOrigin:t}));let o=xt(s.deps);return o!==void 0&&(o.bindToSession(n),r=[...r,...o.descriptors]),r}}function xt(s){if(s.extensionMcp===void 0||s.mcpTokenRegistry===void 0||s.getDaemonOrigin===void 0)return;let e=s.extensionMcp.list();if(e.length===0)return;let t=td(32).toString("hex"),n=s.mcpTokenRegistry.reserve(t),r=s.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=s.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{n.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>n.abandon(a)}}var rs=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function nd(s){if(s.publicHost&&s.publicHost.length>0)return s.publicHost;if(s.host&&!Ja(s.host))return s.port!==void 0?`${s.host}:${s.port}`:s.host}function rd(s,e,t,n={}){s.get("/v1/sessions",async u=>{let c=u.query,l=c?.includeNonInteractive==="1"||c?.includeNonInteractive==="true",p=c?.status==="warm"||c?.status==="cold"?c.status:void 0;return{sessions:await e.list({cwd:c?.cwd,includeNonInteractive:l,...p?{status:p}:{}})}}),s.get("/v1/sessions/:id",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.getOne(p);return f||(c.code(404).send({error:"session not found"}),c)}),s.post("/v1/sessions/search",async(u,c)=>{let l=u.body??{},p=typeof l.q=="string"?l.q:"";if(p.trim().length===0)return c.code(400).send({error:"q is required"}),c;let h={sessionIds:Array.isArray(l.sessionIds)?l.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0};return typeof l.snippetWidth=="number"&&(h.snippetWidth=l.snippetWidth),await Za(e,p,h)}),s.post("/v1/sessions",async(u,c)=>{let l=u.body??{},p=de(l.cwd??t.cwd),f=l.agentId??t.agentId,h=xt(n),g=h!==void 0?[...l.mcpServers??[],...h.descriptors]:l.mcpServers;try{let m=await e.create({cwd:p,agentId:f,mcpServers:g,...l.workspace!==void 0?{workspace:l.workspace}:{}});h!==void 0&&h.bindToSession(m),c.code(201).send({sessionId:m.sessionId,agentId:m.agentId,cwd:m.cwd,...m.workspace!==void 0?{workspace:m.workspace}:{},...m.workspaceError!==void 0?{workspaceError:m.workspaceError}:{}})}catch(m){h!==void 0&&h.abandon(m instanceof Error?m:void 0),c.code(500).send({error:m.message})}}),s.post("/v1/sessions/collect",async(u,c)=>{let l=u.body??{},p=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,f=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,h=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let g=await _r({manager:e,maxAgeMs:p,maxDeletions:f,selection:h,verbose:!1});c.code(200).send(g)}catch(g){c.code(500).send({error:g.message})}}),s.post("/v1/sessions/:id/kill",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(f){f.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),c.code(202).send();return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),s.post("/v1/sessions/:id/stdin/open",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(!f)return c.code(404).send({error:"session not found"}),c;let h=u.body??{},g={};(h.mode==="memory"||h.mode==="file")&&(g.mode=h.mode),typeof h.capacityBytes=="number"&&(g.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(g.fileCapBytes=h.fileCapBytes),(g.mode??"memory")==="file"&&(g.filePathFor=m=>os.join(sd.tmpdir(),`hydra-acp-stdin-${m}.log`));try{return f.openStream(g)}catch(m){return c.code(409).send({error:m.message}),c}}),s.post("/v1/sessions/:id/stdin",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(!f)return c.code(404).send({error:"session not found"}),c;let h=u.body??{},g=typeof h.chunk=="string"?h.chunk:"",m=h.eof===!0;try{return f.streamWrite(g,m)}catch(y){return c.code(409).send({error:y.message}),c}}),s.patch("/v1/sessions/:id",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=u.body??{};if(f.cwd!==void 0){if(typeof f.cwd!="string"||!os.isAbsolute(f.cwd)){c.code(400).send({error:"cwd must be an absolute path"});return}let g=await e.setCwd(p,f.cwd);if(g==="missing"){c.code(404).send({error:"session not found"});return}if(g==="not-a-directory"){c.code(400).send({error:`${f.cwd} is not a directory`});return}if(g==="live"){c.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(g==="bound"){c.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}c.code(204).send();return}if("workspace"in f){if(f.workspace!==null){c.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let g=await e.clearWorkspaceBinding(p);if(g==="missing"){c.code(404).send({error:"session not found"});return}if(g==="live"){c.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}c.code(204).send();return}if(f.priority!==void 0){let g=f.priority,m;if(g===null||g===0)m=void 0;else if(typeof g=="number"&&Number.isInteger(g)&&g>0)m=g;else{c.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,m)){c.code(404).send({error:"session not found"});return}c.code(204).send();return}if(f.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 f.title!="string"||f.title.trim().length===0){c.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,f.title)){c.code(404).send({error:"session not found"});return}c.code(204).send()}),s.delete("/v1/sessions/:id",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(f){await f.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),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()}),s.get("/v1/sessions/:id/export",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=u.query?.tools,h=f==="references"?"references":Xi(f),g=await e.exportBundle(p,h==="references"?{tools:"references"}:{});if(!g){c.code(404).send({error:"session not found"});return}let m=qt({record:g.record,history:h==="summary"?Zi(g.history,"summary"):g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,...g.toolBlobs!==void 0?{toolBlobs:g.toolBlobs}:{},hydraVersion:ie,machine:$t(),hydraHost:nd(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");c.header("Content-Disposition",`attachment; filename="${p}-${y}.hydra"`),c.code(200).send(m)}),s.get("/v1/sessions/:id/diff",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.exportBundle(p);if(!f){c.code(404).send({error:"session not found"});return}let h=u.query??{},g=h.fold==="true"||h.fold==="1",m=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(k=>k.trim()).filter(k=>k.length>0)):void 0,y=Ba(f.history);m&&(y=y.filter(k=>m.has(k.path))),g&&(y=y.map(k=>({...k,hunks:Ua(k.hunks)}))),c.code(200).send(y)}),s.get("/v1/sessions/:id/tools/:hash",async(u,c)=>{let l=u.params,p=await e.resolveCanonicalId(l.id)??l.id,f=await e.loadToolBlob(p,l.hash);if(f===null){c.code(404).send({error:"tool blob not found"});return}c.header("Content-Type","text/plain; charset=utf-8"),c.code(200).send(f)}),s.get("/v1/sessions/:id/transcript",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.exportBundle(p);if(!f){c.code(404).send({error:"session not found"});return}let h=qt({record:f.record,history:f.history,promptHistory:f.promptHistory.length>0?f.promptHistory:void 0,hydraVersion:ie,machine:$t(),hydraHost:nd(t)}),g=u.query,m=w=>w==="1"||w==="true"||w==="yes",y=w=>{let b=g?.[w];if(b===void 0||b==="")return;let v=Number(b);return Number.isFinite(v)?v:"bad"},k={};for(let w of["from","to","last","since"]){let b=y(w);if(b==="bad"){c.code(400).send({error:`${w} must be a number`});return}b!==void 0&&(k[w==="since"?"sinceMs":w]=b)}c.header("Content-Type","text/markdown; charset=utf-8"),c.code(200).send(qa(h,{includeTools:m(g?.tools),includeThoughts:m(g?.thoughts),...k}))}),s.post("/v1/sessions/:id/fork",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=u.body??{},h={};if(f.forkAt!==void 0){if(typeof f.forkAt!="string"||f.forkAt.length===0){c.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=f.forkAt}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}h.cwd=de(f.cwd)}if(f.agentId!==void 0){if(typeof f.agentId!="string"||f.agentId.length===0){c.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=f.agentId}if(f.title!==void 0){if(typeof f.title!="string"){c.code(400).send({error:"title must be a string"});return}h.title=f.title}if(f.mode!==void 0){if(f.mode!=="verbatim"&&f.mode!=="synthesis"){c.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=f.mode}if(f.model!==void 0){if(typeof f.model!="string"||f.model.length===0){c.code(400).send({error:"model must be a non-empty string"});return}h.model=f.model}try{let g=await e.forkSession(p,h);c.code(201).send(g)}catch(g){let m=g;if(m.code===C.SessionNotFound){c.code(404).send({error:m.message});return}if(m.code===C.InvalidParams||m.code===C.AgentNotInstalled){c.code(400).send({error:m.message});return}c.code(500).send({error:m.message})}}),s.post("/v1/sessions/import",async(u,c)=>{let l=u.body??{};if(l.bundle===void 0){c.code(400).send({error:"missing bundle"});return}let p;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}p=l.cwd}let f;try{f=aa(l.bundle)}catch(h){c.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(f,{replace:l.replace===!0,...p!==void 0?{cwd:p}:{}});c.code(201).send(h)}catch(h){let g=h;if(g.code===C.BundleAlreadyImported){c.code(409).send({error:"bundle already imported",existingSessionId:g.existingSessionId});return}c.code(500).send({error:g.message})}}),s.get("/v1/sessions/:id/compact/status",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p),h;if(f?h=f.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(p),h===void 0&&!await e.hasRecord(p))return c.code(404).send({error:"session not found"}),c;let g=await e.getCompactionState(p),m=await e.getRollbackBreadcrumb(p),y=!1,k,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let v=h??0,S=b.length,x=b.slice(v),R=Ma(x);k=Fr(R);let M=f?.currentModel,H=b.at(-1).recordedAt,$=f?.currentUsage;y=Ta({summarizedThroughEntry:v,totalEntries:S,unsummarizedChars:R,compactionInFlight:e.getCompactionInFlight(),currentModel:M,lastActivityMs:H,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...k!=null?{approxTokens:k}:{},...g!=null?{compactionState:g}:{},...m!=null?{rollbackBreadcrumb:m}:{}}}),s.post("/v1/sessions/:id/compact",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l;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})}),s.post("/v1/sessions/:id/compact/rollback",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l;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(f){let h=f instanceof Error?f.message:String(f);c.code(409).send({error:h})}}),s.post("/v1/sessions/:id/workspace/clean",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=u.body??{};if(f.deep!==void 0&&typeof f.deep!="boolean"){c.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(p)){c.code(404).send({error:"session not found"});return}if(e.get(p)===void 0){c.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let h=await e.runWorkspaceAction(p,"clean",void 0,{deep:f.deep===!0});c.code(202).send({report:h})}catch(h){c.code(409).send({error:h instanceof Error?h.message:String(h)})}}),s.get("/v1/sessions/:id/history",async(u,c)=>{let l=u.params.id,p=u.query,f=p?.follow==="1"||p?.follow==="true",h=await e.resolveCanonicalId(l)??l,g=e.get(h),m,y,k=!1,w=1e4,b=[];if(g){f&&(y=g.onBroadcast(S=>{c.raw.writableEnded||(k?c.raw.write(JSON.stringify(S)+`
186
- `):(b.push(S),b.length>w&&b.shift()))})),u.raw.on("close",()=>{y?.(),c.raw.writableEnded||c.raw.end()});try{m=await g.getHistorySnapshot()}catch(S){throw y?.(),S}}else{let S=await e.getHistory(h);if(S===void 0)return c.code(404).send({error:"session not found"}),c;m=S}c.raw.setHeader("Content-Type","application/x-ndjson"),c.raw.setHeader("Cache-Control","no-cache"),c.raw.statusCode=200;let v=new Set;for(let S of m??[]){c.raw.write(JSON.stringify(S)+`
187
- `);let x=S;typeof x.recordedAt=="number"&&v.add(String(x.recordedAt))}for(;b.length>0;){let S=b.splice(0,b.length);for(let x of S){let R=x,M=typeof R.recordedAt=="number"?String(R.recordedAt):"";M&&v.has(M)||c.raw.write(JSON.stringify(x)+`
188
- `)}}return k=!0,y||c.raw.end(),c});function r(u,c,l){let p=typeof u=="string"?u.trim():"";if(p.length===0)return null;let f;try{f=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!f||typeof f!="object"||Array.isArray(f))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=f;if(typeof h.recordedAt!="number"||l!==void 0&&h.recordedAt<l||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let g=h.params;if(typeof g.update!="object"||g.update===null||Array.isArray(g.update))return null;let y=g.update.sessionUpdate;return typeof y!="string"||!c.has(y)?null:{recordedAt:h.recordedAt,entry:f}}function o(u,c,l){let f=c.params.update,h={sessionId:u,ts:new Date(c.recordedAt).toISOString(),kind:l,update:f};return f.messageId!==void 0&&f.messageId!==null&&(h.messageId=f.messageId),h}async function*i(u,c,l,p){for await(let f of c){let h=r(f,l,p);if(h){let g=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:o(u,h.entry,g)}}}}async function a(u,c,l,p){let f=Lr.createInterface({input:Dr.createReadStream(c),crlfDelay:1/0}),h=i(u,f,l,p),g=await h.next(),m=g.done?null:g.value;return{sessionId:u,rl:f,gen:h,current:m,exhausted:m===null}}async function d(u){let c=await u.gen.next();c.done?(u.exhausted=!0,u.current=null):u.current=c.value}s.get("/v1/sessions/events",async(u,c)=>{let l=u.query,p=l.kinds;if(!p||p.trim().length===0)return c.code(400).send({error:"kinds parameter is required"}),c;let f=p.split(",").map(w=>w.trim());if(f.length===0)return c.code(400).send({error:"kinds parameter is required"}),c;for(let w of f)if(!rs.has(w))return c.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...rs].join(", ")}`}),c;let h=new Set(f),g;if(l.since!==void 0&&l.since.trim().length>0){let w=new Date(l.since);if(isNaN(w.getTime()))return c.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),c;g=w.getTime()}let m=await e.list({includeNonInteractive:!0}),y=g!==void 0?m.filter(w=>new Date(w.updatedAt).getTime()>=g):m;c.raw.setHeader("content-type","application/x-ndjson"),c.raw.statusCode=200;let k=[];for(let w of y)try{let b=A.historyFile(w.sessionId),v=await a(w.sessionId,b,h,g);v.exhausted||k.push(v)}catch(b){if(b.code==="ENOENT")continue;throw b}u.raw.on("close",()=>{for(let w of k)try{w.rl.close()}catch{}c.raw.writableEnded||c.raw.end()});try{for(;k.length>0;){let w=-1,b=1/0;for(let S=0;S<k.length;S++){let x=k[S];x.current!==null&&x.current.ts<b&&(b=x.current.ts,w=S)}if(w===-1)break;let v=k[w];if(c.raw.write(JSON.stringify(v.current.row)+`
189
- `),await d(v),v.exhausted){try{v.rl.close()}catch{}k.splice(w,1)}}}catch(w){for(let b of k)try{b.rl.close()}catch{}throw w}return c.raw.end(),c}),s.get("/v1/sessions/:id/events",async(u,c)=>{let l=u.params.id,p=u.query,f=await e.resolveCanonicalId(l)??l;if(!e.get(f)&&!await e.hasRecord(f))return c.code(404).send({error:"session not found"}),c;let g=p.kinds;if(!g||g.trim().length===0)return c.code(400).send({error:"kinds parameter is required"}),c;let m=g.split(",").map(S=>S.trim());if(m.length===0)return c.code(400).send({error:"kinds parameter is required"}),c;for(let S of m)if(!rs.has(S))return c.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...rs].join(", ")}`}),c;let y=new Set(m),k;if(p.since!==void 0&&p.since.trim().length>0){let S=new Date(p.since);if(isNaN(S.getTime()))return c.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),c;k=S.getTime()}let w=A.historyFile(f),b=Dr.createReadStream(w),v=Lr.createInterface({input:b,crlfDelay:1/0});c.raw.setHeader("content-type","application/x-ndjson"),c.raw.statusCode=200;try{for await(let S of v){let x=typeof S=="string"?S.trim():"";if(x.length===0)continue;let R;try{R=JSON.parse(x)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!R||typeof R!="object"||Array.isArray(R)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let M=R;if(typeof M.recordedAt!="number"||typeof M.params!="object"||M.params===null||Array.isArray(M.params))continue;let H=M.params;if(typeof H.update!="object"||H.update===null||Array.isArray(H.update))continue;let $=H.update,O=$.sessionUpdate;if(typeof O!="string"||!y.has(O)||k!==void 0&&M.recordedAt<k)continue;let W={ts:new Date(M.recordedAt).toISOString(),kind:O,update:$};$.messageId!==void 0&&$.messageId!==null&&(W.messageId=$.messageId),c.raw.write(JSON.stringify(W)+`
190
- `)}}catch(S){if(S.code==="ENOENT")return c.raw.end(),c;throw S}return c.raw.end(),c}),s.get("/v1/sessions/:id/attention",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);return!f&&!await e.hasRecord(p)?(c.code(404).send({error:"session not found"}),c):f?{flags:f.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),s.get("/v1/sessions/attention",async(u,c)=>{let l=u.query;if(!l.source||l.source.trim().length===0)return c.code(400).send({error:"source query parameter is required"}),c;let p=await e.list({includeNonInteractive:!0}),f=[];for(let h of p){let g=e.get(h.sessionId),m;g?m=g.listAttentionFlags():m=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let y of m)y.source===l.source&&f.push({...y,sessionId:h.sessionId})}return{flags:f}}),s.post("/v1/sessions/:id/attention/clear",async(u,c)=>{let l=u.params.id,p=await e.resolveCanonicalId(l)??l,h=u.body??{},g=typeof h.source=="string"?h.source:"",m=typeof h.reason=="string"?h.reason:"";if((g.length>0||m.length>0)&&!(g.length>0&&m.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}g.length===0&&m.length;let y=e.get(p);if(y){if(g.length>0&&m.length>0)y.clearAttentionFlag(g,m);else{let S=Array.from(y.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of S)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 k=e.store,w=await k.read(p);if(!w){c.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],v;if(g.length>0&&m.length>0){let S=`${g}::${m}`;v=b.filter(x=>`${x.source}::${x.reason}`!==S)}else v=[];if(v.length===b.length&&v.every((S,x)=>S.source===b[x].source&&S.reason===b[x].reason)){c.code(204).send();return}await k.write({...w,attentionFlags:v}),c.code(204).send()})}function od(s,e,t,n={}){s.get("/v1/agents",async()=>ot(e)),s.get("/v1/registry",async()=>e.load()),s.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),s.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await ye(a,[],{npmRegistry:n.npmRegistry}),u=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:u,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),s.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(u=>({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,agentId:u.agentId,cwd:u.cwd,title:u.title,updatedAt:u.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===C.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}function id(s,e,t){s.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Dp=/^[A-Za-z0-9._-]+$/;function is(s,e,t){let n=e==="extension"?"extensions":"transformers",r=`/v1/${n}`;s.get(r,async()=>({[n]:t.list()})),s.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),s.post(r,async(o,i)=>{let a=o.body??{},d=Lp(a);if("error"in d){i.code(400).send({error:d.error});return}try{let u=t.register(d.config);i.code(201).send(u)}catch(u){tn(i,u)}}),s.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){tn(i,d)}}),s.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){tn(i,d)}}),s.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){tn(i,d)}}),s.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){tn(i,d)}})}function tn(s,e){let t=e.code,n=e.message??"unknown error";if(t==="NOT_FOUND"){s.code(404).send({error:n});return}if(t==="CONFLICT"){s.code(409).send({error:n});return}s.code(500).send({error:n})}function Lp(s){let e=s.name;if(typeof e!="string"||!Dp.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=s.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let n=s.args;if(n!==void 0&&(!Array.isArray(n)||n.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=s.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=s.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:n??[],env:r??{},enabled:o===void 0?!0:o}}}function ad(s,e){is(s,"extension",e)}function dd(s,e){is(s,"transformer",e)}function cd(s,e){s.get("/v1/config",async()=>e)}import{z as Et}from"zod";K();import*as Rt from"fs/promises";import*as ud from"path";import{randomBytes as wb,scrypt as Bp,timingSafeEqual as Up}from"crypto";import{promisify as Wp}from"util";var qp=Wp(Bp);function ld(){return ud.join(A.home(),"password-hash")}var zp=128*1024*1024;async function fd(){try{return(await Rt.readFile(ld(),"utf8")).trim().length>0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function pd(s){if(typeof s!="string"||s.length===0)return!1;let e;try{e=(await Rt.readFile(ld(),"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 n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await qp(s,i,a.length,{N:n,r,p:o,maxmem:zp});return d.length!==a.length?!1:Up(d,a)}var Jp=Et.object({password:Et.string().min(1),label:Et.string().min(1).max(256).optional(),ttlSec:Et.number().int().positive().optional()}),Vp=Et.object({id:Et.string().optional()}).optional();function gd(s,e){s.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,n)=>{let r=Qp(t);if(e.rateLimiter.isBlocked(r))return n.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=Jp.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}if(!await fd())return n.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await pd(o.password))return e.rateLimiter.recordFailure(r),n.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return n.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),s.post("/v1/auth/logout",async(t,n)=>{let r;try{r=Vp.parse(t.body??void 0)}catch{return n.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return n.code(200).send({revoked:!1});let i=await e.store.revoke(o);return n.code(200).send({revoked:i})}),s.get("/v1/auth/verify",async(t,n)=>n.code(200).send({ok:!0})),s.get("/v1/auth/sessions",async(t,n)=>n.code(200).send({sessions:e.store.list()})),s.delete("/v1/auth/sessions/:id",async(t,n)=>{let r=t.params.id;return await e.store.revoke(r)?n.code(204).send():n.code(404).send({error:"Not found"})})}function Qp(s){return s.ip||"unknown"}import{nanoid as Br}from"nanoid";function hd(s){let e=[],t=[],n=!1,r=o=>{if(!n){n=!0;for(let i of t)i(o)}};return s.on("message",(o,i)=>{if(i)return;let a=o.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:C.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),s.on("close",()=>r()),s.on("error",o=>r(o)),{async send(o){if(n)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{s.send(i,u=>{if(u){d(u);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){n||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);s.once("close",a);try{s.close()}catch{a()}}),r())}}}import{randomBytes as vd}from"crypto";import*as Sd from"os";import*as Id from"path";var Gp=200;function Kp(s){if(!s||typeof s!="object")return;let e=s._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[be];if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.sentBy;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n,o={};if(typeof r.sessionId=="string"&&r.sessionId.length>0&&(o.sessionId=r.sessionId),typeof r.label=="string"&&r.label.length>0&&(o.label=r.label.slice(0,Gp)),r.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function md(s,e,t){let n=Kp(s);if(!n)return;let r={};if(n.label!==void 0&&(r.fromLabel=n.label),n.awaiting===!0&&(r.awaiting=!0),n.sessionId!==void 0){let o=await e.resolveCanonicalId(n.sessionId)??n.sessionId,i=await e.getOne(o);if(i){r.fromSession=o,i.title&&(r.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;r.depth=(a??0)+1}else t?.(n.sessionId)}if(!(r.fromSession===void 0&&r.fromLabel===void 0))return r}var nn=new Map;function yd(s,e){let t=nn.get(s);t||(t=new Set,nn.set(s,t)),t.add(e);let n=!1;return()=>{if(n)return;n=!0;let r=nn.get(s);r&&(r.delete(e),r.size===0&&nn.delete(s))}}function wd(s,e){if(s===e)return!0;let t=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(t.has(r))continue;t.add(r);let o=nn.get(r);if(o){if(o.has(s))return!0;for(let i of o)n.push(i)}}return!1}function T(s,e,t){let n=new Error(e);return n.code=s,t!==void 0&&(n.data=t),n}function tg(s){if(!s||typeof s!="object")return 512;let n=s.params?.update;if(!n)return 512;let r=512,o=n.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=n.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let 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 me(s,e,t){let n=s.get(e);if(!n)throw T(C.SessionNotFound,t??`session ${e} not found`);return n}async function as(s,e){let t=xt(s),n,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&s.mcpTokenRegistry!==void 0&&s.getDaemonOrigin!==void 0&&(n=vd(32).toString("hex"),r=s.mcpTokenRegistry.reserve(n),o={name:"hydra-acp-recall",type:"http",url:`${s.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${n}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=jr({baselineMcpServers:void 0,stdinEnabled:!1,deps:s}),u;try{u=await s.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),n!==void 0&&r!==void 0&&s.mcpTokenRegistry!==void 0){let c=n,l=s.mcpTokenRegistry;r.complete(u),u.onClose(()=>{l.unbind(c)})}return ug(u,s),Cd(u.sessionId,s),u}function Ad(s,e){s.get("/acp",{websocket:!0},async(t,n)=>{let r=Pa({headers:n.headers,url:n.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=hd(t),a=new dt(i),d={clientId:`hydra_client_${Br(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let l of d.attached.values())e.manager.get(l.sessionId)?.detach(l.clientId);d.attached.clear()});let u=(l,p)=>{if(d.attached.get(l)?.readonly)throw T(C.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async l=>{let p=Eo.parse(l??{});p.clientInfo?.name&&(d.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let f=p.clientInfo?.version;return f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f)),cg()}),o&&e.extensionCommands){let l=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let f=p??{},h=Array.isArray(f.commands)?f.commands.map(g=>{if(!g||typeof g!="object")return;let m=g;if(typeof m.verb!="string")return;let y={verb:m.verb};return typeof m.argsHint=="string"&&(y.argsHint=m.argsHint),typeof m.description=="string"&&(y.description=m.description),y}).filter(g=>g!==void 0):[];return l.register(o.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{l.clear(o.name)})}if(o&&e.extensionMcp){let l=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let h=f??{},g=typeof h.instructions=="string"?h.instructions:void 0,m=Array.isArray(h.tools)?h.tools.map(y=>{if(!y||typeof y!="object")return;let k=y;if(typeof k.name!="string"||k.name.length===0||typeof k.description!="string"||k.inputSchema===null||typeof k.inputSchema!="object")return;let w={name:k.name,description:k.description,inputSchema:k.inputSchema};return k.outputSchema!==null&&typeof k.outputSchema=="object"&&(w.outputSchema=k.outputSchema),w}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return l.register(o.name,a,g,m),{ok:!0,registered:m.length}});let p=f=>{let h=f??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw T(C.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async f=>{let h=p(f),g=f??{};if(typeof g.key!="string"||g.key.length===0)throw T(C.InvalidParams,"key is required");if(!e.manager)throw T(C.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,o.name,g.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async f=>{let h=p(f);if(!e.manager)throw T(C.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async f=>{let h=p(f),g=f??{};if(typeof g.key!="string"||g.key.length===0)throw T(C.InvalidParams,"key is required");if(g.value===void 0)throw T(C.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw T(C.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,o.name,g.key,g.value)}catch(m){throw T(C.InvalidParams,m.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async f=>{let h=p(f),g=f??{};if(typeof g.key!="string"||g.key.length===0)throw T(C.InvalidParams,"key is required");if(!e.manager)throw T(C.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,o.name,g.key),{ok:!0}}),e.extensionMcpControls){let f=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let g=h??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw T(C.InvalidParams,"refresh_session requires sessionId");return await f.notifyToolListChanged(g.sessionId,o.name),{ok:!0}})}a.onClose(()=>{l.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let f=p??{},h=Array.isArray(f.intercepts)?f.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,h),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let f=p??{},h=typeof f.sessionId=="string"?f.sessionId:void 0,g=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!h)throw T(-32602,"emit_message requires sessionId");if(!g&&y!=="client_broadcast")throw T(-32602,"emit_message requires method");let k=me(e.manager,h),w=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(w)return k.dischargeClaim(w,m),{ok:!0};if(y==="chain")return{ok:!0,response:await k.emitToChain(o.name,g,m)};if(y==="queue"){if(g!=="session/prompt")throw T(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await k.emitToQueue(o.name,m)}}if(y==="daemon")return{ok:!0,response:await k.emitToChain(o.name,g,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw T(-32602,"client_broadcast requires an envelope object");return k.broadcastClientUpdate(m),{ok:!0}}throw T(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let f=p??{},h=typeof f.sessionId=="string"?f.sessionId:void 0;if(!h)throw T(-32602,"hydra-acp/session/request_permission requires sessionId");return me(e.manager,h).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async p=>og(p,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let f=p??{},h=typeof f.agentId=="string"?f.agentId:e.defaultAgent,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,k=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,w=k&&typeof k.title=="string"?k.title:void 0,b=k&&typeof k.model=="string"?k.model:void 0;if(!g&&m){let x=e.manager.get(m);x&&(g=x.cwd)}if(!g)throw T(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let v=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:g,parentSessionId:m,interactive:v,transformChain:[],title:w,model:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async p=>{let f=p??{};if(typeof f.sessionId!="string")throw T(C.InvalidParams,"fork_session requires sessionId");let h=typeof f.forkAt=="string"?f.forkAt:void 0,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0,y=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0,k=typeof f.model=="string"&&f.model.length>0?f.model:void 0;return await e.manager.forkSession(f.sessionId,{...h!==void 0?{forkAt:h}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{},...y!==void 0?{mode:y}:{},...k!==void 0?{model:k}:{}})}),a.onRequest("session/fork",async p=>{let f=p??{};if(typeof f.sessionId!="string")throw T(C.InvalidParams,"session/fork requires sessionId");let h=typeof f.cwd=="string"?f.cwd:void 0;return{sessionId:(await e.manager.forkSession(f.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let l=async(p,f)=>{let h=p??{};if(typeof h.sessionId!="string")throw T(C.InvalidParams,`${f} requires sessionId`);let g=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,m=e.manager.get(g);if(m)return await m.close({deleteRecord:!0,by:`session/delete ${d.clientId}`}),await e.manager.waitForDeletion(g),await e.manager.hasRecord(g)&&await e.manager.deleteRecord(g),{id:g,existed:!0};let y=await e.manager.deleteRecord(g);return{id:g,existed:y}};a.onRequest("session/delete",async p=>(await l(p,"session/delete"),{})),a.onRequest("session/close",async p=>{let f=p??{};if(typeof f.sessionId!="string")throw T(C.InvalidParams,"session/close requires sessionId");u(f.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=e.manager.get(h);if(g)return await g.close({deleteRecord:!1,by:`session/close ${d.clientId}`+(d.processIdentity?` (${d.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(h))return{};throw T(C.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:f,existed:h}=await l(p,"hydra-acp/session/delete");if(!h)throw T(C.SessionNotFound,`session ${f} not found`);return{deleted:!0,sessionId:f}}),a.onRequest("hydra-acp/child_session/await",async p=>{let f=p??{},h=typeof f.childSessionId=="string"?f.childSessionId:void 0,g=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!h)throw T(-32602,"await_child requires childSessionId");let y=me(e.manager,h,`child session ${h} not found`);return new Promise(k=>{let v=[],S=[],x=0,R=!1,M,H,$=!1,O=()=>{$||($=!0,clearTimeout(W),M?.(),H?.(),k(R?{entries:v,truncated:!0}:{entries:v}))};M=y.onBroadcast(G=>{let le=tg(G);for(v.push(G),S.push(le),x+=le;v.length>0&&(v.length>1e3||x>1048576);)v.shift(),x-=S.shift()??0,R=!0;g==="turn_complete"&&G.params?.update?.sessionUpdate==="turn_complete"&&O()});let W=setTimeout(O,m);typeof W.unref=="function"&&W.unref(),H=y.onClose(()=>O())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let f=p??{},h=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!h)throw T(-32602,"close_child_session requires childSessionId");let g=e.manager.get(h);return g&&await g.close({deleteRecord:!1,by:`child_session/close ${d.clientId}`}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async p=>ig(p,o.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>ag(p,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let f=p??{},h=typeof f.token=="string"?f.token:void 0,g=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return h&&g&&e.manager.get(g)?.keepAliveClaim(h,m),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async l=>{let p=l??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw T(C.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let f=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,h=await e.manager.loadToolBlob(f,p.hash);if(h===null)throw T(C.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async l=>ng(l,e)),a.onRequest("logout",async l=>sg(l,e)),a.onRequest("session/new",async l=>{let p=Po.parse(l),f=it(l?._meta),h=Array.isArray(f.transformers)&&f.transformers.every(O=>typeof O=="string")?f.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(h)??[],m,y,k=p.mcpServers;if(f.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){m=vd(32).toString("hex"),y=e.mcpTokenRegistry.reserve(m);let W={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${m}`}]};k=[...p.mcpServers??[],W]}let w,b,v=xt(e);v!==void 0&&(k=[...k??[],...v.descriptors]);let S=jr({baselineMcpServers:p.mcpServers,stdinEnabled:f.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:p.cwd,agentId:f.agentId??e.defaultAgent,mcpServers:k,title:f.title,agentArgs:f.agentArgs,model:f.model,onInstallProgress:bd(a),transformChain:g,originatingClient:d.clientInfo,...f.interactive!==void 0?{interactive:f.interactive}:{},...f.env!==void 0?{forwardedEnv:f.env}:{},...f.workspace!==void 0?{workspace:f.workspace}:{},...S?{mintMcpServersForSwap:S}:{}})}catch(O){throw y!==void 0&&y.abandon(O instanceof Error?O:void 0),b!==void 0&&b.abandon(O instanceof Error?O:void 0),v!==void 0&&v.abandon(O instanceof Error?O:void 0),O}if(m!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let O=m,W=e.mcpTokenRegistry;y.complete(x),x.onClose(()=>{W.unbind(O)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let O=w,W=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{W.unbind(O)})}v!==void 0&&v.bindToSession(x),Cd(x.sessionId,e);let R,M;try{ls(d,x,x.sessionId),R=sn(a,x,d),{entries:M}=await x.attach(R,"full")}catch(O){throw await x.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),O}d.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:R.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let O of M){if(a.isClosed())break;await a.notify(O.method,We(O.params,O.recordedAt)).catch(()=>{})}})()});let H=ds(x),$=cs(x);return{sessionId:x.sessionId,...H?{modes:H}:{},...$?{models:$}:{},configOptions:x.buildConfigOptions(),_meta:us(e.manager,x,{clientId:R.clientId})}}),a.onRequest("session/attach",async l=>{let p=To.parse(l),f=p.clientInfo?.version;f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f));let h=it(p._meta),g=h.resume,m=h.readonly===!0,y=h.env;s.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!g} readonly=${m}`);let k=g?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(k);if(!w&&m){let $=await e.manager.loadFromDisk(k);if(!$)throw T(C.SessionNotFound,`session ${p.sessionId} not found`);let O=await e.manager.loadHistory(k),W=p.clientId??`cli_${Br(8)}`;d.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:W,readonly:!0}),s.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${W} attachedCount=${d.attached.size} replayed=${O.length}`);for(let G of O)await a.notify(G.method,We(G.params,G.recordedAt)).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:W,connectedClients:[W],historyPolicy:"full",replayed:O.length,_meta:dg($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(k),O=$;if(g&&(O={...$,hydraSessionId:p.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:$?.workspace?.path??g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!O)throw T(C.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(O.agentId,O.upstreamSessionId))throw T(C.SessionNotFound,`session ${p.sessionId} was deleted`);let W=O.originatingClient?O:{...O,originatingClient:d.clientInfo},G=y!==void 0?{...W,forwardedEnv:y}:W;w=await as(e,{...G,onInstallProgress:bd(a)})}ls(d,w,w.sessionId);let v=sn(a,w,d,p.clientInfo,p.clientId),S=h.replayMode==="drip",{entries:x,appliedPolicy:R}=await w.attach(v,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:S,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(d.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:v.clientId,readonly:m}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),s.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${v.clientId} attachedCount=${d.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${R} replayed=${x.length} readonly=${m}${S?" replayMode=drip":""}`),S){let $=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,O=750;(async()=>{let W=null;for(let G of x){let le=typeof G.recordedAt=="number"?G.recordedAt:null;if(W!==null&&le!==null){let et=Math.min(O,Math.max(0,(le-W)/$));et>0&&await new Promise(rn=>setTimeout(rn,et))}le!==null&&(W=le);try{await a.notify(G.method,We(G.params,le??void 0))}catch{return}}})()}else for(let $=0;$<x.length&&!a.isClosed();$++){let O=x[$],W=a.notify(O.method,We(O.params,O.recordedAt)).catch(()=>{});($+1)%200===0&&await W}w.replayPendingPermissions(v);let M=ds(w),H=cs(w);return{sessionId:w.sessionId,clientId:v.clientId,connectedClients:w.connectedClients(v.clientId),historyPolicy:R,replayed:x.length,...M?{modes:M}:{},...H?{models:H}:{},configOptions:w.buildConfigOptions(),_meta:us(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async l=>{let p=_o.parse(l),f=d.attached.get(p.sessionId);if(!f)throw T(C.SessionNotFound,"client not attached to that session");let h=e.manager.get(p.sessionId);return h?.detach(f.clientId),d.attached.delete(p.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[be]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async l=>{let p=$o.parse(l??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(m=>m.originatingClient?.name!==Fn).map(Fo)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw T(C.InternalError,"agent registry unavailable");return ot(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async l=>{let p=l??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw T(C.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 l=>{let p=No.parse(l);u(p.sessionId,"session/prompt");let f=await md(p,e.manager,y=>{s.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${y} sessionId=${p.sessionId}`)});if(f?.fromSession!==void 0){if((f.depth??0)>3)throw s.log.warn(`session/prompt: refusing depth ${f.depth} chain from ${f.fromSession} to ${p.sessionId}`),T(C.InvalidRequest,`message chain too deep (${f.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(f.awaiting===!0&&wd(f.fromSession,p.sessionId))throw s.log.warn(`session/prompt: refusing deadlock ${f.fromSession} -> ${p.sessionId}`),T(C.InvalidRequest,`would deadlock: ${p.sessionId} is already blocked waiting on ${f.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let h=d.attached.get(p.sessionId);if(!h)throw s.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),T(C.SessionNotFound,"not attached to session");let g=e.manager.get(p.sessionId);if(!g){let y=await e.manager.loadFromDisk(p.sessionId);if(!y)throw T(C.SessionNotFound,`session ${p.sessionId} not found`);s.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),g=await as(e,y);let k=sn(a,g,d,void 0,h.clientId);await g.attach(k,"none")}let m=f?.awaiting===!0&&f.fromSession!==void 0?yd(f.fromSession,p.sessionId):void 0;try{return await g.prompt(h.clientId,p,f)}finally{m?.()}});let c=l=>{let p;try{p=gn.parse(l)}catch(g){s.log.warn(`session/cancel: invalid params: ${g.message}`);return}let f=d.attached.get(p.sessionId);if(!f)return;if(f.readonly){s.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let h=e.manager.get(p.sessionId);h&&h.cancel(f.clientId).catch(g=>{s.log.warn(`session/cancel for ${p.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",c),a.onRequest("session/cancel",async l=>{let p=gn.parse(l);return u(p.sessionId,"session/cancel"),c(l),null}),a.onRequest("hydra-acp/prompt/cancel",async l=>{let p=Ho.parse(l);return u(p.sessionId,"hydra-acp/prompt/cancel"),me(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async l=>{let p=gn.parse(l);return u(p.sessionId,"hydra-acp/session/force_cancel"),me(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async l=>{let p=jo.parse(l);return u(p.sessionId,"hydra-acp/prompt/update"),me(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async l=>{let p=Do.parse(l);u(p.sessionId,"hydra-acp/prompt/amend");let f=d.attached.get(p.sessionId);if(!f)throw T(C.SessionNotFound,"not attached to session");return me(e.manager,p.sessionId).amendPrompt(f.clientId,p)}),a.onRequest("session/resume",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0;if(!f)throw T(C.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(f)??f,g=e.manager.get(h);if(!g){let w=await e.manager.loadFromDisk(h);if(!w)throw T(C.SessionNotFound,`session ${f} not found in memory or on disk`);g=await as(e,w)}ls(d,g,g.sessionId);let m=sn(a,g,d);await g.attach(m,"pending_only"),d.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:m.clientId,readonly:!1}),g.replayPendingPermissions(m);let y=ds(g),k=cs(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...k?{models:k}:{},configOptions:g.buildConfigOptions(),_meta:us(e.manager,g,{clientId:m.clientId})}}),a.onRequest("session/load",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0;if(!f)throw T(C.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(f)??f,g=e.manager.get(h);if(!g){let b=await e.manager.loadFromDisk(h);if(!b)throw T(C.SessionNotFound,`session ${f} not found in memory or on disk`);g=await as(e,b)}ls(d,g,g.sessionId);let m=sn(a,g,d),{entries:y}=await g.attach(m,"pending_only");d.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:m.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,We(b.params,b.recordedAt)).catch(()=>{})}g.replayPendingPermissions(m);let k=ds(g),w=cs(g);return{sessionId:g.sessionId,...k?{modes:k}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:us(e.manager,g,{clientId:m.clientId})}}),a.onRequest("session/set_model",async l=>{let p=l?.sessionId;typeof p=="string"&&u(p,"session/set_model");let f=rg(l,e.manager);if(f.kind==="error")throw s.log.warn(f.logMessage),T(f.code,f.message);if(f.kind==="no_op")return s.log.warn(f.logMessage),await a.notify("session/update",{sessionId:f.sessionId,update:{sessionUpdate:"current_model_update",currentModel:f.currentModel}}).catch(()=>{}),null;s.log.info(f.logMessage);let{modelId:h}=f,g=await f.session.forwardModelChange(h,l);return f.session.applyModelChange(h),g}),a.onRequest("session/set_mode",async l=>{let p=l,f=p?.sessionId;if(typeof f=="string"&&u(f,"session/set_mode"),!p||typeof p.sessionId!="string")throw T(C.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw T(C.InvalidParams,"session/set_mode requires string modeId");let h=me(e.manager,p.sessionId),g=await h.forwardRequest("session/set_mode",l);return h.applyModeChange(p.modeId),g}),a.onRequest("session/set_config_option",async l=>{let p=l,f=y=>T(C.InvalidParams,y),h=p?.sessionId;if(typeof h=="string"&&u(h,"session/set_config_option"),!p||typeof p.sessionId!="string")throw f("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw f("session/set_config_option requires string configId");if(typeof p.value!="string")throw f("session/set_config_option requires string value");let g=me(e.manager,p.sessionId),m=g.buildConfigOptions().find(y=>y.id===p.configId);if(!m)throw f(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!m.options.some(y=>y.value===p.value))throw f(`value ${JSON.stringify(p.value)} is not valid for configId ${JSON.stringify(p.configId)}`);switch(p.configId){case"model":{p.value!==g.currentModel&&await g.forwardModelChange(p.value),g.applyModelChange(p.value);break}case"mode":{p.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:p.sessionId,modeId:p.value}),g.applyModeChange(p.value);break}case"agent":{p.value!==g.agentId&&await g.setAgent(p.value);break}default:await g.forwardRequest("session/set_config_option",{sessionId:p.sessionId,configId:p.configId,value:p.value})}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(l,p)=>{let f=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=p.startsWith("session/"),g=p.startsWith("hydra-acp/");if(!h&&!g||l===null||typeof l!="object"||f.has(p))throw T(C.MethodNotFound,`Method not found: ${p}`);let m=l.sessionId;if(typeof m!="string")throw T(C.MethodNotFound,`Method not found: ${p}`);return u(m,p),me(e.manager,m).forwardRequest(p,l)})})}async function ng(s,e){let t=s??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw T(C.InvalidParams,"authenticate requires a non-empty methodId string");let n=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let f=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(f)}let d=a.authMethods??[],u=d.find(f=>f.id===n);if(!u){let f=d.map(h=>h.id);throw T(C.InvalidParams,`authenticate: methodId ${JSON.stringify(n)} is not advertised by agent ${a.agentId}; valid: [${f.map(h=>JSON.stringify(h)).join(", ")}]`)}let c=u._meta?.type,l=(()=>{let f=u._meta?.["terminal-auth"];if(f&&typeof f=="object"&&!Array.isArray(f))return f})();if((u.type??(c==="agent"||c==="terminal"?c:l!==void 0?"terminal":"agent"))==="terminal"){let f=(w,b)=>{if(!Array.isArray(w))throw T(C.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let v of w)if(typeof v!="string")throw T(C.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be string[]; got non-string entry ${JSON.stringify(v)}`);return w},h=await e.manager.planSpawnForAgent(a.agentId),g,m;if(l?.args!==void 0){let w=typeof l.command=="string"?l.command:void 0;g=w!==void 0&&Id.isAbsolute(w)?w:h.command,m=f(l.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?f(w.raw,w.label):[];g=h.command,m=[...h.args,...b]}let y={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(y[w]=b);Object.assign(y,h.env);let k=Sd.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${n}`),{kind:"terminal",command:g,args:m,env:y,cwd:k}}try{return await a.connection.request("authenticate",{methodId:n})}catch(f){throw Ve(f,a)}}async function sg(s,e){let n=(s??{})._meta?.["hydra-acp"],r=typeof n?.sessionId=="string"?n.sessionId:void 0,o=typeof n?.agentId=="string"?n.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function bd(s){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),s.notify(Lo,t).catch(()=>{})}}function ds(s){let e=s.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:s.currentMode??e[0].id,availableModes:t}}function cs(s){let e=s.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:s.currentModel??e[0].modelId,availableModels:t}}function rg(s,e){if(!s||typeof s!="object")return{kind:"error",code:C.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=s;if(typeof t.sessionId!="string")return{kind:"error",code:C.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:C.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let n=e.get(t.sessionId);if(!n)return{kind:"error",code:C.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=n.availableModels(),o=gt(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:n,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:n,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:n,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return n.currentModel!==void 0&&n.currentModel.length>0?{kind:"no_op",session:n,sessionId:t.sessionId,currentModel:n.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(n.currentModel)} agentId=${n.agentId} known=[${i}]`}:{kind:"error",code:C.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${n.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${n.agentId} known=[${i}] (no current model to fall back to)`}}async function og(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0;if(!r)throw T(C.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw T(C.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw T(C.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return me(t.manager,r).addTransformer(o),{ok:!0}}async function ig(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0,o=typeof n.reason=="string"?n.reason:void 0;if(!r)throw T(C.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw T(C.InvalidParams,"hydra-acp/attention/set requires string reason");return me(t.manager,r).setAttentionFlag(e,o,n.payload),{ok:!0}}async function ag(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0,o=typeof n.reason=="string"?n.reason:void 0;if(!r)throw T(C.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw T(C.InvalidParams,"hydra-acp/attention/clear requires string reason");return me(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function dg(s){let e={sessionId:s.hydraSessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,workspace:s.workspace,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:zt(s.currentUsage),forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:s.interactive,updatedAt:s.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:s.currentMode,agentArgs:s.agentArgs,availableCommands:s.agentCommands,availableModes:s.agentModes,availableModels:s.agentModels};return{[be]:pn(e,t)}}function us(s,e,t={}){let n=s.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 _t(e.agentMeta,pn(n,r))}function cg(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ie},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:_t(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 ug(s,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let n=e.transformers.resolveChain([t])[0];n&&s.addTransformer(n)}}function Cd(s,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let n of t)n.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:s}).catch(()=>{})}function sn(s,e,t,n,r){return{clientId:r??`cli_${Br(8)}`,connection:s,clientInfo:n}}function ls(s,e,t){let n=s.attached.get(t);n&&(e.detach(n.clientId),s.attached.delete(t))}var fs=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,n,r=new Promise((i,a)=>{t=i,n=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),n(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:n}=this.reserve(e);n(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let n=this.byToken.get(e);n!==void 0&&n.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let n of t.disposers)try{await n()}catch{}}}size(){return this.byToken.size}};import{randomUUID as lg}from"crypto";import{McpServer as fg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as pg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as ae}from"zod";function Ur(s){if(s.method!=="session/update")return null;let t=s.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function ue(s){return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}var xd="Bearer ";function Pt(s){let e=s.headers.authorization;if(typeof e!="string"||!e.startsWith(xd))return;let t=e.slice(xd.length).trim();return t.length>0?t:void 0}function gg(s){let e=new fg({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:ae.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let n=s.streamTail(t);return ue(n)}),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:ae.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let n=s.streamHead(t);return ue(n)}),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:ae.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:ae.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:ae.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:n,wait_ms:r})=>{let o=await s.streamRead(t,n,r);return ue(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:ae.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:ae.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:n})=>{let r=await s.streamWaitFor(t,n),o=s.streamInfo();return ue({outcome:r,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:ae.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:ae.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:ae.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:ae.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:ae.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:ae.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:ae.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:ae.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:ae.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 n={pattern:t.pattern};t.regex!==void 0&&(n.regex=t.regex),t.case_insensitive!==void 0&&(n.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(n.invert=t.invert),t.max_matches!==void 0&&(n.maxMatches=t.max_matches),t.max_bytes!==void 0&&(n.maxBytes=t.max_bytes),t.context_before!==void 0&&(n.contextBefore=t.context_before),t.context_after!==void 0&&(n.contextAfter=t.context_after),t.cursor!==void 0&&(n.cursor=t.cursor);let r=s.streamGrep(n);return ue(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=s.streamInfo();return ue(t)}),e}var hg=1e4;function Rd(s,e){let t=new Map;async function n(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let u=gg(a),c=new pg({sessionIdGenerator:()=>lg()});await u.connect(c);let l={server:u,transport:c};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(i,a){let d=Pt(i);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,f=new Promise(g=>{p=setTimeout(()=>g(void 0),hg)}),h=await Promise.race([u.sessionReady.catch(()=>{}),f]);if(p!==void 0&&clearTimeout(p),h===void 0){a.code(503).send({error:"session not ready"});return}c=h}let l=await n(d,c);a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};s.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),s.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),s.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as mg}from"crypto";import{McpServer as yg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as wg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Fe}from"zod";function kg(s){switch(s){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var Ed=2e3,Pd=2e4;function bg(s,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return ht([s]);let n=[],r=Ft(t);r!==void 0?n.push(`Tool: ${r}`):typeof t.title=="string"&&t.title.length>0&&n.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&n.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&n.push(a.path);let i=wn(t);return i!==void 0&&n.push(i),n.join(`
191
- `)}function vg(s,e){if(s.length<=148)return s;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>s.length&&(o=s.length-148,o<0&&(o=0));let a=s.slice(o,i);return o>0&&(a="\u2026"+a),i<s.length&&(a=a+"\u2026"),a}function Sg(s){let e=new yg({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. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. 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:Fe.string().min(1).describe("Case-insensitive substring to search for."),limit:Fe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Fe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:n=10,include_tool_calls:r=!0})=>{let o=await s();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return ue({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=[],a=t.toLowerCase();for await(let{entryId:u,entry:c}of o.iterRecallNewestFirst()){let l=Ur(c);if(!l)continue;let{kind:p,update:f}=l;if((p==="tool_call"||p==="tool_call_update")&&!r)continue;let h=bg(c,p,f),g=h.toLowerCase().indexOf(a);if(g<0)continue;let m=kg(p),y=vg(h,g),k=typeof c.recordedAt=="number"?String(c.recordedAt):void 0;if(i.push({entryId:u,speaker:m,snippet:y,timestamp:k}),i.length>=n)break}i.sort((u,c)=>u.entryId-c.entryId);let d=i.length>=n;return ue({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Fe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Fe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:n})=>{let r=await s();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return ue({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(n<t)throw new Error(`range: to_entry (${n}) must be >= from_entry (${t})`);let o=n-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getRecallTotalCount();if(i===0)return ue({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(n,i-1),u=a>t||d<n;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:u}};let c=await r.sliceRecallHistory(a,d),l=ht(c,{toolOutput:{maxPerCall:Ed,maxTotal:Pd}});return{content:[{type:"text",text:l}],structuredContent:{text:l,entry_count:c.length,truncated:u}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:Fe.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:Fe.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:Fe.string().optional(),limit:Fe.number().int().min(1).max(100).optional(),include_output:Fe.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:n,file_path:r,limit:o=20,include_output:i=!0})=>{let a=await s();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return ue({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 d=typeof t=="string"&&t.length>0,u=typeof n=="string"&&n.length>0,c=typeof r=="string"&&r.length>0;if(!d&&!u&&!c)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let l=new Map,p=Math.max(o*4,200);for await(let{entryId:k,entry:w}of a.iterRecallNewestFirst()){let b=Ur(w);if(!b)continue;let{kind:v,update:S}=b;if(v!=="tool_call"&&v!=="tool_call_update")continue;let x=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:`__noid_${k}`,R=l.get(x);if(R||(R={entryId:k,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},l.set(x,R)),k<R.entryId&&(R.entryId=k),!R.nameAuthoritative){let H=Ft(S);H!==void 0?(R.toolName=H,R.nameAuthoritative=!0):typeof S.name=="string"&&S.name.length>0?(R.toolName=S.name,R.nameAuthoritative=!0):v==="tool_call"&&typeof S.title=="string"&&S.title.length>0&&(R.toolName=S.title,R.nameAuthoritative=!0)}if(R.kind===void 0&&typeof S.kind=="string"&&S.kind.length>0&&(R.kind=S.kind),R.output===void 0){let H=wn(S);H!==void 0&&(R.output=H)}let M=S.rawInput;if(M&&typeof M=="object"&&!Array.isArray(M)&&Object.keys(M).length>0)for(let[H,$]of Object.entries(M))R.rawInput[H]===void 0&&(R.rawInput[H]=$);if(Array.isArray(S.locations))for(let H of S.locations){let $=H?.path;typeof $=="string"&&$.length>0&&!R.locations.includes($)&&R.locations.push($)}if(typeof S.status=="string"&&R.status==="in_progress"&&(R.status=S.status),w.recordedAt!==void 0&&R.timestamp===void 0&&(R.timestamp=String(w.recordedAt)),l.size>=p)break}let f=[...l.keys()].sort((k,w)=>l.get(k).entryId-l.get(w).entryId),h=[],g=Pd,m=!1;for(let k of f){let w=l.get(k);if(w.toolName=Ls({name:w.toolName,rawInput:w.rawInput,...w.kind!==void 0?{kind:w.kind}:{}}),d&&!w.toolName.toLowerCase().includes(t.toLowerCase())||u&&(w.kind??"").toLowerCase()!==n.toLowerCase())continue;if(c){let S=r.toLowerCase(),x=["file_path","filePath","path"],R=!1;for(let M of x){let H=w.rawInput[M];if(typeof H=="string"&&H.toLowerCase().includes(S)){R=!0;break}}if(!R){for(let M of w.locations)if(M.toLowerCase().includes(S)){R=!0;break}}if(!R)continue}let b={};for(let[S,x]of Object.entries(w.rawInput))typeof x=="string"?b[S]=x.length>500?x.slice(0,497)+"\u2026":x:(typeof x=="number"||typeof x=="boolean")&&(b[S]=x);w.locations.length>0&&b.locations===void 0&&(b.locations=w.locations);let v={entryId:w.entryId,tool:w.toolName,args:b,status:w.status,timestamp:w.timestamp};if(w.kind!==void 0&&(v.kind=w.kind),i&&w.output!==void 0){let S=w.output,x=Math.min(Ed,g);if(x<=0)m=!0;else{let R=S.length<=x?S:S.slice(0,x-1)+"\u2026";v.output=R,v.outputBytes=S.length,v.outputTruncated=R.length<S.length,g-=R.length}}if(h.push(v),h.length>=o)break}let y=h.length>=o;return ue({calls:h,truncated:y,...m?{outputBudgetExhausted:m}:{}})}),e}var Ig=1e4;function Md(s,e){let t=new Map;async function n(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let u=Sg(a),c=new wg({sessionIdGenerator:()=>mg()});await u.connect(c);let l={server:u,transport:c};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await c.close()}catch{}try{await u.close()}catch{}}),c}async function r(i,a){let d=Pt(i);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 l=await n(d,async()=>{if(u.session!==void 0)return u.session;let p,f=new Promise(g=>{p=setTimeout(()=>g(void 0),Ig)}),h=await Promise.race([u.sessionReady.catch(()=>{}),f]);if(p!==void 0&&clearTimeout(p),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};s.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),s.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),s.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var ps=class{byName=new Map;changeHandlers=[];register(e,t,n,r){this.byName.set(e,{connection:t,instructions:n,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 n of this.changeHandlers)try{n(e,t)}catch{}}};import{StreamableHTTPServerTransport as Tg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as _g}from"crypto";import{Server as Ag}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Cg,ListToolsRequestSchema as xg}from"@modelcontextprotocol/sdk/types.js";function Td(s,e,t,n){let r=typeof t=="function"?async()=>t():async()=>t,o=new Ag({name:s,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(xg,async()=>{let a=n?.peekSessionId?.();if(a!==void 0&&n?.fetchSessionTools!==void 0)try{let d=await n.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(Cg,async(a,d)=>{let u=a.params.name,c=d._meta?.progressToken??d.requestId,l=Eg(c,d.sendNotification);try{let p=await r(),f=await Pg(e.connection,s,u,a.params.arguments??{},p);return Mg(f,u)}catch(p){return Wr(p instanceof Error?p.message:String(p))}finally{l()}}),o}var Rg=15e3;function Eg(s,e,t=Rg){if(s===void 0)return()=>{};let n=0,r=setInterval(()=>{n+=1,e({method:"notifications/progress",params:{progressToken:s,progress:n}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function Pg(s,e,t,n,r){return await s.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:n,sessionId:r})}function Mg(s,e){if(s===null||typeof s!="object")return Wr(`extension ${e} returned non-object`);let t=s;return Array.isArray(t.content)?t:Wr(`extension ${e} omitted content array`)}function Wr(s){return{content:[{type:"text",text:s}],isError:!0}}var $g=1e4;function _d(s,e,t){let n=new Map;async function r(c){try{await c.transport.close()}catch{}try{await c.server.close()}catch{}}function o(c){for(let l of n.values()){let p=l.get(c);p!==void 0&&(l.delete(c),r(p))}}async function i(c,l){for(let[p,f]of n){if(e.lookup(p)?.session?.sessionId!==c)continue;let g=f.get(l);if(g!==void 0)try{await g.server.sendToolListChanged()}catch{}}}t.onChange(c=>{o(c)});async function a(c,l){let p=n.get(c);p===void 0&&(p=new Map,n.set(c,p),e.addDisposer(c,async()=>{let b=n.get(c);if(b!==void 0){n.delete(c);for(let v of b.values())await r(v)}}));let f=p.get(l);if(f!==void 0)return f.transport;let h=t.lookup(l);if(h===void 0)return;let k=Td(l,h,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 v,S=new Promise(R=>{v=setTimeout(()=>R(void 0),$g)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId},{peekSessionId:()=>e.lookup(c)?.session?.sessionId,fetchSessionTools:async b=>{let v=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!v||typeof v!="object")return;let S=v.tools;if(!Array.isArray(S))return;let x=[];for(let R of S){if(!R||typeof R!="object")continue;let M=R;if(typeof M.name!="string"||M.name.length===0||typeof M.description!="string"||M.inputSchema===null||typeof M.inputSchema!="object")continue;let H={name:M.name,description:M.description,inputSchema:M.inputSchema};M.outputSchema!==null&&typeof M.outputSchema=="object"&&(H.outputSchema=M.outputSchema),x.push(H)}return x}}),w=new Tg({sessionIdGenerator:()=>_g()});return await k.connect(w),p.set(l,{server:k,transport:w}),w}async function d(c,l){let p=Pt(c);if(p===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(p)===void 0){l.code(404).send({error:"unknown mcp token"});return}let h=c.params.name,g=await a(p,h);if(g===void 0){l.code(404).send({error:`unknown mcp server: ${h}`});return}l.hijack(),await g.handleRequest(c.raw,l.raw,c.body)}let u={config:{skipAuth:!0}};return s.post("/mcp/:name",u,async(c,l)=>{await d(c,l)}),s.get("/mcp/:name",u,async(c,l)=>{await d(c,l)}),s.delete("/mcp/:name",u,async(c,l)=>{await d(c,l)}),{notifyToolListChanged:i}}async function jd(s,e){Lg(s),co(s.daemon.scrubEnv);let t=s.daemon.tls?await Ne.readFile(de(s.daemon.tls.key)):void 0,n=s.daemon.tls?await Ne.readFile(de(s.daemon.tls.cert)):void 0;await Ne.mkdir(A.home(),{recursive:!0});let{stream:r,fileStream:o}=await jg(s.daemon.logLevel),i=Fg({logger:{level:s.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(Ng,{options:{handleProtocols:oo}}),Rs(D=>{i.log.info(D)}),Ms(D=>{i.log.info(D)});let a=await Qn.load(),d=new Zn,u=new Xn,c=new Yn([new Gn(e),new Kn(a),u]),l=Ea({validator:c});i.addHook("onRequest",async(D,Ae)=>{D.routeOptions.config?.skipAuth||D.url==="/acp"||D.url?.startsWith("/acp?")||await l(D,Ae)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let f=setInterval(()=>{d.sweepExpired()},300*1e3);f.unref();let h=new ln(s,{onFetched:()=>{wa(h,k)}});Tr(D=>i.log.info(D));let g={info:D=>i.log.info(D),warn:D=>i.log.warn(D)},m=D=>ze.spawn({...D,stderrTailBytes:s.daemon.agentStderrTailBytes,logger:g});po(s.compressToolContent);let y=new Jn,k=new Dn(h,m,void 0,{idleTimeoutMs:s.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:s.defaultModels,synopsisAgent:s.synopsisAgent,synopsisModel:s.synopsisModel,compactionAgent:s.compaction?.agent,compactionModel:s.compaction?.model,defaultTransformers:s.defaultTransformers,sessionHistoryMaxEntries:s.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:s.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:s.daemon.sessionHistoryArchiveTiers,logger:g,npmRegistry:s.npmRegistry,extensionCommands:y,defaultCwd:s.defaultCwd,disableWorkspaceSnapshots:s.disableWorkspaceSnapshots}),w=new qn(to(s),void 0,{tokenRegistry:u}),b=new zn(no(s),void 0,{tokenRegistry:u});id(i,ie,va(s));let v=new fs,S=new ps,x,R=()=>{if(x!==void 0)return x;let D=i.server.address();return x=`http://127.0.0.1:${D&&typeof D=="object"?D.port:s.daemon.port}`,x};rd(i,k,{agentId:s.defaultAgent,cwd:s.defaultCwd,publicHost:s.daemon.publicHost,host:s.daemon.host,port:s.daemon.port,compaction:s.compaction},{extensionMcp:S,mcpTokenRegistry:v,getDaemonOrigin:R}),od(i,h,k,{npmRegistry:s.npmRegistry}),ad(i,w),dd(i,b),cd(i,{defaultAgent:s.defaultAgent,defaultCwd:s.defaultCwd,defaultModels:{...s.defaultModels},...s.synopsisAgent!==void 0?{synopsisAgent:s.synopsisAgent}:{},...s.synopsisModel!==void 0?{synopsisModel:s.synopsisModel}:{},defaultTransformers:[...s.defaultTransformers]}),gd(i,{store:a,rateLimiter:d}),Rd(i,v),Md(i,v);let M=_d(i,v,S);Ad(i,{validator:c,manager:k,defaultAgent:s.defaultAgent,processRegistry:u,onExtensionVersion:(D,Ae)=>w.reportVersion(D,Ae),onTransformerVersion:(D,Ae)=>b.reportVersion(D,Ae),transformers:b,extensionCommands:y,mcpTokenRegistry:v,extensionMcp:S,extensionMcpControls:M,getDaemonOrigin:R,registry:h});let H=!!s.daemon.tls;await i.listen({host:H?"127.0.0.1":s.daemon.host,port:H?0:s.daemon.port});let $=i.server.address(),O=$&&typeof $=="object"?$.port:s.daemon.port,W,G=s.daemon.host,le=O;if(H&&t&&n){W=Dg({listenHost:s.daemon.host,listenPort:s.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:O,tlsOptions:{key:t,cert:n},logger:i.log});let D=W.address();D&&typeof D=="object"&&(le=D.port)}await Ne.mkdir(A.home(),{recursive:!0}),await ya({pid:process.pid,host:G,port:le,loopbackPort:O,startedAt:new Date().toISOString()});let et={daemonUrl:`http://127.0.0.1:${O}`,daemonHost:"127.0.0.1",daemonPort:O,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${O}/acp`,hydraHome:A.home()};w.setContext(et),b.setContext(et),await w.start(),await b.start();try{await k.reconcilePermissionFlags()}catch(D){i.log.warn(`permission flag reconcile failed: ${D.message}`)}k.resurrectPendingQueues().catch(D=>{i.log.warn(`queue replay scan failed: ${D.message}`)}),k.resumePendingCompactions().catch(D=>{i.log.warn(`compaction resume scan failed: ${D.message}`)}),k.resumePendingAgentSwaps().catch(D=>{i.log.warn(`agent-swap resume scan failed: ${D.message}`)});let rn=s.daemon.agentSyncIntervalMinutes*60*1e3,Jr=rn>0?ka({registry:h,manager:k,intervalMs:rn,logger:g}):void 0,Vr=s.daemon.sessionGcIntervalMinutes*60*1e3,Gd=s.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Qr=Vr>0?ba({manager:k,intervalMs:Vr,maxAgeMs:Gd,logger:g}):void 0;return{app:i,manager:k,registry:h,extensions:w,transformers:b,mcpTokenRegistry:v,extensionMcp:S,processRegistry:u,shutdown:async()=>{Qr&&Qr(),Jr&&Jr(),clearInterval(p),clearInterval(f);let D=async(Ae,Kd)=>{try{await Kd()}catch(hs){i.log.warn(`shutdown step ${Ae} failed: ${hs instanceof Error?hs.message:String(hs)}`)}};await D("sessionTokenStore.flush",()=>a.flush()),await D("extensions.stop",()=>w.stop()),await D("transformers.stop",()=>b.stop()),await D("manager.closeAll",()=>k.closeAll()),await D("manager.flushSynopsis",()=>k.flushSynopsis(3e4)),await D("manager.shutdownSynopsis",()=>k.shutdownSynopsis()),await D("manager.flushMetaWrites",()=>k.flushMetaWrites()),await D("manager.flushHistoryWrites",()=>k.flushHistoryWrites()),Rs(null),Ms(null),Tr(null),W&&await D("tlsTerminator.close",()=>new Promise(Ae=>W.close(()=>Ae()))),await D("app.close",()=>i.close());try{Nd.unlinkSync(A.pidFile())}catch{}await D("fileStream.flushSync",()=>o.flushSync())}}}var Fd=20;async function Hg(s,e){let t=Mt.dirname(s),n=Mt.basename(s,".log"),r=new RegExp(`^${n}\\.(\\d+)\\.log$`),o;try{o=await Ne.readdir(t)}catch{return}let i=[];for(let d of o){let u=d.match(r);u&&i.push({name:d,n:Number(u[1])})}if(i.length<=e)return;i.sort((d,u)=>d.n-u.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>Ne.unlink(Mt.join(t,d.name))))}async function jg(s){await Hg(A.logFile(),Fd);let e=await Og({file:A.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Fd,removeOtherLogFiles:!0}}),t=$d.destination(2);return{stream:$d.multistream([{stream:e,level:s},{stream:t,level:s}]),fileStream:e}}function Dg(s){let e=Hd.createServer(s.tlsOptions,t=>{let n=Od.connect({host:s.upstreamHost,port:s.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&s.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{n.destroy()}catch{}}};t.on("error",o),n.on("error",o),t.on("close",()=>o()),n.on("close",()=>o()),t.pipe(n),n.pipe(t)});return e.on("tlsClientError",t=>{s.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:s.listenHost,port:s.listenPort}),e}function Lg(s){let e=s.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!s.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}async function th(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:s}=await Promise.resolve().then(()=>(Qd(),Vd));s();let e=await vs(),t=await Gr(),n=await jd(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
184
+ `),a}function Hr(s,e){let t=s<0?e+s+1:s;return t<1?1:t>e?e:t}function wf(s,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:s};let n=[],r=0;for(let{event:p}of s)p.kind==="user-text"&&(r+=1),n.push(r===0?1:r);let o=Math.max(r,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=Hr(o-e.last+1,o):(e.from!==void 0&&(i=Hr(e.from,o)),e.to!==void 0&&(a=Hr(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,c=new Set;d!==void 0&&s.forEach((p,g)=>{p.recordedAt>=d&&c.add(n[g])});let u=[],l,f;return s.forEach((p,g)=>{let m=n[g];m<i||m>a||d!==void 0&&!c.has(m)||(u.push(p),l??=m,f=m)}),{events:u,window:{from:l??i,to:f??a,total:o}}}function kf(s){let e=[];for(let t of s.history){if(t.method!=="session/update")continue;let n=t.params;if(!n||typeof n!="object")continue;let r=Ha(n.update,{cwd:s.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function bf(s){let e=new Map;for(let{event:t}of s){if(t.kind==="tool-call"){let n=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??n?.status??"pending"});continue}if(t.kind==="tool-call-update"){let n=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??n.title,status:t.status??n.status})}}return e}function vf(s,e){let t=e.session,n=He(t.sessionId),r=t.title?.trim()||`Hydra session ${n}`;s.push(`# ${en(r)}`),s.push("");let o=[];o.push(`- **Session:** \`${n}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0||a.cumulativeCost!==void 0)){let d=[];if(a.used!==void 0){let u=a.size!==void 0?`${jr(a.size)}`:void 0;d.push(u?`${jr(a.used)} / ${u} tokens`:`${jr(a.used)} tokens`)}let c=vr(a);if(c!==void 0){let u=a.costCurrency??"USD";d.push(`$${c.toFixed(2)} ${u}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}s.push(o.join(`
185
+ `)),s.push("")}function Sf(s,e,t,n){let{includeTools:r,includeThoughts:o}=n;if(!e.some(m=>If(m.event,o))){s.push("_No conversation history recorded._"),s.push("");return}let i=0,a="",d="",c=[],u=new Set,l=!1,f=()=>{if(c.length!==0){for(let m of c)s.push(m);s.push(""),c=[]}},p=()=>{f(),d.length>0&&(za(s,d.trimEnd(),"*"),s.push(""),d=""),a.length!==0&&(s.push(a.trimEnd()),s.push(""),a="")},g=()=>{l||(l=!0)};for(let{event:m}of e)switch(m.kind){case"user-text":{p(),s.push("---"),s.push(""),i+=1,za(s,m.text,"**"),s.push(""),l=!0;break}case"agent-text":g(),a+=m.text;break;case"agent-thought":{if(!o)break;g(),a.length>0&&(s.push(a.trimEnd()),s.push(""),a=""),d+=m.text;break}case"tool-call":{if(!r||(g(),(a.length>0||d.length>0)&&p(),u.has(m.toolCallId)))break;u.add(m.toolCallId);let h=t.get(m.toolCallId)??{title:m.title,status:m.status??"pending"};c.push(`- ${Cf(h.status)} ${Af(h)}`);break}case"tool-call-update":break;case"plan":{g(),p(),s.push("**Plan:**"),s.push("");for(let h of m.entries){let y=h.status==="completed"?"[x]":"[ ]";s.push(`- ${y} ${en(h.content)}`)}s.push("");break}case"mode-changed":g(),p(),s.push(`_mode: ${en(m.mode)}_`),s.push("");break;case"model-changed":g(),p(),s.push(`_model: ${en(m.model)}_`),s.push("");break;case"turn-complete":p();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}p()}function If(s,e){switch(s.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 Af(s){let e=s.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${en(s.title)}${t}`}function Cf(s){switch(s){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}var Va=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,xf=new RegExp(Va);function za(s,e,t){if(xf.test(e)){Rf(s,e);return}let n=e.split(/\n\s*\n/);for(let r=0;r<n.length;r++){let o=n[r];if(o.trim().length===0)continue;let i=o.split(`
186
+ `);for(let a=0;a<i.length;a++){let d=i[a];s.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}r<n.length-1&&s.push("")}}function Rf(s,e){let t=e.replace(/\s+$/,"");if(t.length===0)return;let n=0;for(let o of t.match(/`+/g)??[])n=Math.max(n,o.length);let r="`".repeat(Math.max(3,n+1));s.push(r);for(let o of t.split(`
187
+ `))s.push(o);s.push(r)}function en(s){return s.replace(new RegExp(Va,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function jr(s){return s.toLocaleString("en-US")}function Ga(s){return s==="127.0.0.1"||s==="::1"||s==="localhost"||s==="[::1]"}function Ef(s){let e=s.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[0]);let o="OR",i=!1,a=!1,d=[];for(let u of n){let l=u.toUpperCase();l==="AND"?i=!0:l==="OR"?a=!0:d.push(u)}i?o="AND":a&&(o="OR");let c=d.map(u=>Pf(u)).filter(u=>u.term.length>0);return{operator:o,terms:c}}function Pf(s){let e=/^(\w+):"([^"]*)"$/.exec(s);if(e)return{scope:Qa(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(s);if(t)return{scope:"all",term:t[1]};let n=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(s);return n?{scope:Qa(n[1]),term:n[2].trim()}:{scope:"all",term:s.trim()}}function Qa(s){switch(s.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function Mf(s,e){return e==="edit"?s==="edit":s==="edit"?!1:s==="all"?!0:s==="user"?e==="user":s==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Tf=5,_f=200,ss=72,$f=24,Ff=512;function ed(s){return Number.isFinite(s)?Math.max($f,Math.min(Ff,Math.floor(s))):ss}async function td(s,e,t={}){let n=Ef(e);if(n.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Tf,o=t.maxSessions??_f,i=ed(t.snippetWidth??ss),a=t.sessionIds?new Set(t.sessionIds):null,d=await s.list(),c=a?d.filter(f=>a.has(f.sessionId)):d,u=[],l=!1;for(let f of c){if(u.length>=o){l=!0;break}let p=await s.loadHistory(f.sessionId,{tools:"references"}).catch(()=>[]),g=Of(p,n,r,i,Nf(f));if(g.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:g.totalMatches,snippets:g.snippets};f.title!==void 0&&(m.title=f.title),u.push(m)}return{query:e,truncated:l,results:u}}function Nf(s){let e=s.workspace?.sourceCwd;if(e===void 0||e.length===0||s.cwd.length===0)return;let t=s.cwd.endsWith("/")?s.cwd:s.cwd+"/";return n=>n.startsWith(t)?e.replace(/\/+$/,"")+"/"+n.slice(t.length):n}function Of(s,e,t,n=ss,r){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:c,term:u}of e.terms){let l=Hf(s,u,c,t,n,r);if(e.operator==="AND"&&l.totalMatches===0)return{totalMatches:0,snippets:[]};o+=l.totalMatches,i.push(...l.snippets.slice(0,a)),d.push(...l.snippets.slice(a))}for(let c of d){if(i.length>=t)break;i.push(c)}return{totalMatches:o,snippets:i.slice(0,t)}}function Hf(s,e,t,n,r,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let u of s){let l=jf(u).filter(f=>Mf(t,f.kind));for(let f of l){let p=f.text.toLowerCase();if(f.kind==="edit"){let h=o?.(f.text);if(!(Ka(f.text,e)||(h!==void 0&&h!==f.text?Ka(h,e):!1))||c.has(f.text))continue;if(c.add(f.text),a+=1,d.length<n){let k={kind:"edit",text:f.text,recordedAt:u.recordedAt};f.toolName!==void 0&&(k.toolName=f.toolName),d.push(k)}continue}let g=p.indexOf(i);if(g===-1)continue;let m=0;for(;g!==-1;)m++,g=p.indexOf(i,g+i.length);if(a+=m,d.length<n){let h=p.indexOf(i),y={kind:f.kind,text:zf(f.text,h,i.length,r),recordedAt:u.recordedAt};f.toolName!==void 0&&(y.toolName=f.toolName),d.push(y)}}}return{totalMatches:a,snippets:d}}function jf(s){if(s.method!=="session/update")return[];let e=s.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,r=typeof n.sessionUpdate=="string"?n.sessionUpdate:n.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=ns(n.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof n.text=="string"?ke(n.text):ns(n.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(Wf(n))return[];let o=ns(n.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=qf(n.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return Uf(n);default:return[]}}function Uf(s){let e=Xa(s,"name"),t=Xa(s,"title"),n=[];if(t!==void 0){let a=Z(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),n.push(d)}}if(e!==void 0&&e!==t){let a=Z(e);a.length>0&&n.push({kind:"tool",toolName:e,text:a})}let r=s.rawInput;if(r&&typeof r=="object"){let a=Za(r);if(a.length>0){let d={kind:"tool-input",text:Z(a)};e!==void 0&&(d.toolName=e),n.push(d)}}for(let a of Df(s)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),n.push(d)}let o=s.locations;if(Array.isArray(o)&&o.length>0){let a=Za(o);if(a.length>0){let d={kind:"tool-input",text:Z(a)};e!==void 0&&(d.toolName=e),n.push(d)}}let i=Bf(s);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),n.push(a)}return n}function Df(s){let e=[],t=new Set,n=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},r=s.content;if(Array.isArray(r))for(let i of r){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&n(a.path)}let o=s.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&n(typeof i.file_path=="string"?i.file_path:i.path)}return e}function Ka(s,e){let t=Ya(s.toLowerCase()),n=Ya(e.toLowerCase());if(n.length===0)return!1;if(n.startsWith("/"))return t===n||t.startsWith(n+"/");let r="/"+n,o=t.indexOf(r);for(;o!==-1;){let i=o+r.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(r,o+1)}return t===n||t.startsWith(n+"/")}function Ya(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Bf(s){if(!Lf(s.status))return null;let e=s.content;if(Array.isArray(e))for(let n of e){if(!n||typeof n!="object")continue;let o=n.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=Z(i.text);if(a.length>0)return a}}let t=s.rawOutput;if(t&&typeof t=="object"){let n=t.error;if(typeof n=="string"){let r=Z(n);if(r.length>0)return r}}return null}function Lf(s){return s==="failed"||s==="rejected"||s==="cancelled"}function Wf(s){let e=s._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 ns(s){if(typeof s=="string")return ke(s);if(!s||typeof s!="object"||Array.isArray(s))return"";let e=s;return typeof e.text=="string"?ke(e.text):""}function qf(s){if(!Array.isArray(s))return"";let e=[];for(let t of s){let n=ns(t);n.length>0&&e.push(n)}return e.join("")}function Xa(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Za(s){try{return JSON.stringify(s)}catch{return""}}function zf(s,e,t,n=ss){let r=s.replace(/\s+/g," ").trim();if(r.length===0)return"";let o=r.toLowerCase(),i=s.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=ed(n),c=Math.max(0,d-i.length),u=Math.floor(c/2),l=Math.min(u,a),f=Math.min(c-l,r.length-(a+i.length)),p=Math.max(0,a-(c-f)),g=Math.min(r.length,a+i.length+f),m=p>0?"\u2026":"",h=g<r.length?"\u2026":"";return`${m}${r.slice(p,g)}${h}`}import{randomBytes as sd}from"crypto";function nd(s){let e=sd(32).toString("hex");return s.tokenRegistry.reserve(e).complete(s.session),s.session.onClose(()=>{s.tokenRegistry.unbind(e)}),{name:s.name,type:"http",url:`${s.getOrigin()}/mcp/${s.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Ur(s){if(s.deps.mcpTokenRegistry===void 0||s.deps.getDaemonOrigin===void 0)return;let e=s.deps.mcpTokenRegistry,t=s.deps.getDaemonOrigin;return async n=>{let r=[...s.baselineMcpServers??[]];s.stdinEnabled&&r.push(nd({name:"hydra-acp-stdin",session:n,tokenRegistry:e,getOrigin:t})),r.push(nd({name:"hydra-acp-recall",session:n,tokenRegistry:e,getOrigin:t}));let o=xt(s.deps);return o!==void 0&&(o.bindToSession(n),r=[...r,...o.descriptors]),r}}function xt(s){if(s.extensionMcp===void 0||s.mcpTokenRegistry===void 0||s.getDaemonOrigin===void 0)return;let e=s.extensionMcp.list();if(e.length===0)return;let t=sd(32).toString("hex"),n=s.mcpTokenRegistry.reserve(t),r=s.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=s.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{n.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>n.abandon(a)}}var rs=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function rd(s){if(s.publicHost&&s.publicHost.length>0)return s.publicHost;if(s.host&&!Ga(s.host))return s.port!==void 0?`${s.host}:${s.port}`:s.host}function id(s,e,t,n={}){s.get("/v1/sessions",async c=>{let u=c.query,l=u?.includeNonInteractive==="1"||u?.includeNonInteractive==="true",f=u?.status==="warm"||u?.status==="cold"?u.status:void 0;return{sessions:await e.list({cwd:u?.cwd,includeNonInteractive:l,...f?{status:f}:{}})}}),s.get("/v1/sessions/:id",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.getOne(f);return p||(u.code(404).send({error:"session not found"}),u)}),s.post("/v1/sessions/search",async(c,u)=>{let l=c.body??{},f=typeof l.q=="string"?l.q:"";if(f.trim().length===0)return u.code(400).send({error:"q is required"}),u;let g={sessionIds:Array.isArray(l.sessionIds)?l.sessionIds.filter(h=>typeof h=="string"&&h.length>0):void 0};return typeof l.snippetWidth=="number"&&(g.snippetWidth=l.snippetWidth),await td(e,f,g)}),s.post("/v1/sessions",async(c,u)=>{let l=c.body??{},f=de(l.cwd??t.cwd),p=l.agentId??t.agentId,g=xt(n),m=g!==void 0?[...l.mcpServers??[],...g.descriptors]:l.mcpServers;try{let h=await e.create({cwd:f,agentId:p,mcpServers:m,...l.workspace!==void 0?{workspace:l.workspace}:{}});g!==void 0&&g.bindToSession(h),u.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd,...h.workspace!==void 0?{workspace:h.workspace}:{},...h.workspaceError!==void 0?{workspaceError:h.workspaceError}:{}})}catch(h){g!==void 0&&g.abandon(h instanceof Error?h:void 0),u.code(500).send({error:h.message})}}),s.post("/v1/sessions/collect",async(c,u)=>{let l=c.body??{},f=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,p=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,g=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let m=await $r({manager:e,maxAgeMs:f,maxDeletions:p,selection:g,verbose:!1});u.code(200).send(m)}catch(m){u.code(500).send({error:m.message})}}),s.post("/v1/sessions/:id/kill",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(p){p.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),u.code(202).send();return}if(!await e.hasRecord(f)){u.code(404).send({error:"session not found"});return}u.code(204).send()}),s.post("/v1/sessions/:id/stdin/open",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(!p)return u.code(404).send({error:"session not found"}),u;let g=c.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=>os.join(od.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return p.openStream(m)}catch(h){return u.code(409).send({error:h.message}),u}}),s.post("/v1/sessions/:id/stdin",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(!p)return u.code(404).send({error:"session not found"}),u;let g=c.body??{},m=typeof g.chunk=="string"?g.chunk:"",h=g.eof===!0;try{return p.streamWrite(m,h)}catch(y){return u.code(409).send({error:y.message}),u}}),s.patch("/v1/sessions/:id",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.body??{};if(p.cwd!==void 0){if(typeof p.cwd!="string"||!os.isAbsolute(p.cwd)){u.code(400).send({error:"cwd must be an absolute path"});return}let m=await e.setCwd(f,p.cwd);if(m==="missing"){u.code(404).send({error:"session not found"});return}if(m==="not-a-directory"){u.code(400).send({error:`${p.cwd} is not a directory`});return}if(m==="live"){u.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(m==="bound"){u.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}u.code(204).send();return}if("workspace"in p){if(p.workspace!==null){u.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let m=await e.clearWorkspaceBinding(f);if(m==="missing"){u.code(404).send({error:"session not found"});return}if(m==="live"){u.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}u.code(204).send();return}if(p.priority!==void 0){let m=p.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{u.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,h)){u.code(404).send({error:"session not found"});return}u.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){u.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),u.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){u.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){u.code(404).send({error:"session not found"});return}u.code(204).send()}),s.delete("/v1/sessions/:id",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(p){await p.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),u.code(204).send();return}if(!await e.deleteRecord(f)){u.code(404).send({error:"session not found"});return}u.code(204).send()}),s.get("/v1/sessions/:id/export",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.query?.tools,g=p==="references"?"references":ta(p),m=await e.exportBundle(f,g==="references"?{tools:"references"}:{});if(!m){u.code(404).send({error:"session not found"});return}let h=qt({record:m.record,history:g==="summary"?na(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:ie,machine:$t(),hydraHost:rd(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");u.header("Content-Disposition",`attachment; filename="${f}-${y}.hydra"`),u.code(200).send(h)}),s.get("/v1/sessions/:id/diff",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.exportBundle(f);if(!p){u.code(404).send({error:"session not found"});return}let g=c.query??{},m=g.fold==="true"||g.fold==="1",h=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(k=>k.trim()).filter(k=>k.length>0)):void 0,y=Wa(p.history);h&&(y=y.filter(k=>h.has(k.path))),m&&(y=y.map(k=>({...k,hunks:qa(k.hunks)}))),u.code(200).send(y)}),s.get("/v1/sessions/:id/tools/:hash",async(c,u)=>{let l=c.params,f=await e.resolveCanonicalId(l.id)??l.id,p=await e.loadToolBlob(f,l.hash);if(p===null){u.code(404).send({error:"tool blob not found"});return}u.header("Content-Type","text/plain; charset=utf-8"),u.code(200).send(p)}),s.get("/v1/sessions/:id/transcript",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.exportBundle(f);if(!p){u.code(404).send({error:"session not found"});return}let g=qt({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:ie,machine:$t(),hydraHost:rd(t)}),m=c.query,h=w=>w==="1"||w==="true"||w==="yes",y=w=>{let S=m?.[w];if(S===void 0||S==="")return;let I=Number(S);return Number.isFinite(I)?I:"bad"},k={};for(let w of["from","to","last","since"]){let S=y(w);if(S==="bad"){u.code(400).send({error:`${w} must be a number`});return}S!==void 0&&(k[w==="since"?"sinceMs":w]=S)}u.header("Content-Type","text/markdown; charset=utf-8"),u.code(200).send(Ja(g,{includeTools:h(m?.tools),includeThoughts:h(m?.thoughts),...k}))}),s.post("/v1/sessions/:id/fork",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.body??{},g={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){u.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){u.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=de(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){u.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){u.code(400).send({error:"title must be a string"});return}g.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){u.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){u.code(400).send({error:"model must be a non-empty string"});return}g.model=p.model}try{let m=await e.forkSession(f,g);u.code(201).send(m)}catch(m){let h=m;if(h.code===x.SessionNotFound){u.code(404).send({error:h.message});return}if(h.code===x.InvalidParams||h.code===x.AgentNotInstalled){u.code(400).send({error:h.message});return}u.code(500).send({error:h.message})}}),s.post("/v1/sessions/import",async(c,u)=>{let l=c.body??{};if(l.bundle===void 0){u.code(400).send({error:"missing bundle"});return}let f;if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){u.code(400).send({error:"cwd must be a non-empty string"});return}f=l.cwd}let p;try{p=ua(l.bundle)}catch(g){u.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(p,{replace:l.replace===!0,...f!==void 0?{cwd:f}:{}});u.code(201).send(g)}catch(g){let m=g;if(m.code===x.BundleAlreadyImported){u.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}u.code(500).send({error:m.message})}}),s.get("/v1/sessions/:id/compact/status",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f),g;if(p?g=p.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(f),g===void 0&&!await e.hasRecord(f))return u.code(404).send({error:"session not found"}),u;let m=await e.getCompactionState(f),h=await e.getRollbackBreadcrumb(f),y=!1,k,w=p?.currentUsage,S=typeof w?.used=="number"&&typeof w?.size=="number"&&w.size>0?{used:w.used,size:w.size}:void 0,I=await e.loadHistory(f,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(I.length>0&&t.compaction){let b=g??0,A=I.length,R=b<=I.length?b:0,E=I.slice(R),$=_a(E);k=Nr($);let _=p?.currentModel,M=I.at(-1).recordedAt;y=$a({summarizedThroughEntry:b,totalEntries:A,unsummarizedChars:$,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:M,nowMs:Date.now(),config:t.compaction,...typeof w?.used=="number"?{agentReportedUsed:w.used}:{},...typeof w?.size=="number"?{agentReportedSize:w.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...k!=null?{approxTokens:k}:{},...S!=null?{currentUsage:S}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),s.post("/v1/sessions/:id/compact",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(e.get(f)){e.scheduleCompaction(f),u.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){u.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),u.code(202).send({scheduled:!0})}),s.post("/v1/sessions/:id/compact/rollback",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(!await e.hasRecord(f)){u.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),u.code(202).send({rolledBack:!0})}catch(p){let g=p instanceof Error?p.message:String(p);u.code(409).send({error:g})}}),s.post("/v1/sessions/:id/workspace/clean",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.body??{};if(p.deep!==void 0&&typeof p.deep!="boolean"){u.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(f)){u.code(404).send({error:"session not found"});return}if(e.get(f)===void 0){u.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let g=await e.runWorkspaceAction(f,"clean",void 0,{deep:p.deep===!0});u.code(202).send({report:g})}catch(g){u.code(409).send({error:g instanceof Error?g.message:String(g)})}}),s.get("/v1/sessions/:id/history",async(c,u)=>{let l=c.params.id,f=c.query,p=f?.follow==="1"||f?.follow==="true",g=await e.resolveCanonicalId(l)??l,m=e.get(g),h,y,k=!1,w=1e4,S=[];if(m){p&&(y=m.onBroadcast(b=>{u.raw.writableEnded||(k?u.raw.write(JSON.stringify(b)+`
188
+ `):(S.push(b),S.length>w&&S.shift()))})),c.raw.on("close",()=>{y?.(),u.raw.writableEnded||u.raw.end()});try{h=await m.getHistorySnapshot()}catch(b){throw y?.(),b}}else{let b=await e.getHistory(g);if(b===void 0)return u.code(404).send({error:"session not found"}),u;h=b}u.raw.setHeader("Content-Type","application/x-ndjson"),u.raw.setHeader("Cache-Control","no-cache"),u.raw.statusCode=200;let I=new Set;for(let b of h??[]){u.raw.write(JSON.stringify(b)+`
189
+ `);let A=b;typeof A.recordedAt=="number"&&I.add(String(A.recordedAt))}for(;S.length>0;){let b=S.splice(0,S.length);for(let A of b){let R=A,E=typeof R.recordedAt=="number"?String(R.recordedAt):"";E&&I.has(E)||u.raw.write(JSON.stringify(A)+`
190
+ `)}}return k=!0,y||u.raw.end(),u});function r(c,u,l){let f=typeof c=="string"?c.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let g=p;if(typeof g.recordedAt!="number"||l!==void 0&&g.recordedAt<l||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"||!u.has(y)?null:{recordedAt:g.recordedAt,entry:p}}function o(c,u,l){let p=u.params.update,g={sessionId:c,ts:new Date(u.recordedAt).toISOString(),kind:l,update:p};return p.messageId!==void 0&&p.messageId!==null&&(g.messageId=p.messageId),g}async function*i(c,u,l,f){for await(let p of u){let g=r(p,l,f);if(g){let m=g.entry.params.update.sessionUpdate;yield{ts:g.recordedAt,row:o(c,g.entry,m)}}}}async function a(c,u,l,f){let p=Br.createInterface({input:Dr.createReadStream(u),crlfDelay:1/0}),g=i(c,p,l,f),m=await g.next(),h=m.done?null:m.value;return{sessionId:c,rl:p,gen:g,current:h,exhausted:h===null}}async function d(c){let u=await c.gen.next();u.done?(c.exhausted=!0,c.current=null):c.current=u.value}s.get("/v1/sessions/events",async(c,u)=>{let l=c.query,f=l.kinds;if(!f||f.trim().length===0)return u.code(400).send({error:"kinds parameter is required"}),u;let p=f.split(",").map(w=>w.trim());if(p.length===0)return u.code(400).send({error:"kinds parameter is required"}),u;for(let w of p)if(!rs.has(w))return u.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...rs].join(", ")}`}),u;let g=new Set(p),m;if(l.since!==void 0&&l.since.trim().length>0){let w=new Date(l.since);if(isNaN(w.getTime()))return u.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),u;m=w.getTime()}let h=await e.list({includeNonInteractive:!0}),y=m!==void 0?h.filter(w=>new Date(w.updatedAt).getTime()>=m):h;u.raw.setHeader("content-type","application/x-ndjson"),u.raw.statusCode=200;let k=[];for(let w of y)try{let S=C.historyFile(w.sessionId),I=await a(w.sessionId,S,g,m);I.exhausted||k.push(I)}catch(S){if(S.code==="ENOENT")continue;throw S}c.raw.on("close",()=>{for(let w of k)try{w.rl.close()}catch{}u.raw.writableEnded||u.raw.end()});try{for(;k.length>0;){let w=-1,S=1/0;for(let b=0;b<k.length;b++){let A=k[b];A.current!==null&&A.current.ts<S&&(S=A.current.ts,w=b)}if(w===-1)break;let I=k[w];if(u.raw.write(JSON.stringify(I.current.row)+`
191
+ `),await d(I),I.exhausted){try{I.rl.close()}catch{}k.splice(w,1)}}}catch(w){for(let S of k)try{S.rl.close()}catch{}throw w}return u.raw.end(),u}),s.get("/v1/sessions/:id/events",async(c,u)=>{let l=c.params.id,f=c.query,p=await e.resolveCanonicalId(l)??l;if(!e.get(p)&&!await e.hasRecord(p))return u.code(404).send({error:"session not found"}),u;let m=f.kinds;if(!m||m.trim().length===0)return u.code(400).send({error:"kinds parameter is required"}),u;let h=m.split(",").map(b=>b.trim());if(h.length===0)return u.code(400).send({error:"kinds parameter is required"}),u;for(let b of h)if(!rs.has(b))return u.code(400).send({error:`kind "${b}" is not queryable; allowed kinds: ${[...rs].join(", ")}`}),u;let y=new Set(h),k;if(f.since!==void 0&&f.since.trim().length>0){let b=new Date(f.since);if(isNaN(b.getTime()))return u.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),u;k=b.getTime()}let w=C.historyFile(p),S=Dr.createReadStream(w),I=Br.createInterface({input:S,crlfDelay:1/0});u.raw.setHeader("content-type","application/x-ndjson"),u.raw.statusCode=200;try{for await(let b of I){let A=typeof b=="string"?b.trim():"";if(A.length===0)continue;let R;try{R=JSON.parse(A)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!R||typeof R!="object"||Array.isArray(R)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let E=R;if(typeof E.recordedAt!="number"||typeof E.params!="object"||E.params===null||Array.isArray(E.params))continue;let $=E.params;if(typeof $.update!="object"||$.update===null||Array.isArray($.update))continue;let _=$.update,M=_.sessionUpdate;if(typeof M!="string"||!y.has(M)||k!==void 0&&E.recordedAt<k)continue;let W={ts:new Date(E.recordedAt).toISOString(),kind:M,update:_};_.messageId!==void 0&&_.messageId!==null&&(W.messageId=_.messageId),u.raw.write(JSON.stringify(W)+`
192
+ `)}}catch(b){if(b.code==="ENOENT")return u.raw.end(),u;throw b}return u.raw.end(),u}),s.get("/v1/sessions/:id/attention",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);return!p&&!await e.hasRecord(f)?(u.code(404).send({error:"session not found"}),u):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),s.get("/v1/sessions/attention",async(c,u)=>{let l=c.query;if(!l.source||l.source.trim().length===0)return u.code(400).send({error:"source query parameter is required"}),u;let f=await e.list({includeNonInteractive:!0}),p=[];for(let g of f){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===l.source&&p.push({...y,sessionId:g.sessionId})}return{flags:p}}),s.post("/v1/sessions/:id/attention/clear",async(c,u)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,g=c.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)){u.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(f);if(y){if(m.length>0&&h.length>0)y.clearAttentionFlag(m,h);else{let b=Array.from(y.listAttentionFlags()).map(A=>`${A.source}::${A.reason}`);for(let A of b)y.clearAttentionFlag(A.split("::")[0],A.split("::").slice(1).join("::"))}u.code(204).send();return}if(!await e.hasRecord(f)){u.code(404).send({error:"session not found"});return}let k=e.store,w=await k.read(f);if(!w){u.code(404).send({error:"session not found"});return}let S=w.attentionFlags??[],I;if(m.length>0&&h.length>0){let b=`${m}::${h}`;I=S.filter(A=>`${A.source}::${A.reason}`!==b)}else I=[];if(I.length===S.length&&I.every((b,A)=>b.source===S[A].source&&b.reason===S[A].reason)){u.code(204).send();return}await k.write({...w,attentionFlags:I}),u.code(204).send()})}function ad(s,e,t,n={}){s.get("/v1/agents",async()=>it(e)),s.get("/v1/registry",async()=>e.load()),s.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),s.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await we(a,[],{npmRegistry:n.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),s.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===x.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}function dd(s,e,t){s.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Jf=/^[A-Za-z0-9._-]+$/;function is(s,e,t){let n=e==="extension"?"extensions":"transformers",r=`/v1/${n}`;s.get(r,async()=>({[n]:t.list()})),s.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),s.post(r,async(o,i)=>{let a=o.body??{},d=Vf(a);if("error"in d){i.code(400).send({error:d.error});return}try{let c=t.register(d.config);i.code(201).send(c)}catch(c){tn(i,c)}}),s.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){tn(i,d)}}),s.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){tn(i,d)}}),s.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){tn(i,d)}}),s.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){tn(i,d)}})}function tn(s,e){let t=e.code,n=e.message??"unknown error";if(t==="NOT_FOUND"){s.code(404).send({error:n});return}if(t==="CONFLICT"){s.code(409).send({error:n});return}s.code(500).send({error:n})}function Vf(s){let e=s.name;if(typeof e!="string"||!Jf.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=s.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let n=s.args;if(n!==void 0&&(!Array.isArray(n)||n.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=s.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=s.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:n??[],env:r??{},enabled:o===void 0?!0:o}}}function cd(s,e){is(s,"extension",e)}function ud(s,e){is(s,"transformer",e)}function ld(s,e){s.get("/v1/config",async()=>e)}import{z as Et}from"zod";K();import*as Rt from"fs/promises";import*as pd from"path";import{randomBytes as Eb,scrypt as Gf,timingSafeEqual as Qf}from"crypto";import{promisify as Kf}from"util";var Yf=Kf(Gf);function fd(){return pd.join(C.home(),"password-hash")}var Xf=128*1024*1024;async function gd(){try{return(await Rt.readFile(fd(),"utf8")).trim().length>0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function md(s){if(typeof s!="string"||s.length===0)return!1;let e;try{e=(await Rt.readFile(fd(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await Yf(s,i,a.length,{N:n,r,p:o,maxmem:Xf});return d.length!==a.length?!1:Qf(d,a)}var Zf=Et.object({password:Et.string().min(1),label:Et.string().min(1).max(256).optional(),ttlSec:Et.number().int().positive().optional()}),eg=Et.object({id:Et.string().optional()}).optional();function hd(s,e){s.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,n)=>{let r=tg(t);if(e.rateLimiter.isBlocked(r))return n.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=Zf.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}if(!await gd())return n.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await md(o.password))return e.rateLimiter.recordFailure(r),n.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return n.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),s.post("/v1/auth/logout",async(t,n)=>{let r;try{r=eg.parse(t.body??void 0)}catch{return n.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return n.code(200).send({revoked:!1});let i=await e.store.revoke(o);return n.code(200).send({revoked:i})}),s.get("/v1/auth/verify",async(t,n)=>n.code(200).send({ok:!0})),s.get("/v1/auth/sessions",async(t,n)=>n.code(200).send({sessions:e.store.list()})),s.delete("/v1/auth/sessions/:id",async(t,n)=>{let r=t.params.id;return await e.store.revoke(r)?n.code(204).send():n.code(404).send({error:"Not found"})})}function tg(s){return s.ip||"unknown"}import{nanoid as Lr}from"nanoid";function yd(s){let e=[],t=[],n=!1,r=o=>{if(!n){n=!0;for(let i of t)i(o)}};return s.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:x.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),s.on("close",()=>r()),s.on("error",o=>r(o)),{async send(o){if(n)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{s.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){n||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);s.once("close",a);try{s.close()}catch{a()}}),r())}}}import{randomBytes as Id}from"crypto";import*as Ad from"os";import*as Cd from"path";var ng=200;function sg(s){if(!s||typeof s!="object")return;let e=s._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[ue];if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.sentBy;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n,o={};if(typeof r.sessionId=="string"&&r.sessionId.length>0&&(o.sessionId=r.sessionId),typeof r.label=="string"&&r.label.length>0&&(o.label=r.label.slice(0,ng)),r.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function wd(s,e,t){let n=sg(s);if(!n)return;let r={};if(n.label!==void 0&&(r.fromLabel=n.label),n.awaiting===!0&&(r.awaiting=!0),n.sessionId!==void 0){let o=await e.resolveCanonicalId(n.sessionId)??n.sessionId,i=await e.getOne(o);if(i){r.fromSession=o,i.title&&(r.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;r.depth=(a??0)+1}else t?.(n.sessionId)}if(!(r.fromSession===void 0&&r.fromLabel===void 0))return r}var nn=new Map;function kd(s,e){let t=nn.get(s);t||(t=new Set,nn.set(s,t)),t.add(e);let n=!1;return()=>{if(n)return;n=!0;let r=nn.get(s);r&&(r.delete(e),r.size===0&&nn.delete(s))}}function bd(s,e){if(s===e)return!0;let t=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(t.has(r))continue;t.add(r);let o=nn.get(r);if(o){if(o.has(s))return!0;for(let i of o)n.push(i)}}return!1}function F(s,e,t){let n=new Error(e);return n.code=s,t!==void 0&&(n.data=t),n}function dg(s){if(!s||typeof s!="object")return 512;let n=s.params?.update;if(!n)return 512;let r=512,o=n.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=n.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ye(s,e,t){let n=s.get(e);if(!n)throw F(x.SessionNotFound,t??`session ${e} not found`);return n}async function as(s,e){let t=xt(s),n,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&s.mcpTokenRegistry!==void 0&&s.getDaemonOrigin!==void 0&&(n=Id(32).toString("hex"),r=s.mcpTokenRegistry.reserve(n),o={name:"hydra-acp-recall",type:"http",url:`${s.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${n}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=Ur({baselineMcpServers:void 0,stdinEnabled:!1,deps:s}),c;try{c=await s.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(u){throw t!==void 0&&t.abandon(u instanceof Error?u:void 0),r!==void 0&&r.abandon(u instanceof Error?u:void 0),u}if(t!==void 0&&t.bindToSession(c),n!==void 0&&r!==void 0&&s.mcpTokenRegistry!==void 0){let u=n,l=s.mcpTokenRegistry;r.complete(c),c.onClose(()=>{l.unbind(u)})}return yg(c,s),Rd(c.sessionId,s),c}function xd(s,e){s.get("/acp",{websocket:!0},async(t,n)=>{let r=Ta({headers:n.headers,url:n.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=yd(t),a=new dt(i),d={clientId:`hydra_client_${Lr(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let l of d.attached.values())e.manager.get(l.sessionId)?.detach(l.clientId);d.attached.clear()});let c=(l,f)=>{if(d.attached.get(l)?.readonly)throw F(x.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async l=>{let f=Po.parse(l??{});f.clientInfo?.name&&(d.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),hg()}),o&&e.extensionCommands){let l=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return l.register(o.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{l.clear(o.name)})}if(o&&e.extensionMcp){let l=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let g=p??{},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 k=y;if(typeof k.name!="string"||k.name.length===0||typeof k.description!="string"||k.inputSchema===null||typeof k.inputSchema!="object")return;let w={name:k.name,description:k.description,inputSchema:k.inputSchema};return k.outputSchema!==null&&typeof k.outputSchema=="object"&&(w.outputSchema=k.outputSchema),w}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return l.register(o.name,a,m,h),{ok:!0,registered:h.length}});let f=p=>{let g=p??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw F(x.InvalidParams,"sessionId is required");return g.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let g=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw F(x.InvalidParams,"key is required");if(!e.manager)throw F(x.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(g,o.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let g=f(p);if(!e.manager)throw F(x.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(g,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let g=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw F(x.InvalidParams,"key is required");if(m.value===void 0)throw F(x.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw F(x.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(g,o.name,m.key,m.value)}catch(h){throw F(x.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let g=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw F(x.InvalidParams,"key is required");if(!e.manager)throw F(x.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(g,o.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=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 F(x.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,o.name),{ok:!0}})}a.onClose(()=>{l.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async f=>{let p=f??{},g=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,g),e.manager?.defaultTransformers.includes(o.name))){let m=e.transformers.resolveChain([o.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let p=f??{},g=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,h=p.envelope,y=p.route;if(!g)throw F(-32602,"emit_message requires sessionId");if(!m&&y!=="client_broadcast")throw F(-32602,"emit_message requires method");let k=ye(e.manager,g),w=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(w)return k.dischargeClaim(w,h),{ok:!0};if(y==="chain")return{ok:!0,response:await k.emitToChain(o.name,m,h)};if(y==="queue"){if(m!=="session/prompt")throw F(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await k.emitToQueue(o.name,h)}}if(y==="daemon")return{ok:!0,response:await k.emitToChain(o.name,m,h)};if(y==="client_broadcast"){if(!h||typeof h!="object")throw F(-32602,"client_broadcast requires an envelope object");return k.broadcastClientUpdate(h),{ok:!0}}throw F(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},g=typeof p.sessionId=="string"?p.sessionId:void 0;if(!g)throw F(-32602,"hydra-acp/session/request_permission requires sessionId");return ye(e.manager,g).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>pg(f,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let p=f??{},g=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,h=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,y=p._meta&&typeof p._meta=="object"?p._meta:void 0,k=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,w=k&&typeof k.title=="string"?k.title:void 0,S=k&&typeof k.model=="string"?k.model:void 0;if(!m&&h){let A=e.manager.get(h);A&&(m=A.cwd)}if(!m)throw F(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let I=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:g,cwd:m,parentSessionId:h,interactive:I,transformChain:[],title:w,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw F(x.InvalidParams,"fork_session requires sessionId");let g=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,h=typeof p.agentId=="string"?p.agentId:void 0,y=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,k=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...g!==void 0?{forkAt:g}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{},...y!==void 0?{mode:y}:{},...k!==void 0?{model:k}:{}})}),a.onRequest("session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw F(x.InvalidParams,"session/fork requires sessionId");let g=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...g!==void 0?{cwd:g}:{},mode:"verbatim"})).sessionId}});let l=async(f,p)=>{let g=f??{};if(typeof g.sessionId!="string")throw F(x.InvalidParams,`${p} 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,by:`session/delete ${d.clientId}`}),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 f=>(await l(f,"session/delete"),{})),a.onRequest("session/close",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw F(x.InvalidParams,"session/close requires sessionId");c(p.sessionId,"session/close");let g=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(g);if(m)return await m.close({deleteRecord:!1,by:`session/close ${d.clientId}`+(d.processIdentity?` (${d.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(g))return{};throw F(x.SessionNotFound,`session ${g} not found`)}),a.onRequest("hydra-acp/session/delete",async f=>{let{id:p,existed:g}=await l(f,"hydra-acp/session/delete");if(!g)throw F(x.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let p=f??{},g=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",h=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!g)throw F(-32602,"await_child requires childSessionId");let y=ye(e.manager,g,`child session ${g} not found`);return new Promise(k=>{let I=[],b=[],A=0,R=!1,E,$,_=!1,M=()=>{_||(_=!0,clearTimeout(W),E?.(),$?.(),k(R?{entries:I,truncated:!0}:{entries:I}))};E=y.onBroadcast(Q=>{let pe=dg(Q);for(I.push(Q),b.push(pe),A+=pe;I.length>0&&(I.length>1e3||A>1048576);)I.shift(),A-=b.shift()??0,R=!0;m==="turn_complete"&&Q.params?.update?.sessionUpdate==="turn_complete"&&M()});let W=setTimeout(M,h);typeof W.unref=="function"&&W.unref(),$=y.onClose(()=>M())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let p=f??{},g=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!g)throw F(-32602,"close_child_session requires childSessionId");let m=e.manager.get(g);return m&&await m.close({deleteRecord:!1,by:`child_session/close ${d.clientId}`}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>fg(f,o.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>gg(f,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let p=f??{},g=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,h=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return g&&m&&e.manager.get(m)?.keepAliveClaim(g,h),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async l=>{let f=l??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw F(x.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=await e.manager.loadToolBlob(p,f.hash);if(g===null)throw F(x.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async l=>cg(l,e)),a.onRequest("logout",async l=>ug(l,e)),a.onRequest("session/new",async l=>{let f=Mo.parse(l),p=Qe(l?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(M=>typeof M=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,k=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Id(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let W={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};k=[...f.mcpServers??[],W]}let w,S,I=xt(e);I!==void 0&&(k=[...k??[],...I.descriptors]);let b=Ur({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),A;try{A=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:k,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Sd(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...p.workspace!==void 0?{workspace:p.workspace}:{},...b?{mintMcpServersForSwap:b}:{}})}catch(M){throw y!==void 0&&y.abandon(M instanceof Error?M:void 0),S!==void 0&&S.abandon(M instanceof Error?M:void 0),I!==void 0&&I.abandon(M instanceof Error?M:void 0),M}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let M=h,W=e.mcpTokenRegistry;y.complete(A),A.onClose(()=>{W.unbind(M)})}if(w!==void 0&&S!==void 0&&e.mcpTokenRegistry!==void 0){let M=w,W=e.mcpTokenRegistry;S.complete(A),A.onClose(()=>{W.unbind(M)})}I!==void 0&&I.bindToSession(A),Rd(A.sessionId,e);let R,E;try{ls(d,A,A.sessionId),R=sn(a,A,d),{entries:E}=await A.attach(R,"full")}catch(M){throw await A.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),M}d.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:R.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let M of E){if(a.isClosed())break;await a.notify(M.method,We(M.params,M.recordedAt)).catch(()=>{})}})()});let $=ds(A),_=cs(A);return{sessionId:A.sessionId,...$?{modes:$}:{},..._?{models:_}:{},configOptions:A.buildConfigOptions(),_meta:us(e.manager,A,{clientId:R.clientId})}}),a.onRequest("session/attach",async l=>{let f=_o.parse(l),p=f.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let g=Qe(f._meta),m=g.resume,h=g.readonly===!0,y=g.env;s.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${h}`);let k=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,w=e.manager.get(k);if(!w&&h){let _=await e.manager.loadFromDisk(k);if(!_)throw F(x.SessionNotFound,`session ${f.sessionId} not found`);let M=await e.manager.loadHistory(k),W=f.clientId??`cli_${Lr(8)}`;d.attached.set(_.hydraSessionId,{sessionId:_.hydraSessionId,clientId:W,readonly:!0}),s.log.info(`session/attach OK (viewer) sessionId=${_.hydraSessionId} clientId=${W} attachedCount=${d.attached.size} replayed=${M.length}`);for(let Q of M)await a.notify(Q.method,We(Q.params,Q.recordedAt)).catch(()=>{});return{sessionId:_.hydraSessionId,clientId:W,connectedClients:[W],historyPolicy:"full",replayed:M.length,_meta:mg(_)}}let S=!w;if(!w){let _=await e.manager.loadFromDisk(k),M=_;if(m&&(M={..._,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:_?.workspace?.path??m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!M)throw F(x.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(M.agentId,M.upstreamSessionId))throw F(x.SessionNotFound,`session ${f.sessionId} was deleted`);let W=M.originatingClient?M:{...M,originatingClient:d.clientInfo},Q=y!==void 0?{...W,forwardedEnv:y}:W;w=await as(e,{...Q,onInstallProgress:Sd(a)})}ls(d,w,w.sessionId);let I=sn(a,w,d,f.clientInfo,f.clientId),b=g.replayMode==="drip",{entries:A,appliedPolicy:R}=await w.attach(I,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:b,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:I.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),s.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${I.clientId} attachedCount=${d.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${R} replayed=${A.length} readonly=${h}${b?" replayMode=drip":""}`),b){let _=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,M=750;(async()=>{let W=null;for(let Q of A){let pe=typeof Q.recordedAt=="number"?Q.recordedAt:null;if(W!==null&&pe!==null){let tt=Math.min(M,Math.max(0,(pe-W)/_));tt>0&&await new Promise(rn=>setTimeout(rn,tt))}pe!==null&&(W=pe);try{await a.notify(Q.method,We(Q.params,pe??void 0))}catch{return}}})()}else for(let _=0;_<A.length&&!a.isClosed();_++){let M=A[_],W=a.notify(M.method,We(M.params,M.recordedAt)).catch(()=>{});(_+1)%200===0&&await W}w.replayPendingPermissions(I);let E=ds(w),$=cs(w);return{sessionId:w.sessionId,clientId:I.clientId,connectedClients:w.connectedClients(I.clientId),historyPolicy:R,replayed:A.length,...E?{modes:E}:{},...$?{models:$}:{},configOptions:w.buildConfigOptions(),_meta:us(e.manager,w,{resurrected:S})}}),a.onRequest("session/detach",async l=>{let f=$o.parse(l),p=d.attached.get(f.sessionId);if(!p)throw F(x.SessionNotFound,"client not attached to that session");let g=e.manager.get(f.sessionId);return g?.detach(p.clientId),d.attached.delete(f.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[ue]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async l=>{let f=Fo.parse(l??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(h=>h.originatingClient?.name!==Fn).map(No)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw F(x.InternalError,"agent registry unavailable");return it(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async l=>{let f=l??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw F(x.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async l=>{let f=Oo.parse(l);c(f.sessionId,"session/prompt");let p=await wd(f,e.manager,y=>{s.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${y} sessionId=${f.sessionId}`)});if(p?.fromSession!==void 0){if((p.depth??0)>3)throw s.log.warn(`session/prompt: refusing depth ${p.depth} chain from ${p.fromSession} to ${f.sessionId}`),F(x.InvalidRequest,`message chain too deep (${p.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(p.awaiting===!0&&bd(p.fromSession,f.sessionId))throw s.log.warn(`session/prompt: refusing deadlock ${p.fromSession} -> ${f.sessionId}`),F(x.InvalidRequest,`would deadlock: ${f.sessionId} is already blocked waiting on ${p.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let g=d.attached.get(f.sessionId);if(!g)throw s.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),F(x.SessionNotFound,"not attached to session");let m=e.manager.get(f.sessionId);if(!m){let y=await e.manager.loadFromDisk(f.sessionId);if(!y)throw F(x.SessionNotFound,`session ${f.sessionId} not found`);s.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),m=await as(e,y);let k=sn(a,m,d,void 0,g.clientId);await m.attach(k,"none")}let h=p?.awaiting===!0&&p.fromSession!==void 0?kd(p.fromSession,f.sessionId):void 0;try{return await m.prompt(g.clientId,f,p)}finally{h?.()}});let u=l=>{let f;try{f=gn.parse(l)}catch(m){s.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(f.sessionId);if(!p)return;if(p.readonly){s.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let g=e.manager.get(f.sessionId);g&&g.cancel(p.clientId).catch(m=>{s.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",u),a.onRequest("session/cancel",async l=>{let f=gn.parse(l);return c(f.sessionId,"session/cancel"),u(l),null}),a.onRequest("hydra-acp/prompt/cancel",async l=>{let f=jo.parse(l);return c(f.sessionId,"hydra-acp/prompt/cancel"),ye(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async l=>{let f=gn.parse(l);return c(f.sessionId,"hydra-acp/session/force_cancel"),ye(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async l=>{let f=Uo.parse(l);return c(f.sessionId,"hydra-acp/prompt/update"),ye(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async l=>{let f=Do.parse(l);c(f.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(f.sessionId);if(!p)throw F(x.SessionNotFound,"not attached to session");return ye(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw F(x.InvalidParams,"session/resume requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let w=await e.manager.loadFromDisk(g);if(!w)throw F(x.SessionNotFound,`session ${p} not found in memory or on disk`);m=await as(e,w)}ls(d,m,m.sessionId);let h=sn(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=ds(m),k=cs(m);return{sessionId:m.sessionId,...y?{modes:y}:{},...k?{models:k}:{},configOptions:m.buildConfigOptions(),_meta:us(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/load",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw F(x.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let S=await e.manager.loadFromDisk(g);if(!S)throw F(x.SessionNotFound,`session ${p} not found in memory or on disk`);m=await as(e,S)}ls(d,m,m.sessionId);let h=sn(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 S of y){if(a.isClosed())break;await a.notify(S.method,We(S.params,S.recordedAt)).catch(()=>{})}m.replayPendingPermissions(h);let k=ds(m),w=cs(m);return{sessionId:m.sessionId,...k?{modes:k}:{},...w?{models:w}:{},configOptions:m.buildConfigOptions(),_meta:us(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async l=>{let f=l?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=lg(l,e.manager);if(p.kind==="error")throw s.log.warn(p.logMessage),F(p.code,p.message);if(p.kind==="no_op")return s.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;s.log.info(p.logMessage);let{modelId:g}=p,m=await p.session.forwardModelChange(g,l);return p.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async l=>{let f=l,p=f?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw F(x.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw F(x.InvalidParams,"session/set_mode requires string modeId");let g=ye(e.manager,f.sessionId),m=await g.forwardRequest("session/set_mode",l);return g.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async l=>{let f=l,p=y=>F(x.InvalidParams,y),g=f?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=ye(e.manager,f.sessionId),h=m.buildConfigOptions().find(y=>y.id===f.configId);if(!h)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!h.options.some(y=>y.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardModelChange(f.value),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:await m.forwardRequest("session/set_config_option",{sessionId:f.sessionId,configId:f.configId,value:f.value})}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(l,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),g=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!g&&!m||l===null||typeof l!="object"||p.has(f))throw F(x.MethodNotFound,`Method not found: ${f}`);let h=l.sessionId;if(typeof h!="string")throw F(x.MethodNotFound,`Method not found: ${f}`);return c(h,f),ye(e.manager,h).forwardRequest(f,l)})})}async function cg(s,e){let t=s??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw F(x.InvalidParams,"authenticate requires a non-empty methodId string");let n=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===n);if(!c){let p=d.map(g=>g.id);throw F(x.InvalidParams,`authenticate: methodId ${JSON.stringify(n)} is not advertised by agent ${a.agentId}; valid: [${p.map(g=>JSON.stringify(g)).join(", ")}]`)}let u=c._meta?.type,l=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(u==="agent"||u==="terminal"?u:l!==void 0?"terminal":"agent"))==="terminal"){let p=(w,S)=>{if(!Array.isArray(w))throw F(x.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${S} must be a string[]; got ${w===null?"null":typeof w}`);for(let I of w)if(typeof I!="string")throw F(x.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${S} must be string[]; got non-string entry ${JSON.stringify(I)}`);return w},g=await e.manager.planSpawnForAgent(a.agentId),m,h;if(l?.args!==void 0){let w=typeof l.command=="string"?l.command:void 0;m=w!==void 0&&Cd.isAbsolute(w)?w:g.command,h=p(l.args,'_meta["terminal-auth"].args')}else{let w=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=w!==void 0?p(w.raw,w.label):[];m=g.command,h=[...g.args,...S]}let y={};for(let[w,S]of Object.entries(process.env))typeof S=="string"&&(y[w]=S);Object.assign(y,g.env);let k=Ad.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${n}`),{kind:"terminal",command:m,args:h,env:y,cwd:k}}try{return await a.connection.request("authenticate",{methodId:n})}catch(p){throw Ve(p,a)}}async function ug(s,e){let n=(s??{})._meta?.["hydra-acp"],r=typeof n?.sessionId=="string"?n.sessionId:void 0,o=typeof n?.agentId=="string"?n.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function Sd(s){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),s.notify(Bo,t).catch(()=>{})}}function ds(s){let e=s.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:s.currentMode??e[0].id,availableModes:t}}function cs(s){let e=s.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:s.currentModel??e[0].modelId,availableModels:t}}function lg(s,e){if(!s||typeof s!="object")return{kind:"error",code:x.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=s;if(typeof t.sessionId!="string")return{kind:"error",code:x.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:x.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let n=e.get(t.sessionId);if(!n)return{kind:"error",code:x.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=n.availableModels(),o=gt(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:n,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:n,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:n,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return n.currentModel!==void 0&&n.currentModel.length>0?{kind:"no_op",session:n,sessionId:t.sessionId,currentModel:n.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(n.currentModel)} agentId=${n.agentId} known=[${i}]`}:{kind:"error",code:x.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${n.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${n.agentId} known=[${i}] (no current model to fall back to)`}}async function pg(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0;if(!r)throw F(x.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw F(x.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw F(x.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ye(t.manager,r).addTransformer(o),{ok:!0}}async function fg(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0,o=typeof n.reason=="string"?n.reason:void 0;if(!r)throw F(x.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw F(x.InvalidParams,"hydra-acp/attention/set requires string reason");return ye(t.manager,r).setAttentionFlag(e,o,n.payload),{ok:!0}}async function gg(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0,o=typeof n.reason=="string"?n.reason:void 0;if(!r)throw F(x.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw F(x.InvalidParams,"hydra-acp/attention/clear requires string reason");return ye(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function mg(s){let e={sessionId:s.hydraSessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,workspace:s.workspace,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:zt(s.currentUsage),forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:s.interactive,updatedAt:s.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:s.currentMode,agentArgs:s.agentArgs,availableCommands:s.agentCommands,availableModes:s.agentModes,availableModels:s.agentModels};return{[ue]:fn(e,t)}}function us(s,e,t={}){let n=s.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 _t(e.agentMeta,fn(n,r))}function hg(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ie},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:_t(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 yg(s,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let n=e.transformers.resolveChain([t])[0];n&&s.addTransformer(n)}}function Rd(s,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let n of t)n.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:s}).catch(()=>{})}function sn(s,e,t,n,r){return{clientId:r??`cli_${Lr(8)}`,connection:s,clientInfo:n}}function ls(s,e,t){let n=s.attached.get(t);n&&(e.detach(n.clientId),s.attached.delete(t))}var ps=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,n,r=new Promise((i,a)=>{t=i,n=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),n(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:n}=this.reserve(e);n(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let n=this.byToken.get(e);n!==void 0&&n.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let n of t.disposers)try{await n()}catch{}}}size(){return this.byToken.size}};import{randomUUID as wg}from"crypto";import{McpServer as kg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as bg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as ae}from"zod";function Wr(s){if(s.method!=="session/update")return null;let t=s.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function le(s){return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}var Ed="Bearer ";function Pt(s){let e=s.headers.authorization;if(typeof e!="string"||!e.startsWith(Ed))return;let t=e.slice(Ed.length).trim();return t.length>0?t:void 0}function vg(s){let e=new kg({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:ae.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let n=s.streamTail(t);return le(n)}),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:ae.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let n=s.streamHead(t);return le(n)}),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:ae.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:ae.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:ae.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:n,wait_ms:r})=>{let o=await s.streamRead(t,n,r);return le(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:ae.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:ae.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:n})=>{let r=await s.streamWaitFor(t,n),o=s.streamInfo();return le({outcome:r,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:ae.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:ae.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:ae.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:ae.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:ae.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:ae.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:ae.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:ae.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:ae.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 n={pattern:t.pattern};t.regex!==void 0&&(n.regex=t.regex),t.case_insensitive!==void 0&&(n.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(n.invert=t.invert),t.max_matches!==void 0&&(n.maxMatches=t.max_matches),t.max_bytes!==void 0&&(n.maxBytes=t.max_bytes),t.context_before!==void 0&&(n.contextBefore=t.context_before),t.context_after!==void 0&&(n.contextAfter=t.context_after),t.cursor!==void 0&&(n.cursor=t.cursor);let r=s.streamGrep(n);return le(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=s.streamInfo();return le(t)}),e}var Sg=1e4;function Pd(s,e){let t=new Map;async function n(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=vg(a),u=new bg({sessionIdGenerator:()=>wg()});await c.connect(u);let l={server:c,transport:u};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await u.close()}catch{}try{await c.close()}catch{}}),u}async function r(i,a){let d=Pt(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let u;if(c.session!==void 0)u=c.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Sg)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),g===void 0){a.code(503).send({error:"session not ready"});return}u=g}let l=await n(d,u);a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};s.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),s.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),s.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as Ig}from"crypto";import{McpServer as Ag}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Cg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Fe}from"zod";function xg(s){switch(s){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var Md=2e3,Td=2e4;function Rg(s,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return mt([s]);let n=[],r=Ft(t);r!==void 0?n.push(`Tool: ${r}`):typeof t.title=="string"&&t.title.length>0&&n.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&n.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&n.push(a.path);let i=wn(t);return i!==void 0&&n.push(i),n.join(`
193
+ `)}function Eg(s,e){if(s.length<=148)return s;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>s.length&&(o=s.length-148,o<0&&(o=0));let a=s.slice(o,i);return o>0&&(a="\u2026"+a),i<s.length&&(a=a+"\u2026"),a}function Pg(s){let e=new Ag({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. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. 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:Fe.string().min(1).describe("Case-insensitive substring to search for."),limit:Fe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Fe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:n=10,include_tool_calls:r=!0})=>{let o=await s();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return le({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=[],a=t.toLowerCase();for await(let{entryId:c,entry:u}of o.iterRecallNewestFirst()){let l=Wr(u);if(!l)continue;let{kind:f,update:p}=l;if((f==="tool_call"||f==="tool_call_update")&&!r)continue;let g=Rg(u,f,p),m=g.toLowerCase().indexOf(a);if(m<0)continue;let h=xg(f),y=Eg(g,m),k=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(i.push({entryId:c,speaker:h,snippet:y,timestamp:k}),i.length>=n)break}i.sort((c,u)=>c.entryId-u.entryId);let d=i.length>=n;return le({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Fe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Fe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:n})=>{let r=await s();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return le({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(n<t)throw new Error(`range: to_entry (${n}) must be >= from_entry (${t})`);let o=n-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getRecallTotalCount();if(i===0)return le({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(n,i-1),c=a>t||d<n;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let u=await r.sliceRecallHistory(a,d),l=mt(u,{toolOutput:{maxPerCall:Md,maxTotal:Td}});return{content:[{type:"text",text:l}],structuredContent:{text:l,entry_count:u.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:Fe.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:Fe.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:Fe.string().optional(),limit:Fe.number().int().min(1).max(100).optional(),include_output:Fe.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:n,file_path:r,limit:o=20,include_output:i=!0})=>{let a=await s();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return le({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 d=typeof t=="string"&&t.length>0,c=typeof n=="string"&&n.length>0,u=typeof r=="string"&&r.length>0;if(!d&&!c&&!u)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let l=new Map,f=Math.max(o*4,200);for await(let{entryId:k,entry:w}of a.iterRecallNewestFirst()){let S=Wr(w);if(!S)continue;let{kind:I,update:b}=S;if(I!=="tool_call"&&I!=="tool_call_update")continue;let A=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:`__noid_${k}`,R=l.get(A);if(R||(R={entryId:k,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},l.set(A,R)),k<R.entryId&&(R.entryId=k),!R.nameAuthoritative){let $=Ft(b);$!==void 0?(R.toolName=$,R.nameAuthoritative=!0):typeof b.name=="string"&&b.name.length>0?(R.toolName=b.name,R.nameAuthoritative=!0):I==="tool_call"&&typeof b.title=="string"&&b.title.length>0&&(R.toolName=b.title,R.nameAuthoritative=!0)}if(R.kind===void 0&&typeof b.kind=="string"&&b.kind.length>0&&(R.kind=b.kind),R.output===void 0){let $=wn(b);$!==void 0&&(R.output=$)}let E=b.rawInput;if(E&&typeof E=="object"&&!Array.isArray(E)&&Object.keys(E).length>0)for(let[$,_]of Object.entries(E))R.rawInput[$]===void 0&&(R.rawInput[$]=_);if(Array.isArray(b.locations))for(let $ of b.locations){let _=$?.path;typeof _=="string"&&_.length>0&&!R.locations.includes(_)&&R.locations.push(_)}if(typeof b.status=="string"&&R.status==="in_progress"&&(R.status=b.status),w.recordedAt!==void 0&&R.timestamp===void 0&&(R.timestamp=String(w.recordedAt)),l.size>=f)break}let p=[...l.keys()].sort((k,w)=>l.get(k).entryId-l.get(w).entryId),g=[],m=Td,h=!1;for(let k of p){let w=l.get(k);if(w.toolName=Ds({name:w.toolName,rawInput:w.rawInput,...w.kind!==void 0?{kind:w.kind}:{}}),d&&!w.toolName.toLowerCase().includes(t.toLowerCase())||c&&(w.kind??"").toLowerCase()!==n.toLowerCase())continue;if(u){let b=r.toLowerCase(),A=["file_path","filePath","path"],R=!1;for(let E of A){let $=w.rawInput[E];if(typeof $=="string"&&$.toLowerCase().includes(b)){R=!0;break}}if(!R){for(let E of w.locations)if(E.toLowerCase().includes(b)){R=!0;break}}if(!R)continue}let S={};for(let[b,A]of Object.entries(w.rawInput))typeof A=="string"?S[b]=A.length>500?A.slice(0,497)+"\u2026":A:(typeof A=="number"||typeof A=="boolean")&&(S[b]=A);w.locations.length>0&&S.locations===void 0&&(S.locations=w.locations);let I={entryId:w.entryId,tool:w.toolName,args:S,status:w.status,timestamp:w.timestamp};if(w.kind!==void 0&&(I.kind=w.kind),i&&w.output!==void 0){let b=w.output,A=Math.min(Md,m);if(A<=0)h=!0;else{let R=b.length<=A?b:b.slice(0,A-1)+"\u2026";I.output=R,I.outputBytes=b.length,I.outputTruncated=R.length<b.length,m-=R.length}}if(g.push(I),g.length>=o)break}let y=g.length>=o;return le({calls:g,truncated:y,...h?{outputBudgetExhausted:h}:{}})}),e}var Mg=1e4;function _d(s,e){let t=new Map;async function n(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=Pg(a),u=new Cg({sessionIdGenerator:()=>Ig()});await c.connect(u);let l={server:c,transport:u};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await u.close()}catch{}try{await c.close()}catch{}}),u}async function r(i,a){let d=Pt(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let l=await n(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Mg)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),g===void 0)throw new Error("recall: session not ready");return g});a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};s.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),s.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),s.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var fs=class{byName=new Map;changeHandlers=[];register(e,t,n,r){this.byName.set(e,{connection:t,instructions:n,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 n of this.changeHandlers)try{n(e,t)}catch{}}};import{StreamableHTTPServerTransport as jg}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Ug}from"crypto";import{Server as Tg}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as _g,ListToolsRequestSchema as $g}from"@modelcontextprotocol/sdk/types.js";function $d(s,e,t,n){let r=typeof t=="function"?async()=>t():async()=>t,o=new Tg({name:s,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler($g,async()=>{let a=n?.peekSessionId?.();if(a!==void 0&&n?.fetchSessionTools!==void 0)try{let d=await n.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(_g,async(a,d)=>{let c=a.params.name,u=d._meta?.progressToken??d.requestId,l=Ng(u,d.sendNotification);try{let f=await r(),p=await Og(e.connection,s,c,a.params.arguments??{},f);return Hg(p,c)}catch(f){return qr(f instanceof Error?f.message:String(f))}finally{l()}}),o}var Fg=15e3;function Ng(s,e,t=Fg){if(s===void 0)return()=>{};let n=0,r=setInterval(()=>{n+=1,e({method:"notifications/progress",params:{progressToken:s,progress:n}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function Og(s,e,t,n,r){return await s.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:n,sessionId:r})}function Hg(s,e){if(s===null||typeof s!="object")return qr(`extension ${e} returned non-object`);let t=s;return Array.isArray(t.content)?t:qr(`extension ${e} omitted content array`)}function qr(s){return{content:[{type:"text",text:s}],isError:!0}}var Dg=1e4;function Fd(s,e,t){let n=new Map;async function r(u){try{await u.transport.close()}catch{}try{await u.server.close()}catch{}}function o(u){for(let l of n.values()){let f=l.get(u);f!==void 0&&(l.delete(u),r(f))}}async function i(u,l){for(let[f,p]of n){if(e.lookup(f)?.session?.sessionId!==u)continue;let m=p.get(l);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(u=>{o(u)});async function a(u,l){let f=n.get(u);f===void 0&&(f=new Map,n.set(u,f),e.addDisposer(u,async()=>{let S=n.get(u);if(S!==void 0){n.delete(u);for(let I of S.values())await r(I)}}));let p=f.get(l);if(p!==void 0)return p.transport;let g=t.lookup(l);if(g===void 0)return;let k=$d(l,g,async()=>{let S=e.lookup(u);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let I,b=new Promise(R=>{I=setTimeout(()=>R(void 0),Dg)}),A=await Promise.race([S.sessionReady.catch(()=>{}),b]);if(I!==void 0&&clearTimeout(I),A===void 0)throw new Error("session not ready");return A.sessionId},{peekSessionId:()=>e.lookup(u)?.session?.sessionId,fetchSessionTools:async S=>{let I=await g.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!I||typeof I!="object")return;let b=I.tools;if(!Array.isArray(b))return;let A=[];for(let R of b){if(!R||typeof R!="object")continue;let E=R;if(typeof E.name!="string"||E.name.length===0||typeof E.description!="string"||E.inputSchema===null||typeof E.inputSchema!="object")continue;let $={name:E.name,description:E.description,inputSchema:E.inputSchema};E.outputSchema!==null&&typeof E.outputSchema=="object"&&($.outputSchema=E.outputSchema),A.push($)}return A}}),w=new jg({sessionIdGenerator:()=>Ug()});return await k.connect(w),f.set(l,{server:k,transport:w}),w}async function d(u,l){let f=Pt(u);if(f===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){l.code(404).send({error:"unknown mcp token"});return}let g=u.params.name,m=await a(f,g);if(m===void 0){l.code(404).send({error:`unknown mcp server: ${g}`});return}l.hijack(),await m.handleRequest(u.raw,l.raw,u.body)}let c={config:{skipAuth:!0}};return s.post("/mcp/:name",c,async(u,l)=>{await d(u,l)}),s.get("/mcp/:name",c,async(u,l)=>{await d(u,l)}),s.delete("/mcp/:name",c,async(u,l)=>{await d(u,l)}),{notifyToolListChanged:i}}async function Dd(s,e){Vg(s),uo(s.daemon.scrubEnv);let t=s.daemon.tls?await Ne.readFile(de(s.daemon.tls.key)):void 0,n=s.daemon.tls?await Ne.readFile(de(s.daemon.tls.cert)):void 0;await Ne.mkdir(C.home(),{recursive:!0});let{stream:r,fileStream:o}=await zg(s.daemon.logLevel),i=Bg({logger:{level:s.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(Lg,{options:{handleProtocols:io}}),Rs(U=>{i.log.info(U)}),Ms(U=>{i.log.info(U)});let a=await Gn.load(),d=new Zn,c=new Xn,u=new Yn([new Qn(e),new Kn(a),c]),l=Ma({validator:u});i.addHook("onRequest",async(U,Ae)=>{U.routeOptions.config?.skipAuth||U.url==="/acp"||U.url?.startsWith("/acp?")||await l(U,Ae)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{d.sweepExpired()},300*1e3);p.unref();let g=new ln(s,{onFetched:()=>{ba(g,k)}});_r(U=>i.log.info(U));let m={info:U=>i.log.info(U),warn:U=>i.log.warn(U)},h=U=>ze.spawn({...U,stderrTailBytes:s.daemon.agentStderrTailBytes,logger:m});go(s.compressToolContent);let y=new Jn,k=new Un(g,h,void 0,{idleTimeoutMs:s.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:s.defaultModels,synopsisAgent:s.synopsisAgent,synopsisModel:s.synopsisModel,compactionAgent:s.compaction?.agent,compactionModel:s.compaction?.model,defaultTransformers:s.defaultTransformers,sessionHistoryMaxEntries:s.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:s.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:s.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:s.npmRegistry,extensionCommands:y,defaultCwd:s.defaultCwd,disableWorkspaceSnapshots:s.disableWorkspaceSnapshots}),w=new qn(no(s),void 0,{tokenRegistry:c}),S=new zn(so(s),void 0,{tokenRegistry:c});dd(i,ie,Ia(s));let I=new ps,b=new fs,A,R=()=>{if(A!==void 0)return A;let U=i.server.address();return A=`http://127.0.0.1:${U&&typeof U=="object"?U.port:s.daemon.port}`,A};id(i,k,{agentId:s.defaultAgent,cwd:s.defaultCwd,publicHost:s.daemon.publicHost,host:s.daemon.host,port:s.daemon.port,compaction:s.compaction},{extensionMcp:b,mcpTokenRegistry:I,getDaemonOrigin:R}),ad(i,g,k,{npmRegistry:s.npmRegistry}),cd(i,w),ud(i,S),ld(i,{defaultAgent:s.defaultAgent,defaultCwd:s.defaultCwd,defaultModels:{...s.defaultModels},...s.synopsisAgent!==void 0?{synopsisAgent:s.synopsisAgent}:{},...s.synopsisModel!==void 0?{synopsisModel:s.synopsisModel}:{},defaultTransformers:[...s.defaultTransformers]}),hd(i,{store:a,rateLimiter:d}),Pd(i,I),_d(i,I);let E=Fd(i,I,b);xd(i,{validator:u,manager:k,defaultAgent:s.defaultAgent,processRegistry:c,onExtensionVersion:(U,Ae)=>w.reportVersion(U,Ae),onTransformerVersion:(U,Ae)=>S.reportVersion(U,Ae),transformers:S,extensionCommands:y,mcpTokenRegistry:I,extensionMcp:b,extensionMcpControls:E,getDaemonOrigin:R,registry:g});let $=!!s.daemon.tls;await i.listen({host:$?"127.0.0.1":s.daemon.host,port:$?0:s.daemon.port});let _=i.server.address(),M=_&&typeof _=="object"?_.port:s.daemon.port,W,Q=s.daemon.host,pe=M;if($&&t&&n){W=Jg({listenHost:s.daemon.host,listenPort:s.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:M,tlsOptions:{key:t,cert:n},logger:i.log});let U=W.address();U&&typeof U=="object"&&(pe=U.port)}await Ne.mkdir(C.home(),{recursive:!0}),await ka({pid:process.pid,host:Q,port:pe,loopbackPort:M,startedAt:new Date().toISOString()});let tt={daemonUrl:`http://127.0.0.1:${M}`,daemonHost:"127.0.0.1",daemonPort:M,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${M}/acp`,hydraHome:C.home()};w.setContext(tt),S.setContext(tt),await w.start(),await S.start();try{await k.reconcilePermissionFlags()}catch(U){i.log.warn(`permission flag reconcile failed: ${U.message}`)}k.resurrectPendingQueues().catch(U=>{i.log.warn(`queue replay scan failed: ${U.message}`)}),k.resumePendingCompactions().catch(U=>{i.log.warn(`compaction resume scan failed: ${U.message}`)}),k.resumePendingAgentSwaps().catch(U=>{i.log.warn(`agent-swap resume scan failed: ${U.message}`)});let rn=s.daemon.agentSyncIntervalMinutes*60*1e3,Vr=rn>0?va({registry:g,manager:k,intervalMs:rn,logger:m}):void 0,Gr=s.daemon.sessionGcIntervalMinutes*60*1e3,Yd=s.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Qr=Gr>0?Sa({manager:k,intervalMs:Gr,maxAgeMs:Yd,logger:m}):void 0;return{app:i,manager:k,registry:g,extensions:w,transformers:S,mcpTokenRegistry:I,extensionMcp:b,processRegistry:c,shutdown:async()=>{Qr&&Qr(),Vr&&Vr(),clearInterval(f),clearInterval(p);let U=async(Ae,Xd)=>{try{await Xd()}catch(ms){i.log.warn(`shutdown step ${Ae} failed: ${ms instanceof Error?ms.message:String(ms)}`)}};await U("sessionTokenStore.flush",()=>a.flush()),await U("extensions.stop",()=>w.stop()),await U("transformers.stop",()=>S.stop()),await U("manager.closeAll",()=>k.closeAll()),await U("manager.flushSynopsis",()=>k.flushSynopsis(3e4)),await U("manager.shutdownSynopsis",()=>k.shutdownSynopsis()),await U("manager.flushMetaWrites",()=>k.flushMetaWrites()),await U("manager.flushHistoryWrites",()=>k.flushHistoryWrites()),Rs(null),Ms(null),_r(null),W&&await U("tlsTerminator.close",()=>new Promise(Ae=>W.close(()=>Ae()))),await U("app.close",()=>i.close());try{Hd.unlinkSync(C.pidFile())}catch{}await U("fileStream.flushSync",()=>o.flushSync())}}}var Od=20;async function qg(s,e){let t=Mt.dirname(s),n=Mt.basename(s,".log"),r=new RegExp(`^${n}\\.(\\d+)\\.log$`),o;try{o=await Ne.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(r);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>Ne.unlink(Mt.join(t,d.name))))}async function zg(s){await qg(C.logFile(),Od);let e=await Wg({file:C.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Od,removeOtherLogFiles:!0}}),t=Nd.destination(2);return{stream:Nd.multistream([{stream:e,level:s},{stream:t,level:s}]),fileStream:e}}function Jg(s){let e=Ud.createServer(s.tlsOptions,t=>{let n=jd.connect({host:s.upstreamHost,port:s.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&s.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{n.destroy()}catch{}}};t.on("error",o),n.on("error",o),t.on("close",()=>o()),n.on("close",()=>o()),t.pipe(n),n.pipe(t)});return e.on("tlsClientError",t=>{s.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:s.listenHost,port:s.listenPort}),e}function Vg(s){let e=s.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!s.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}async function dm(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:s}=await Promise.resolve().then(()=>(Kd(),Qd));s();let e=await vs(),t=await Kr(),n=await Dd(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
192
194
  `);let r=1e4,o=!1,i=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
193
195
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
194
196
  `);let a=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${r}ms; forcing exit.
195
197
  `),process.exit(1)},r);a.unref();try{await n.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
196
- `)}clearTimeout(a),process.exit(0)};process.on("SIGINT",()=>{i()}),process.on("SIGTERM",()=>{i()}),process.on("SIGHUP",()=>{})}th().catch(s=>{process.stderr.write(`hydra-acp-daemon: ${s instanceof Error?s.message:String(s)}
198
+ `)}clearTimeout(a),process.exit(0)};process.on("SIGINT",()=>{i()}),process.on("SIGTERM",()=>{i()}),process.on("SIGHUP",()=>{})}dm().catch(s=>{process.stderr.write(`hydra-acp-daemon: ${s instanceof Error?s.message:String(s)}
197
199
  `),process.exit(1)});