@hydra-acp/cli 0.1.192 → 0.1.193

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 +66 -66
  2. package/dist/daemon.js +14 -14
  3. package/package.json +1 -1
package/dist/daemon.js CHANGED
@@ -5,8 +5,8 @@ var Nu=Object.defineProperty;var Ln=(s,e)=>()=>(s&&(e=s(s=0)),e);var Du=(s,e)=>{
5
5
  `,{encoding:"utf8",mode:384})}async function oi(){let s=await Lu();if(s)return s;let e=sr();return await rr(e),process.stderr.write(`hydra-acp: initialized ${x.authToken()} with a fresh service token.
6
6
  `),e}Ne();import*as di from"fs/promises";import*as nn from"os";import*as De from"path";var ee="read by the daemon, which loads config.json at startup",ai={daemon:{reload:"restart",overlay:"partial",overlayNote:"only changes which daemon this client dials; a daemon started from here still binds config.json's host/port. Use `home` for a separate daemon",nested:!0},agents:{reload:"live",overlay:"inert",overlayNote:ee},agentOverrides:{reload:"live",overlay:"inert",overlayNote:ee},registry:{reload:"live",overlay:"inert",overlayNote:ee},npmRegistry:{reload:"live",overlay:"inert",overlayNote:ee},defaultAgent:{reload:"live",overlay:"effective"},defaultCwd:{reload:"live",overlay:"effective"},sessionDefaults:{reload:"live",overlay:"partial",overlayNote:"applies to WS session/new and child_session/spawn; POST /v1/sessions has no model/mode/effort field to apply any of it to"},synopsisAgent:{reload:"warn",overlay:"inert",overlayNote:ee},synopsisModel:{reload:"warn",overlay:"inert",overlayNote:ee},compaction:{reload:"warn",overlay:"inert",overlayNote:ee},defaultTransformers:{reload:"warn",overlay:"inert",overlayNote:ee},disableWorkspaceSnapshots:{reload:"warn",overlay:"inert",overlayNote:ee},compressToolContent:{reload:"warn",overlay:"inert",overlayNote:ee},extensions:{reload:"warn",overlay:"inert",overlayNote:ee},transformers:{reload:"warn",overlay:"inert",overlayNote:ee},tui:{reload:"client",overlay:"effective"},sessionListColdLimit:{reload:"client",overlay:"effective"}},Gu={host:{reload:"restart",overlay:"inert"},port:{reload:"restart",overlay:"inert"},publicHost:{reload:"restart",overlay:"inert"},tls:{reload:"restart",overlay:"inert"},scrubEnv:{reload:"live",overlay:"inert",overlayNote:ee},logLevel:{reload:"warn",overlay:"inert",overlayNote:ee},sessionIdleTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:ee},nonInteractiveOrphanTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:ee},sessionHistoryMaxEntries:{reload:"warn",overlay:"inert",overlayNote:ee},sessionHistoryArchiveMaxBytes:{reload:"warn",overlay:"inert",overlayNote:ee},sessionHistoryArchiveTiers:{reload:"warn",overlay:"inert",overlayNote:ee},agentStderrTailBytes:{reload:"warn",overlay:"inert",overlayNote:ee},agentSyncIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:ee},sessionGcIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:ee},sessionGcMaxAgeDays:{reload:"warn",overlay:"inert",overlayNote:ee}};function or(s){return ai[s]??{reload:"restart",overlay:"inert"}}function ir(s){return Gu[s]??{reload:"restart",overlay:"inert"}}function ar(){let s=[];for(let[e,t]of Object.entries(ai))t.overlay!=="effective"&&s.push({key:e,effect:t.overlay,note:t.overlayNote??ee});return s}var Ku=".hydra-acp.json",dr="home",Qu=64,hw=ar().map(s=>s.key);function Yu(s){return s==="~"?nn.homedir():s.startsWith("~/")?De.join(nn.homedir(),s.slice(2)):s.startsWith("$HOME/")?De.join(nn.homedir(),s.slice(6)):s}function cr(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function ur(s,e){let t={...s};for(let[n,r]of Object.entries(e)){let o=t[n];t[n]=cr(o)&&cr(r)?ur(o,r):r}return t}async function Xu(s,e=nn.homedir()){let t=[],n=[],r=De.resolve(e),o=De.resolve(s);for(let i=0;i<Qu;i+=1){let a=De.join(o,Ku),d;try{d=await di.readFile(a,"utf8")}catch{d=void 0}if(d!==void 0)try{let u=JSON.parse(d);cr(u)?t.push({file:a,data:u}):n.push({file:a,key:"",message:"expected a JSON object; ignoring this file"})}catch(u){n.push({file:a,key:"",message:`is not valid JSON (${u.message}); ignoring this file`})}if(o===r)break;let c=De.dirname(o);if(c===o)break;o=c}return t.reverse(),{layers:t,notices:n}}function Zu(s){let e=new Map(ar().map(n=>[n.key,n])),t=[];for(let n of s)for(let r of Object.keys(n.data)){let o=e.get(r);if(!o)continue;let i=o.effect==="partial"?`\`${r}\` ${o.note}`:`\`${r}\` is ${o.note}, so it has no effect in a directory config`;t.push({file:n.file,key:r,message:i})}return t}async function el(s=process.cwd()){let{layers:e,notices:t}=await Xu(s);t.push(...Zu(e));let n={};for(let i of e)n=ur(n,i.data);let r,o=n[dr];return typeof o=="string"&&o.length>0?r=De.resolve(Yu(o)):o!==void 0&&t.push({file:e[e.length-1].file,key:dr,message:"`home` must be a non-empty string; ignoring it"}),delete n[dr],{layers:e,notices:t,merged:n,...r!==void 0?{homeRequest:r}:{}}}function tl(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function nl(s,e){let t=s[e];if(t===null||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i={};for(let[a,d]of Object.entries(o))typeof d=="string"&&(i[a]=d);Object.keys(i).length>0&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}async function sn(s){let e={};try{e=(await el(s)).merged}catch{return{}}let t=tl(e,"defaultAgent"),n=nl(e,"sessionDefaults");return{...t!==void 0?{agentId:t}:{},...n!==void 0?{configDefaults:n}:{}}}var li="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",sl=S.object({cert:S.string(),key:S.string()}),Tt=55514,rl=S.object({host:S.string().default("127.0.0.1"),port:S.number().int().positive().default(Tt),logLevel:S.enum(["debug","info","warn","error"]).default("info"),tls:sl.optional(),sessionIdleTimeoutSeconds:S.number().int().nonnegative().default(3600),nonInteractiveOrphanTimeoutSeconds:S.number().int().nonnegative().default(180),sessionHistoryMaxEntries:S.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:S.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:S.number().int().positive().default(10),agentStderrTailBytes:S.number().int().positive().default(4096),publicHost:S.string().optional(),agentSyncIntervalMinutes:S.number().nonnegative().default(60),scrubEnv:S.array(S.string()).default([]),sessionGcIntervalMinutes:S.number().nonnegative().default(60),sessionGcMaxAgeDays:S.number().positive().default(2)}),ol=S.object({url:S.string().url().default(li),ttlHours:S.number().positive().default(24),pinned:S.boolean().default(!1)}),il=S.object({extends:S.string().optional(),name:S.string().optional(),description:S.string().optional(),command:S.string().optional(),args:S.array(S.string()).optional(),env:S.record(S.string()).optional()}),al=S.object({packageSpec:S.string().optional(),extraArgs:S.array(S.string()).optional(),env:S.record(S.string()).optional()}),dl=S.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-x-ctrl-e","ctrl-y","ctrl-underscore","alt-underscore","escape"]),cl=S.union([S.string(),S.object({field:S.string().optional(),text:S.string().optional(),script:S.string().optional(),refreshMs:S.number().int().positive().optional(),maxWidth:S.number().int().positive().optional(),minWidth:S.number().int().nonnegative().optional(),truncate:S.boolean().optional(),priority:S.number().optional(),prefix:S.string().optional(),suffix:S.string().optional(),separator:S.string().optional(),style:S.string().optional(),onClick:S.string().optional(),onDoubleClick:S.string().optional()}).strict()]),ul=S.object({id:S.string().min(1),script:S.string().min(1),refreshMs:S.number().int().positive().optional(),title:S.string().optional(),cap:S.number().int().positive().optional()}).strict(),ll=S.union([S.string(),ul]),ci=S.array(cl);function fr(s,e){return S.object({left:ci.default(s),right:ci.default(e)}).default({})}var fl=["status",{field:"elapsed",separator:" "},"sessionId","queued","scroll"],pl=["usage"],gl=[],ml=["helpHint"],hl=["cwd","title"],yl=["agentModel"],wl=S.object({composer:S.object({top:fr(fl,pl),bottom:fr(gl,ml),hintTurns:S.number().int().nonnegative().nullable().default(3)}).default({}),sessionbar:fr(hl,yl),scriptRefreshMs:S.number().int().positive().default(5e3),repaintThrottleMs:S.number().int().nonnegative().default(1e3),maxScrollbackLines:S.number().int().positive().default(1e4),mouse:S.boolean().default(!0),inAppSelection:S.boolean().optional(),selectionClipboard:S.enum(["primary","clipboard","both"]).default("both"),openFileCommand:S.union([S.string(),S.array(S.string())]).optional(),openFileInTerminal:S.boolean().optional(),logMaxBytes:S.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:S.number().int().positive().default(32),progressIndicator:S.boolean().default(!0),terminalHost:S.union([S.boolean(),S.enum(["auto","paseo","herdr","tmux"])]).default(!0),launcherModeWhenHosted:S.boolean().default(!1),skipPermissions:S.boolean().default(!1),defaultEnterAction:S.enum(["enqueue","amend"]).default("amend"),showThoughts:S.boolean().default(!0),ambiguousWidth:S.enum(["auto","narrow","wide"]).default("auto"),toolContent:S.enum(["inline","references"]).default("references"),diffContextLines:S.number().int().min(0).default(3),promptHistoryMaxEntries:S.number().int().positive().default(2e3),maxToolItems:S.number().int().nonnegative().default(5),maxPlanItems:S.number().int().nonnegative().default(5),sidebar:S.object({enabled:S.boolean().default(!0),width:S.number().int().positive().optional(),border:S.enum(["none","rule","frame"]).default("frame"),gadgets:S.array(ll).default(["activity","sessions","tasks","context","queue","todo","files","git","resources","info","tools"])}).default({}),showFileUpdates:S.enum(["none","edit","diff"]).default("edit"),sessionColumns:S.array(S.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),defaultHost:S.string().min(1).default("remote:all"),hotkeys:S.record(dl,S.object({command:S.union([S.string(),S.array(S.string())])})).default({}),theme:S.union([S.string(),S.record(S.string(),S.unknown())]).optional(),themeBackground:S.string().optional()}),ui=S.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),kl=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),vl=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),bl=S.object({daemon:rl.default({}),registry:ol.default({url:li,ttlHours:24,pinned:!1}),agents:S.record(S.string(),il).default({}),agentOverrides:S.record(S.string(),al).default({}),defaultAgent:S.string().default("opencode"),sessionDefaults:S.record(S.string(),S.record(S.string(),S.string())).default({}),synopsisAgent:S.string().optional(),synopsisModel:S.string().optional(),compaction:S.object({agent:S.string().optional(),model:S.string().optional(),tailK:S.number().int().nonnegative().default(20),maxIterations:S.number().int().positive().default(3),contextFraction:S.number().min(0).max(1).default(.5),hardCeilingFraction:S.number().min(0).max(1).default(.85),absoluteFallback:S.number().int().positive().default(2e5),idleBeforePromptMs:S.number().int().nonnegative().default(3e5),modelContextWindows:S.record(S.string(),S.number().int().positive()).default({})}).default({}),defaultCwd:S.string().default("~"),disableWorkspaceSnapshots:S.boolean().optional(),compressToolContent:S.boolean().default(!0),sessionListColdLimit:S.number().int().nonnegative().default(20),extensions:S.record(ui,kl).default({}),transformers:S.record(ui,vl).default({}),defaultTransformers:S.array(S.string()).default([]),npmRegistry:S.string().url().optional(),tui:wl.default({})});function fi(s){return Object.entries(s.extensions).map(([e,t])=>({name:e,...t}))}function pi(s){return Object.entries(s.transformers).map(([e,t])=>({name:e,...t}))}async function pr(){return await Sl(),await ie(x.config())??{}}async function Sl(){let s;try{s=await nt.lstat(x.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(s.isSymbolicLink())try{await nt.stat(x.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await nt.readlink(x.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${x.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 Il(){let s=await pr(),e=s.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let n=!1;try{await nt.access(x.authToken()),n=!0}catch(r){if(r.code!=="ENOENT")throw r}if(n)throw new Error(`Auth token present in both ${x.authToken()} and ${x.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await rr(t),delete e.authToken,Object.keys(e).length===0&&delete s.daemon,await pe(x.config(),s,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${x.config()} to ${x.authToken()}.
7
7
  `)}async function Al(){let s=await pr(),e=s.defaultModels&&typeof s.defaultModels=="object"&&!Array.isArray(s.defaultModels)?s.defaultModels:void 0;if(!e)return;let t=s.sessionDefaults&&typeof s.sessionDefaults=="object"&&!Array.isArray(s.sessionDefaults)?s.sessionDefaults:{};for(let[n,r]of Object.entries(e)){if(typeof r!="string")continue;let o=t[n]&&typeof t[n]=="object"&&!Array.isArray(t[n])?t[n]:{};o.model===void 0&&(o.model=r),t[n]=o}s.sessionDefaults=t,delete s.defaultModels,await pe(x.config(),s,{mode:384}),process.stderr.write(`hydra-acp: migrated defaultModels to sessionDefaults in ${x.config()}.
8
- `)}async function rn(){return await Il(),await Al(),bl.parse(await pr())}function ce(s){return s==="~"||s==="$HOME"?lr():s.startsWith("~/")?lr()+s.slice(1):s.startsWith("$HOME/")?lr()+s.slice(5):s}G();import*as Qe from"fs/promises";import*as gi from"path";var Cl=64*1024;async function mi(s){let e=x.daemonBootLog(),t=`[${new Date().toISOString()}] pid=${process.pid} ${s}
9
- `;if(await Qe.mkdir(gi.dirname(e),{recursive:!0}),await Qe.stat(e).then(r=>r.size).catch(()=>0)>Cl){await Qe.writeFile(e,t,{encoding:"utf8",mode:384});return}await Qe.appendFile(e,t,{encoding:"utf8",mode:384})}import*as Tu from"fs";import*as Ke from"fs/promises";import*as Pu from"net";import*as Zt from"path";import*as Mu from"tls";import Zy from"fastify";import ew from"@fastify/websocket";var hi="acp.v1";function yi(s,e){return s.has(hi)?hi:!1}import xu from"pino";import tw from"pino-roll";var Rl={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"],paseo:["PASEO_TERMINAL_ID","PASEO_ACTIVITY_TOKEN"],hydra:["HYDRA_TAB_LABEL"]},wi="HYDRA_ACP_SESSION",xl=[wi],El=[...Object.values(Rl).flat(),...xl];function Un(s,e){return s?{...e??{},[wi]:s}:e}var ki=[];function gr(s){ki=s?[...s]:[]}function Tl(s,e){return e.endsWith("*")?s.startsWith(e.slice(0,-1)):s===e}function Pl(){return[...El,...ki]}function Bn(s=process.env){let e=Pl(),t={};for(let[n,r]of Object.entries(s))r!==void 0&&(e.some(o=>Tl(n,o))||(t[n]=r));return t}G();import*as ge from"fs/promises";import{createHash as Ml}from"crypto";import{gzip as _l,gunzip as $l}from"zlib";import{promisify as vi}from"util";var bi=vi(_l),Ol=vi($l),Si=/^[A-Za-z0-9_-]+$/,Fl=/^[a-f0-9]{64}$/,mr=!0;function Ii(s){mr=s}function Wn(s,e){return Si.test(s)?e===void 0||Fl.test(e):!1}function qn(s,e){return`${x.toolBlobFile(s,e)}.gz`}async function hr(s,e){if(!Wn(s))return null;let t=Ml("sha256").update(e,"utf8").digest("hex"),n=qn(s,t),r=x.toolBlobFile(s,t);for(let a of[n,r])try{return await ge.access(a),t}catch{}await ge.mkdir(x.toolsDir(s),{recursive:!0});let o=mr?n:r,i=mr?await bi(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await ge.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function on(s,e){if(!Wn(s,e))return null;try{let t=await ge.readFile(qn(s,e));return(await Ol(t)).toString("utf8")}catch{}try{return await ge.readFile(x.toolBlobFile(s,e),"utf8")}catch{return null}}async function Ai(s,e){if(!Wn(s,e))return null;try{return await ge.readFile(qn(s,e))}catch{}try{let t=await ge.readFile(x.toolBlobFile(s,e));return await bi(t)}catch{return null}}async function Ci(s,e,t){if(!Wn(s,e))return;let n=qn(s,e);try{await ge.access(n);return}catch{}await ge.mkdir(x.toolsDir(s),{recursive:!0}),await ge.writeFile(n,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ri(s){Si.test(s)&&await ge.rm(x.toolsDir(s),{recursive:!0,force:!0}).catch(()=>{})}G();import*as Li from"fs/promises";import*as Jn from"path";import{z as L}from"zod";Ne();G();import*as Ei from"fs";import*as he from"fs/promises";import*as st from"path";import{spawn as Ti}from"child_process";import{Readable as Nl}from"stream";function je(){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 kr(s,e=je()){if(e)return s[e]}var Pt=s=>{process.stderr.write(s+`
8
+ `)}async function rn(){return await Il(),await Al(),bl.parse(await pr())}function ce(s){return s==="~"||s==="$HOME"?lr():s.startsWith("~/")?lr()+s.slice(1):s.startsWith("$HOME/")?lr()+s.slice(5):s}G();import*as Ye from"fs/promises";import*as gi from"path";var Cl=64*1024;async function mi(s){let e=x.daemonBootLog(),t=`[${new Date().toISOString()}] pid=${process.pid} ${s}
9
+ `;if(await Ye.mkdir(gi.dirname(e),{recursive:!0}),await Ye.stat(e).then(r=>r.size).catch(()=>0)>Cl){await Ye.writeFile(e,t,{encoding:"utf8",mode:384});return}await Ye.appendFile(e,t,{encoding:"utf8",mode:384})}import*as Tu from"fs";import*as Qe from"fs/promises";import*as Pu from"net";import*as Zt from"path";import*as Mu from"tls";import Zy from"fastify";import ew from"@fastify/websocket";var hi="acp.v1";function yi(s,e){return s.has(hi)?hi:!1}import xu from"pino";import tw from"pino-roll";var Rl={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"],paseo:["PASEO_TERMINAL_ID","PASEO_ACTIVITY_TOKEN"],hydra:["HYDRA_TAB_LABEL"]},wi="HYDRA_ACP_SESSION",xl=[wi],El=[...Object.values(Rl).flat(),...xl];function Un(s,e){return s?{...e??{},[wi]:s}:e}var ki=[];function gr(s){ki=s?[...s]:[]}function Tl(s,e){return e.endsWith("*")?s.startsWith(e.slice(0,-1)):s===e}function Pl(){return[...El,...ki]}function Bn(s=process.env){let e=Pl(),t={};for(let[n,r]of Object.entries(s))r!==void 0&&(e.some(o=>Tl(n,o))||(t[n]=r));return t}G();import*as ge from"fs/promises";import{createHash as Ml}from"crypto";import{gzip as _l,gunzip as $l}from"zlib";import{promisify as vi}from"util";var bi=vi(_l),Ol=vi($l),Si=/^[A-Za-z0-9_-]+$/,Fl=/^[a-f0-9]{64}$/,mr=!0;function Ii(s){mr=s}function Wn(s,e){return Si.test(s)?e===void 0||Fl.test(e):!1}function qn(s,e){return`${x.toolBlobFile(s,e)}.gz`}async function hr(s,e){if(!Wn(s))return null;let t=Ml("sha256").update(e,"utf8").digest("hex"),n=qn(s,t),r=x.toolBlobFile(s,t);for(let a of[n,r])try{return await ge.access(a),t}catch{}await ge.mkdir(x.toolsDir(s),{recursive:!0});let o=mr?n:r,i=mr?await bi(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await ge.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function on(s,e){if(!Wn(s,e))return null;try{let t=await ge.readFile(qn(s,e));return(await Ol(t)).toString("utf8")}catch{}try{return await ge.readFile(x.toolBlobFile(s,e),"utf8")}catch{return null}}async function Ai(s,e){if(!Wn(s,e))return null;try{return await ge.readFile(qn(s,e))}catch{}try{let t=await ge.readFile(x.toolBlobFile(s,e));return await bi(t)}catch{return null}}async function Ci(s,e,t){if(!Wn(s,e))return;let n=qn(s,e);try{await ge.access(n);return}catch{}await ge.mkdir(x.toolsDir(s),{recursive:!0}),await ge.writeFile(n,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ri(s){Si.test(s)&&await ge.rm(x.toolsDir(s),{recursive:!0,force:!0}).catch(()=>{})}G();import*as Li from"fs/promises";import*as Jn from"path";import{z as L}from"zod";Ne();G();import*as Ei from"fs";import*as he from"fs/promises";import*as st from"path";import{spawn as Ti}from"child_process";import{Readable as Nl}from"stream";function je(){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 kr(s,e=je()){if(e)return s[e]}var Pt=s=>{process.stderr.write(s+`
10
10
  `)};function vr(s){Pt=s??(e=>process.stderr.write(e+`
11
11
  `))}async function Pi(s){if(!s.target.archive)throw new Error(`Agent ${s.agentId} has no archive URL for ${je()??"this platform"}`);if(!s.target.cmd)throw new Error(`Agent ${s.agentId} has no cmd in its binary target`);let e=je();if(!e)throw new Error(`Agent ${s.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=x.agentInstallDir(s.agentId,e,s.version),n=st.resolve(t,s.target.cmd);if(await wr(n))return n;if(await Dl({agentId:s.agentId,version:s.version,archiveUrl:s.target.archive,installDir:t,onProgress:s.onProgress}),!await wr(n))throw new Error(`Agent ${s.agentId}: extracted archive did not contain ${s.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await he.chmod(n,493).catch(()=>{}),n}async function Dl(s){await he.mkdir(st.dirname(s.installDir),{recursive:!0});let e=await he.mkdtemp(`${s.installDir}.partial-`);try{Pt(`hydra-acp: downloading ${s.agentId} from ${s.archiveUrl}`);let t=await jl({url:s.archiveUrl,dir:e,agentId:s.agentId,version:s.version,onProgress:s.onProgress});Pt(`hydra-acp: extracting ${s.agentId}`),Mt(s.onProgress,{phase:"extract",agentId:s.agentId,version:s.version}),await Ll(t,e),await he.unlink(t).catch(()=>{});try{await he.rename(e,s.installDir)}catch(n){let r=n;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await wr(s.installDir)){await he.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Mt(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version});return}throw n}Pt(`hydra-acp: installed ${s.agentId} to ${s.installDir}`),Mt(s.onProgress,{phase:"installed",agentId:s.agentId,version:s.version})}catch(t){throw await he.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Mt(s,e){if(s)try{s(e)}catch{}}async function jl(s){let e=Hl(s.url),t=st.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=Ei.createWriteStream(t),i=Nl.fromWeb(n.body);Mt(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",p=>{a+=p.length;let m=Date.now();m-c>=l&&(c=m,Mt(s.onProgress,{phase:"download_progress",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r})),m-d>=u&&(d=m,Pt(xi(s.agentId,a,r)))}),await new Promise((p,m)=>{i.on("error",m),o.on("error",m),o.on("finish",()=>p()),i.pipe(o)}),Pt(xi(s.agentId,a,r,!0)),Mt(s.onProgress,{phase:"download_done",agentId:s.agentId,version:s.version,receivedBytes:a,totalBytes:r}),t}function xi(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 Hl(s){let e=new URL(s);return st.posix.basename(e.pathname)||"archive"}async function Ll(s,e){let t=s.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await yr("tar",["-xf",s,"-C",e]);return}if(t.endsWith(".zip")){if(await Ul("unzip")){await yr("unzip",["-q",s,"-d",e]);return}await yr("tar",["-xf",s,"-C",e]);return}throw new Error(`Unsupported archive format: ${s}`)}function yr(s,e){return new Promise((t,n)=>{let r=Ti(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 Ul(s){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",n=Ti(t,[s],{stdio:"ignore"});n.on("error",()=>e(!1)),n.on("exit",r=>e(r===0))})}async function wr(s){try{return await he.access(s),!0}catch{return!1}}G();import*as Ie from"fs/promises";import*as He from"path";import{delimiter as Ql}from"path";import{spawn as Yl}from"child_process";import{statSync as Bl}from"fs";import{delimiter as Wl,join as ql}from"path";var zl=".COM;.EXE;.BAT;.CMD";function Mi(s){try{return Bl(s).isFile()}catch{return!1}}function Jl(s){let e=(s.PATHEXT??zl).split(";").map(n=>n.trim()).filter(n=>n.length>0),t=[];for(let n of e)for(let r of[n,n.toLowerCase(),n.toUpperCase()])t.includes(r)||t.push(r);return t}function Vl(s,e){let t=s.toLowerCase();return e.some(n=>t.endsWith(n.toLowerCase()))}function Gl(s,e={}){if((e.platform??process.platform)!=="win32")return s;let n=e.env??process.env,r=Jl(n);if(Vl(s,r))return s;if(/[\\/]/.test(s)){for(let i of r){let a=s+i;if(Mi(a))return a}return s}let o=n.PATH??n.Path??"";for(let i of o.split(Wl).filter(a=>a.length>0))for(let a of r){let d=ql(i,s+a);if(Mi(d))return d}return s}var Kl=/["%\r\n]/;function _i(s){if(Kl.test(s))throw new Error(`cannot pass ${JSON.stringify(s)} through cmd.exe: it contains a quote, a percent sign, or a newline, none of which can be escaped unambiguously`);return/[\s&|<>^()]/.test(s)?`"${s}"`:s}function _t(s,e,t={}){let n=t.platform??process.platform,r=Gl(s,t);return n!=="win32"||!/\.(cmd|bat)$/i.test(r)?{command:r,args:[...e],shell:!1}:{command:_i(r),args:e.map(_i),shell:!0}}var Sr=s=>{process.stderr.write(s+`
12
12
  `)};function Ir(s){Sr=s??(e=>process.stderr.write(e+`
@@ -20,7 +20,7 @@ stderr: ${l}`:`npm install ${s.packageSpec} failed (${u})`))})})}catch(t){if(t.c
20
20
  `),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}
21
21
  stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...Bn(),...e.plan.env,...e.extraEnv??{}},n=_t(e.plan.command,e.plan.args),r=kf(n.command,n.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],shell:n.shell,windowsHide:!0,detached:!0});return r.unref(),new s(e,r)}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()} ---
22
22
  `),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()} ---
23
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(oa),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${oa}ms after SIGKILL; giving up on the reap`)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0){if(process.platform==="win32"){try{vf("taskkill",["/pid",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0})}catch{try{this.child.kill()}catch{}}return}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)})}},Sf=2e3,oa=5e3;function If(s){try{let e=x.agentLogFile(s);Kn.mkdirSync(ia.dirname(e),{recursive:!0});let t=Kn.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as At from"fs/promises";import*as jd from"os";import*as aa from"os";function cn(){return aa.hostname()}import*as Rn from"path";import{customAlphabet as Vg}from"nanoid";var We="session/set_model",Mr="session/set_config_option",ua="model";function Pr(s){return!s||typeof s!="object"||Array.isArray(s)?!1:Array.isArray(s.availableModels)}function la(s){return Array.isArray(s)&&s.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===ua)}function Nt(s){if(!s)return;if(Pr(s)||Pr(s.models))return We;let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))if(t!=="hydra-acp"&&Pr(n))return We}if(la(s.configOptions))return Mr}function fa(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.sessionUpdate;if(e==="_hydra_current_model_update")return We;if(e==="config_option_update"&&la(s.configOptions))return Mr}function da(s){return typeof s=="object"&&s!==null&&s.code===E.MethodNotFound}function ca(s,e,t,n){let r={...n??{}};return delete r.sessionId,delete r.modelId,delete r.configId,delete r.value,s===We?{...r,sessionId:e,modelId:t}:{...r,sessionId:e,configId:ua,value:t}}function Af(s){return s===We?Mr:We}async function at(s){let{request:e,sessionId:t,modelId:n,extraParams:r,logger:o}=s,i=s.verb??We;try{let a=await e(i,ca(i,t,n,r));return{verb:i,result:a}}catch(a){if(!da(a))throw a;let d=Af(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(n)}`);try{let c=await e(d,ca(d,t,n,r));return{verb:d,result:c}}catch(c){throw da(c)?a:c}}}async function ht(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 yt(s){let{agent:e,upstreamSessionId:t,persistedModel:n,agentReportedModel:r,modelVerb:o,logger:i}=s;if(!n)return{modelId:r};if(n===r)return{modelId:n};try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`);let{verb:a,result:d}=await at({request:(c,u)=>e.connection.request(c,u),sessionId:t,modelId:n,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(n)}`),{modelId:n,result:d}}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)}`),{modelId:r}}}import{customAlphabet as La}from"nanoid";function Ye(s){return`${s.name}:${s.localId}`}function dt(s){let e=s.indexOf(":");if(e===-1)return;let t=s.slice(0,e),n=s.slice(e+1);if(!(t.length===0||n.length===0))return{name:t,localId:n}}import{createHmac as Cf}from"crypto";function Rf(s,e){return Cf("sha256",s).update(e).digest("hex")}function _r(s,e){let t=JSON.stringify(e),n=Rf(s.secret,t);fetch(s.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":n},body:t}).catch(()=>{})}var pa="edit",Qn=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 ga(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 ha from"fs/promises";var xf=64*1024*1024,Ef=1*1024*1024,Dt=64*1024,Tf=6e4,Pf=100,Mf=1e3,_f=64*1024,$f=256*1024,ma=20;function Of(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??xf,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ef,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,Dt));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,Dt)),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,Dt)),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,Tf));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(Of(e.pattern),d),u=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??Pf,Mf)),p=Math.max(1,Math.min(e.maxBytes??_f,$f)),m=Math.max(0,Math.min(e.contextBefore??0,ma)),h=Math.max(0,Math.min(e.contextAfter??0,ma)),f=[],g=[],w=[],y=0,k=!1,b=0,I=0,v=(R,T)=>{for(let M of w)M.remaining>0&&(M.match.after===void 0&&(M.match.after=[]),M.match.after.push({cursor:R,line:T}),M.remaining--,y+=T.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test(T)!==u&&f.length<l){let M={cursor:R,line:T};if(m>0&&g.length>0){M.before=g.slice();for(let W of M.before)y+=W.line.length}y+=T.length,f.push(M),h>0&&w.push({match:M,remaining:h})}if(m>0)for(g.push({cursor:R,line:T});g.length>m;)g.shift();let H=f.length>=l&&w.length===0,J=y>=p;return H||J};for(let R=0;R<i.length;R++){if(i[R]!==10)continue;let T=i.subarray(b,R).toString("utf8"),_=r+b;if(b=R+1,I=b,v(_,T)){k=!0;break}}if(!k&&b<i.length&&this.closed){let R=i.subarray(b).toString("utf8"),T=r+b;v(T,R)&&(k=!0),I=i.length}let A=Math.min(r+I,this.writeCursor),C={matches:f,truncated:k,nextCursor:A,scannedBytes:I};return o>0&&(C.gap=o),this.closed&&A>=this.writeCursor&&(C.eof=!0),C}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(()=>ha.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var jt=[{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] [prompt]",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). A prompt is sent to the fork as its first turn once it's ready."},{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."}],ev=new Map(jt.map(s=>[s.verb,s]));function ya(s){let e=s.lastIndexOf("/");return(e===-1?s:s.slice(e+1)).toLowerCase()}function Ht(s,e){return Lt(s,e.map(t=>t.modelId))}function Lt(s,e){if(e.length===0)return{kind:"none",requested:s};if(e.includes(s))return{kind:"exact",modelId:s};let t=ya(s),n=e.filter(o=>ya(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}}var Ff="Compact conversation",Nf="contextCompaction",Df=`
23
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(oa),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${oa}ms after SIGKILL; giving up on the reap`)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0){if(process.platform==="win32"){try{vf("taskkill",["/pid",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0})}catch{try{this.child.kill()}catch{}}return}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)})}},Sf=2e3,oa=5e3;function If(s){try{let e=x.agentLogFile(s);Kn.mkdirSync(ia.dirname(e),{recursive:!0});let t=Kn.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as At from"fs/promises";import*as jd from"os";import*as aa from"os";function cn(){return aa.hostname()}import*as Rn from"path";import{customAlphabet as Vg}from"nanoid";var We="session/set_model",Mr="session/set_config_option",ua="model";function Pr(s){return!s||typeof s!="object"||Array.isArray(s)?!1:Array.isArray(s.availableModels)}function la(s){return Array.isArray(s)&&s.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===ua)}function Nt(s){if(!s)return;if(Pr(s)||Pr(s.models))return We;let e=s._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))if(t!=="hydra-acp"&&Pr(n))return We}if(la(s.configOptions))return Mr}function fa(s){if(!s||typeof s!="object"||Array.isArray(s))return;let e=s.sessionUpdate;if(e==="_hydra_current_model_update")return We;if(e==="config_option_update"&&la(s.configOptions))return Mr}function da(s){return typeof s=="object"&&s!==null&&s.code===E.MethodNotFound}function ca(s,e,t,n){let r={...n??{}};return delete r.sessionId,delete r.modelId,delete r.configId,delete r.value,s===We?{...r,sessionId:e,modelId:t}:{...r,sessionId:e,configId:ua,value:t}}function Af(s){return s===We?Mr:We}async function at(s){let{request:e,sessionId:t,modelId:n,extraParams:r,logger:o}=s,i=s.verb??We;try{let a=await e(i,ca(i,t,n,r));return{verb:i,result:a}}catch(a){if(!da(a))throw a;let d=Af(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(n)}`);try{let c=await e(d,ca(d,t,n,r));return{verb:d,result:c}}catch(c){throw da(c)?a:c}}}async function ht(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 yt(s){let{agent:e,upstreamSessionId:t,persistedModel:n,agentReportedModel:r,modelVerb:o,logger:i}=s;if(!n)return{modelId:r};if(n===r)return{modelId:n};try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(n)} to agent (agentReported=${JSON.stringify(r)})`);let{verb:a,result:d}=await at({request:(c,u)=>e.connection.request(c,u),sessionId:t,modelId:n,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(n)}`),{modelId:n,result:d}}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)}`),{modelId:r}}}import{customAlphabet as La}from"nanoid";function qe(s){return`${s.name}:${s.localId}`}function dt(s){let e=s.indexOf(":");if(e===-1)return;let t=s.slice(0,e),n=s.slice(e+1);if(!(t.length===0||n.length===0))return{name:t,localId:n}}import{createHmac as Cf}from"crypto";function Rf(s,e){return Cf("sha256",s).update(e).digest("hex")}function _r(s,e){let t=JSON.stringify(e),n=Rf(s.secret,t);fetch(s.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":n},body:t}).catch(()=>{})}var pa="edit",Qn=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 ga(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 ha from"fs/promises";var xf=64*1024*1024,Ef=1*1024*1024,Dt=64*1024,Tf=6e4,Pf=100,Mf=1e3,_f=64*1024,$f=256*1024,ma=20;function Of(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??xf,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ef,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,Dt));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,Dt)),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,Dt)),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,Tf));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(Of(e.pattern),d),u=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??Pf,Mf)),p=Math.max(1,Math.min(e.maxBytes??_f,$f)),m=Math.max(0,Math.min(e.contextBefore??0,ma)),h=Math.max(0,Math.min(e.contextAfter??0,ma)),f=[],g=[],w=[],y=0,k=!1,b=0,I=0,v=(R,T)=>{for(let M of w)M.remaining>0&&(M.match.after===void 0&&(M.match.after=[]),M.match.after.push({cursor:R,line:T}),M.remaining--,y+=T.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test(T)!==u&&f.length<l){let M={cursor:R,line:T};if(m>0&&g.length>0){M.before=g.slice();for(let W of M.before)y+=W.line.length}y+=T.length,f.push(M),h>0&&w.push({match:M,remaining:h})}if(m>0)for(g.push({cursor:R,line:T});g.length>m;)g.shift();let H=f.length>=l&&w.length===0,J=y>=p;return H||J};for(let R=0;R<i.length;R++){if(i[R]!==10)continue;let T=i.subarray(b,R).toString("utf8"),_=r+b;if(b=R+1,I=b,v(_,T)){k=!0;break}}if(!k&&b<i.length&&this.closed){let R=i.subarray(b).toString("utf8"),T=r+b;v(T,R)&&(k=!0),I=i.length}let A=Math.min(r+I,this.writeCursor),C={matches:f,truncated:k,nextCursor:A,scannedBytes:I};return o>0&&(C.gap=o),this.closed&&A>=this.writeCursor&&(C.eof=!0),C}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(()=>ha.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var jt=[{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] [prompt]",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). A prompt is sent to the fork as its first turn once it's ready."},{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."}],ev=new Map(jt.map(s=>[s.verb,s]));function ya(s){let e=s.lastIndexOf("/");return(e===-1?s:s.slice(e+1)).toLowerCase()}function Ht(s,e){return Lt(s,e.map(t=>t.modelId))}function Lt(s,e){if(e.length===0)return{kind:"none",requested:s};if(e.includes(s))return{kind:"exact",modelId:s};let t=ya(s),n=e.filter(o=>ya(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}}var Ff="Compact conversation",Nf="contextCompaction",Df=`
24
24
 
25
25
  Compacting completed.`;function jf(s){if(!s||s.status!=="completed"||s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return!1;let e=s._meta,t=e!==null&&typeof e=="object"&&Nf in e;return s.title===Ff||t}function Hf(s){if(!s||s.sessionUpdate!=="agent_message_chunk")return!1;let e=s.content;return!e||typeof e!="object"||Array.isArray(e)?!1:e.text===Df}function wa(s){return jf(s)||Hf(s)}function va(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=$r(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 qf){if(!ka(c[l]))continue;let p=n.get(u);p===void 0?n.set(u,new Map([[l,c[l]]])):p.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=$r(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?(Bf(r,o.outIndex,Lf(c.content)),Uf(r,o.outIndex,d.seq)):(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 p=l!==void 0&&t.has(l)?Wf(d,t.get(l)??[]):d,m=l===void 0?void 0:n.get(l);if(m!==void 0)for(let[h,f]of m)ka($r(p)?.[h])||(p=zf(p,h,f));r.push(p);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 $r(s){if(s.method!=="session/update")return;let t=s.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Lf(s){if(!s||typeof s!="object")return"";let e=s;return typeof e.text=="string"?e.text:""}function Uf(s,e,t){let n=s[e];n===void 0||typeof t!="number"||n.seq!==void 0&&n.seq>=t||(s[e]={...n,seq:t})}function Bf(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 Wf(s,e){let t=s.params??{},n=t.update??{};return{...s,params:{...t,update:{...n,content:e}}}}var qf=["rawInput","locations"];function ka(s){return s==null||typeof s!="object"?!1:Array.isArray(s)?s.length>0:Object.keys(s).length>0}function zf(s,e,t){let n=s.params??{},r=n.update??{};return{...s,params:{...n,update:{...r,[e]:t}}}}var ba=`[older history truncated]
26
26
  `,Sa=["file_path","filePath","path","command","pattern","query"];function Ut(s,e={}){let t=e.maxChars??4e5,n=Or(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 p=jr(u.prompt).trim();p.length>0&&r.push(`User: ${p}`)}else if(l==="agent_message_chunk"){let p=Hr(u.content);p.length>0&&(o+=p)}else if(l==="tool_call"){if(a(),r.push(Dr(u,n)),e.toolOutput!==void 0){let p=Nr(u),m=p!==void 0?n.get(p)?.output:void 0;if(m!==void 0&&i>0){let h=Math.min(e.toolOutput.maxPerCall,i),f=m.length<=h?m:`${m.slice(0,h)}\u2026[${m.length-h} more chars]`;r.push(`Output: ${f}`),i-=Math.min(f.length,h)}}}else l==="turn_complete"&&a()}return a(),Xf(r.join(`
@@ -32,10 +32,10 @@ Compacting completed.`;function jf(s){if(!s||s.status!=="completed"||s.sessionUp
32
32
  `)}`}function Aa(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 Zf(s,e,t,n){if(s.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=ep(s),i=0,a=[];if(e>0&&r.length>0){let u=r.filter(m=>m.startEntryIndex>=t).length,l=Math.max(u,n),p=Math.min(l,e,r.length);i=p,a=p>0?r.slice(-p):[]}let d=a.length>0?Ca(a):"",c=o?Ca([o]):"";return{closedText:d,openText:c,keptCount:i}}function Ca(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(`
33
33
  `)}function ep(s){let e=[],t=null,n=Or(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:jr(d.prompt).trim(),agent:"",tools:[],startEntryIndex:o};else if(c==="agent_message_chunk"&&t!==null){let u=Hr(d.content);u.length>0&&(t.agent+=u)}else c==="tool_call"&&t!==null?t.tools.push(Dr(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 xa(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.usedAtStart!==void 0?{usedAfter:c.usedAtStart}:{},...u.usedAtEnd!==void 0?{usedBefore:u.usedAtEnd}:{},...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:tp(a),unknownCount:r.filter(d=>d.reason===void 0&&d.inferredReason===void 0&&!d.notCompaction).length}}function tp(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),n.usedAfter!==void 0&&(r.usedAfter=n.usedAfter);continue}e.push({...n.at!==void 0?{at:n.at}:{},upstreamSessionId:n.upstreamSessionId,swaps:1,...n.cost!==void 0?{cost:n.cost}:{},...n.usedBefore!==void 0?{usedBefore:n.usedBefore}:{},...n.usedAfter!==void 0?{usedAfter:n.usedAfter}:{},current:n.endedAt===void 0}),t=n.runId}return e}function np(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 Ra(s){if(s<1e3)return String(s);let e=s/1e3;return e<100?`${e.toFixed(1)}k`:`${Math.round(e)}k`}function sp(s){return s.usedBefore===void 0||s.usedAfter===void 0?"":` ${Ra(s.usedBefore)} \u2192 ${Ra(s.usedAfter)}`}function Ea(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=sp(r),i=r.cost!==void 0?` $${r.cost.toFixed(2)}`:"",a=r.current?" (current)":"",d=r.swaps>1?` (${r.swaps} swaps)`:"";n.push(` ${np(r.at)} ${r.upstreamSessionId}${o}${i}${d}${a}`)}}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}import*as ct from"path";function rp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ur(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(`${rp(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 Br(s,e){if(e.length===0)return!1;let t=e.endsWith("/")?e.slice(0,-1):e;return s.includes(t)}function Ta(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(`
34
34
  `)}function Pa(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(`
35
- `)}function Ma(s,e,t){return s.length===0||!ct.isAbsolute(s)||Zn(s,t)?!1:Zn(s,e)}function Zn(s,e){let t=ct.relative(ct.resolve(e),ct.resolve(s));return!(t.length===0||t.startsWith("..")||ct.isAbsolute(t))}G();import*as qe from"fs/promises";async function fn(s,e){let t=x.queueFile(s);if(e.length===0){await qe.unlink(t).catch(()=>{});return}await qe.mkdir(x.sessionDir(s),{recursive:!0});let n=e.map(r=>JSON.stringify(r)).join(`
35
+ `)}function Ma(s,e,t){return s.length===0||!ct.isAbsolute(s)||Zn(s,t)?!1:Zn(s,e)}function Zn(s,e){let t=ct.relative(ct.resolve(e),ct.resolve(s));return!(t.length===0||t.startsWith("..")||ct.isAbsolute(t))}G();import*as ze from"fs/promises";async function fn(s,e){let t=x.queueFile(s);if(e.length===0){await ze.unlink(t).catch(()=>{});return}await ze.mkdir(x.sessionDir(s),{recursive:!0});let n=e.map(r=>JSON.stringify(r)).join(`
36
36
  `)+`
37
- `;await qe.writeFile(t,n,"utf8")}async function _a(s){let e=x.queueFile(s),t;try{t=await qe.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t.split(`
38
- `))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 $a(s){let e=x.queueFile(s);await qe.unlink(e).catch(()=>{})}import*as Wa from"fs/promises";var Ua="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ba=La(Ua,16),Wr=La(Ua,16),op=20,ip=20,ap=5,dp=32,Ae="hydra_session_";function ze(){return`m_${Ba()}`}function Xe(s){let e=dt(s)?.localId??s;return e.startsWith(Ae)?e.slice(Ae.length):e}var Oa=["start","merge","apply","sync","stop","detach","discard","clean","status"],cp=1e3,es=300*1e3,up=64,lp=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);function fp(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"&&lp.has(r)}function Fa(s){let e=s?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="usage_update"}function pp(s){let e=s?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="tool_call_update"}function gp(s,e){return e===void 0?!1:s.some(t=>{if(!t||typeof t!="object")return!1;let n=t.id;return typeof n=="string"&&n.trim()!==""&&n.trim()!==e})}var qr=120;function mp(s){let e=s.split(`
37
+ `;await ze.writeFile(t,n,"utf8")}async function _a(s){let e=x.queueFile(s),t;try{t=await ze.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t.split(`
38
+ `))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 $a(s){let e=x.queueFile(s);await ze.unlink(e).catch(()=>{})}import*as Wa from"fs/promises";var Ua="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ba=La(Ua,16),Wr=La(Ua,16),op=20,ip=20,ap=5,dp=32,Ae="hydra_session_";function Je(){return`m_${Ba()}`}function Xe(s){let e=dt(s)?.localId??s;return e.startsWith(Ae)?e.slice(Ae.length):e}var Oa=["start","merge","apply","sync","stop","detach","discard","clean","status"],cp=1e3,es=300*1e3,up=64,lp=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);function fp(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"&&lp.has(r)}function Fa(s){let e=s?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="usage_update"}function pp(s){let e=s?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="tool_call_update"}function gp(s,e){return e===void 0?!1:s.some(t=>{if(!t||typeof t!="object")return!1;let n=t.id;return typeof n=="string"&&n.trim()!==""&&n.trim()!==e})}var qr=120;function mp(s){let e=s.split(`
39
39
  `).map(t=>t.trim()).filter(t=>t!=="");return e.length===0?"":e[e.length-1]}var hp=128,yp=new Set(["local_bash"]),wp=1e3,Bt=class s{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;modelVerb=We;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;lastUnsolicitedCancelAt=0;cancelReopenStreak=0;static UNSOLICITED_REOPEN_WINDOW_MS=1e4;static UNSOLICITED_REOPEN_LIMIT=3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}_titleSeedPending=!0;_upstreamRespawned=!1;promptStartedAt;turnRanTool=!1;unsolicitedTurn;pendingSteerDetach;supersededAutonomousTurn;autonomousSalvage;lastBackgroundTask;toolLabels=new Map;armedTasks=new Map;lastArmedBroadcast;liveBackgroundTasks=new Map;sawBackgroundTaskLevel=!1;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;orphanTimeoutMs;orphanTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;lastSeq=0;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 Qn;filesEditedSeen=new Set;openToolCalls=new Map;agentChangeHandlers=[];retiringGenerationCost;retiringGenerationUsed;rotationLifetimeCost;agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];configOptionsHandlers=[];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;pendingTurnNotifiers=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Ae}${Ba()}`,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]),e.agentConfigOptions&&e.agentConfigOptions.length>0&&(this.agentAdvertisedConfigOptions=[...e.agentConfigOptions]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.orphanTimeoutMs=e.orphanTimeoutMs??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._titleSeedPending=!1),e.upstreamRespawned&&(this._upstreamRespawned=!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??cp,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:"_hydra_available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"_hydra_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,t){this.resetBackgroundTaskLevel(),t?.respawn&&(this._upstreamRespawned=!0),e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){Mp(this.internalPromptCapture,n);return}this.maybeEmitToolEdges(n),this.runResponseChain(n)}),e.connection.onNotification("_claude/sdkMessage",n=>{this.applyBackgroundTaskLevel(n)}),e.connection.onRequest("session/request_permission",async n=>{let r=await this.runAgentRequestChain("session/request_permission",n),o=Da(r.shortCircuit?n:r.envelope);if(r.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:r.payload,sourceWasTransformer:!0}),r.payload;let i=await this.handlePermissionRequest(r.envelope);return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),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 p=`t_${Wr()}`,m;try{m=await l.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${l.name} error on ${a}: ${f.message}`);continue}let h=m?.action??"continue";if(h==="stop")return;if(h==="processing"){let f=u,g=i,w=new Set(t),y=r;await new Promise(k=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:l.name}),this.runResponseChain(g,new Set([...w,l.name]),f+1,y).then(()=>k()).catch(()=>k()))},es);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>k(),timer:b,transformerName:l.name,method:y,envelope:g,chainIdx:f,originatedBy:w,side:"response"})});return}m?.payload&&typeof m.payload=="object"&&(i=m.payload),t.add(l.name)}if(r!=="session/update")return;this.noteAgentActivity(i),wa(i.update)&&this.armRecallInPlace().catch(u=>{this.logger?.warn(`armRecallInPlace failed: ${u.message}`)});let d=_p(i);if(d!==null){this.setAgentAdvertisedCommands(d);return}let c=Pp(i);if(c!==null){this.setAgentAdvertisedModes(c);return}if(this.noteModelVerbHint(fa(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)}async armRecallInPlace(){if(!this.historyStore)return;let e=await this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0);if(!(e<=(this._summarizedThroughEntry??0))){if(this._summarizedThroughEntry=e,this.persistWatermarkHook)try{this.persistWatermarkHook(e)}catch(t){this.logger?.warn(`armRecallInPlace: persistWatermarkHook failed: ${t.message}`)}this.broadcastQueueNotification("hydra-acp/context_self_compacted",{sessionId:this.sessionId})}}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=this.pendingOneShotBackgroundTasks();if(e.length>0)return`${e.length} background task(s) still running (${e.join(", ")}); a swap would kill the agent process and abandon them. Wait for them to finish, or cancel them, then try again`;let t=await this.openToolCallIdsInHistory();if(t.length>0)return`${t.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 p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],m=await l({agentId:n,cwd:i,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:p});if(this.accumulateAndResetCost(),this.cwd=i,this.wireAgent(m.agent,{respawn:!0}),!r){let _=await yt({agent:m.agent,upstreamSessionId:m.upstreamSessionId,persistedModel:c,agentReportedModel:m.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(_.result,"model"),await ht({agent:m.agent,upstreamSessionId:m.upstreamSessionId,persistedMode:u,agentReportedMode:m.initialMode,logger:this.logger})}m.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(_){this.logger?.warn(`swapUpstream: historyStore.load failed: ${_.message}`)}let f=Lr({...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:h,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 g,w;try{await m.agent.connection.request("session/prompt",{sessionId:m.upstreamSessionId,prompt:[{type:"text",text:f}]});let _=this.internalPromptCapture;g=_.lastUsed,w=_.lastSize,this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${f.length} toolCalls=${_.toolCalls} thinkingChars=${_.thinkingChars} messageChars=${_.messageChars} used=${_.lastUsed??"?"} size=${_.lastSize??"?"} reply=${JSON.stringify(_.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}g!==void 0&&(this.maybeApplyAgentUsage({update:{sessionUpdate:"usage_update",used:g,...w!==void 0?{size:w}:{}}}),this.broadcastCurrentUsage());let y=this.upstreamSessionId,k=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let b=this.agent;if(this.agent=m.agent,this.upstreamSessionId=m.upstreamSessionId,this.agentMeta=m.agentMeta,this.agentCapabilities=m.agentCapabilities,this.resetModelVerb(m.modelVerb),r&&(this.agentId=n,this.agentAdvertisedCommands=[],this.currentModel=m.initialModel,this.currentMode=m.initialMode,this.setAgentAdvertisedModels(m.initialModels??[]),this.setAgentAdvertisedModes(m.initialModes??[]),this.agentAdvertisedConfigOptions=m.initialConfigOptions??[]),this.broadcastMergedCommands(),this.broadcastConfigOptions(),this.notifyAgentChange("swapUpstream",o,e.runId,g),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:y,...k!==void 0?{previousSummarizedThroughEntry:k}:{},...e.runId!==void 0?{runId:e.runId}:{}})}catch(_){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${_.message}`)}let I=await this.retireAgent(b,r?"agent switch":e.reason==="workspace-enter"||e.reason==="workspace-leave"?"workspace move":"compaction swap");this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,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 v=I.length>0?`
40
40
  Stopped ${I.length} background task(s) with the previous agent: ${I.join(", ")}. Re-arm anything still needed.
41
41
  `:"",R=(e.reason==="workspace-enter"||e.reason==="workspace-leave"?"":r?`
@@ -46,7 +46,7 @@ Compaction completed.
46
46
 
47
47
  `),this.departureNoteSent=!0}return r}applyWorkspacePromptRewrite(e){let t=this.workspace;if(t===void 0)return this.applyDepartedPromptRewrite(e);let n=!1,r=ja(e,i=>Br(i,t.sourceCwd)?(n=!0,Ur(i,t.sourceCwd,t.path).text):i);if(!this.workspacePreambleSent||n){let i=Pa({workspacePath:t.path,sourceCwd:t.sourceCwd,notes:this.workspaceNotes,...this.workspacePreambleSent?{reassert:!0}:{}});r=Jr(r,`${i}
48
48
 
49
- `),this.workspacePreambleSent=!0}return r}async prompt(e,t,n,r){let o=this.clients.get(e);if(!o)throw be(new Error("client not attached"),E.SessionNotFound);if(this.closing)throw be(new Error("session is closing; new prompts cannot be accepted"),E.SessionClosing);let i=ze();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(rt((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0,this.cancelOrphanTimer();for(let d of this.interactiveHandlers)try{d(!0)}catch{}}return this.enqueueUserPrompt(o,t,i,n,r)}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.turnRanTool=!1,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let n=wt(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(()=>{})}originatorNeedsTurnComplete(e){return e.wasAmend===!0||e.wasSteer===!0}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:ze()};o!==void 0&&(i.stopReason=o);let a=rt(t?._meta).salvaged;a!==void 0&&(i._meta={[ae]:{salvaged:a}}),this.supersededAutonomousTurn=void 0;let d=this.amendInProgress;if(d&&n!==void 0&&d.cancelledMessageId===n&&(i._meta={[ae]:{...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);let c=this.pendingTurnNotifiers.get(n);c&&(this.pendingTurnNotifiers.delete(n),_r(c,{sessionId:this.sessionId,messageId:c.originalMessageId,stopReason:o,deliveredAt:Date.now(),...n!==c.originalMessageId?{amendedTo:n}:{}}))}o==="cancelled"||o==="error"||o==="refusal"?this.closeOpenToolCalls(o):this.armOpenToolCalls(),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(fp(e)||this.steerCausedTurnTerminal(e)){if(this.unsolicitedTurn!==void 0){this.closeUnsolicitedTurn("completed");return}this.salvageSupersededTerminal();return}this.pendingSteerDetach!==void 0&&this.currentEntry?.messageId===this.pendingSteerDetach.messageId&&Fa(e)&&(this.pendingSteerDetach=void 0),!zr("session/update",e)&&(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||pp(e)||this.openUnsolicitedTurn()))}}steerCausedTurnTerminal(e){return this.unsolicitedTurn?.steerCaused!==!0?!1:Fa(e)}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=Rp(t._meta);this.rememberToolLabel(n,t,r,o),this.noteBackgroundTaskStopped(t,r,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:Cp(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,p=Ap(t.title,o,r)||u?.repeating===!0;this.armedTasks.set(n,{label:d,...l!==void 0?{taskId:l}:{},repeating:p,armedAt:u?.armedAt??c}),this.onArmedTasksChanged()}applyBackgroundTaskLevel(e){let t=e?.message;if(!t||t.subtype!=="background_tasks_changed")return;let n=t.tasks;if(!Array.isArray(n))return;let r=Date.now(),o=new Map;for(let a of n){let d=a,c=typeof d?.task_id=="string"?d.task_id:void 0;c!==void 0&&o.set(c,{taskType:typeof d?.task_type=="string"?d.task_type:"unknown",description:typeof d?.description=="string"?d.description:"",firstSeen:this.liveBackgroundTasks.get(c)?.firstSeen??r})}let i=[...this.liveBackgroundTasks.keys()].filter(a=>!o.has(a));this.liveBackgroundTasks=o,this.sawBackgroundTaskLevel=!0,this.logger?.info(`session ${this.sessionId} background level: ${o.size} live`+(i.length>0?` (ended: ${i.join(", ")})`:"")),this.onArmedTasksChanged()}get armedBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.entries()].map(([e,t])=>({taskId:e,label:t.description||t.taskType,taskType:t.taskType,since:t.firstSeen})):[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{},since:t.armedAt}))}pendingOneShotBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.values()].filter(e=>yp.has(e.taskType)).map(e=>e.description||e.taskType):[...this.armedTasks.values()].filter(e=>!e.repeating).map(e=>e.label)}get armedSince(){let e;if(this.sawBackgroundTaskLevel){for(let t of this.liveBackgroundTasks.values())(e===void 0||t.firstSeen<e)&&(e=t.firstSeen);return e}for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedBackgroundTasks,t=e.length,n=this.armedSince,r=e.map(o=>o.taskId??o.toolCallId??o.label).sort().join("\0");r===this.lastArmedBroadcast?.key&&n===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={key:r,since:n},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:t,...n!==void 0?{since:n}:{},tasks:e}),this.dispatchIdle())}async retireAgent(e,t){return await e.kill().catch(()=>{}),this.resetBackgroundTaskLevel(),this.discardArmedTasks(t)}resetBackgroundTaskLevel(){this.liveBackgroundTasks.clear(),this.sawBackgroundTaskLevel=!1}discardArmedTasks(e){if(this.armedTasks.size===0)return[];let t=[...this.armedTasks.values()].map(n=>n.label);for(let[n,r]of this.armedTasks)r.openToolCall===!0&&this.openToolCalls.delete(n);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,qr),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,qr),fromDescription:!1})}for(;this.toolLabels.size>hp;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now();if(this.lastUnsolicitedCancelAt!==0&&e-this.lastUnsolicitedCancelAt<=s.UNSOLICITED_REOPEN_WINDOW_MS?this.cancelReopenStreak+=1:this.cancelReopenStreak=0,this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak>=s.UNSOLICITED_REOPEN_LIMIT){this.escalateUnresponsiveCancel();return}let t=this.lastBackgroundTask,n=!1;for(let[i,a]of this.armedTasks)a.repeating||a.openToolCall===!0||(this.armedTasks.delete(i),n=!0);n&&this.onArmedTasksChanged();let r={messageId:ze(),startedAt:e,cause:t,steerCaused:this.pendingSteerDetach!==void 0};this.pendingSteerDetach=void 0,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:"_hydra_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,wp);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,e==="cancelled"?this.lastUnsolicitedCancelAt=Date.now():(this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak=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"):e==="completed"&&this.armOpenToolCalls(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_ended",messageId:ze(),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:{[ae]:{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>up;){let n=this.recentlyTerminal.keys().next().value;if(n===void 0)break;this.recentlyTerminal.delete(n)}}registerTurnNotify(e,t,n){let r=this.recentlyTerminal.get(e);if(r)return{alreadyTerminal:!0,stopReason:r.stopReason};for(this.pendingTurnNotifiers.set(e,{callbackUrl:t,secret:n,registeredAt:Date.now(),originalMessageId:e});this.pendingTurnNotifiers.size>dp;){let o=this.pendingTurnNotifiers.keys().next().value;if(o===void 0)break;this.pendingTurnNotifiers.delete(o)}return{alreadyTerminal:!1}}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 be(new Error("client not attached"),E.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=ze(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let c=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}c.push(u)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:n,position:1}),this.amendInProgress={cancelledMessageId:n,newMessageId:o};let d=this.pendingTurnNotifiers.get(n);return d&&(this.pendingTurnNotifiers.delete(n),this.pendingTurnNotifiers.set(o,d)),this.cancelExtensionDispatch(n,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}async steer(e,t){let n=this.clients.get(e);if(!n)throw be(new Error("client not attached"),E.SessionNotFound);let r=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled;if(r&&this.agent.steeringSupported){this.pendingSteerDetach={messageId:this.currentEntry.messageId};let o;try{o=await this.forwardRequest("_session/steering",t)}catch(d){throw this.pendingSteerDetach=void 0,d}let i=o?.outcome,a=i==="injected"||i==="startedNewTurn"||i==="promptRequired"||i==="failed"?o:{outcome:"failed"};return a.outcome!=="startedNewTurn"&&(this.pendingSteerDetach=void 0),a.outcome==="injected"&&this.recordSteerAsUserMessageChunk(t.prompt,e),a.outcome==="startedNewTurn"?{...a,detached:!0}:a}return r?(this.amendOnHead(n,t.prompt,this.currentEntry.messageId,!1),{outcome:"startedNewTurn"}):t._meta?.steering?.idleBehavior==="promptRequired"?{outcome:"promptRequired",reason:"noRunningTurn"}:(this.prompt(e,{sessionId:t.sessionId,prompt:t.prompt},void 0,{steerOriginated:!0}).catch(o=>{this.logger?.warn(`steer-originated prompt failed to enqueue: ${o.message}`)}),{outcome:"startedNewTurn"})}recordSteerAsUserMessageChunk(e,t){let n=wt(e);n.length!==0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},_meta:{"hydra-acp":{steered:!0}}}},t)}enqueueAmendmentAsFollowUp(e,t){let n=ze(),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 be(new Error("client not attached"),E.SessionNotFound);this.logger?.info(`session ${this.sessionId} session/cancel from ${e} promptInFlight=${this.promptInFlight} agentTurnInFlight=${this.agentTurnInFlight} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length}`),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_${Wr()}`,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(m){this.logger?.warn(`transformer ${d.name} error on ${c}: ${m.message}`);continue}let p=l?.action??"continue";if(p==="stop")return o==="notification"?void 0:l?.payload??Vr(e);if(p==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),n.add(d.name);continue}if(p==="processing"){let m=a,h=i,f=new Set(n);return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:d.name}),this.forwardRequest(e,h,new Set([...f,d.name]),m+1,o).then(g).catch(()=>g(o==="notification"?void 0:Vr(e))))},es);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(u,{resolve:g,timer:w,transformerName:d.name,method:e,envelope:h,chainIdx:m,originatedBy:f,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 at({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??We,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_${Wr()}`,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(p){this.logger?.warn(`transformer ${d.name} error on ${i}: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:u?.payload??Lp(e)};if(l==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),n.add(d.name);continue}if(l==="processing"){let p=a,m=o,h=new Set(n),f=e;return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(f,m,new Set([...h,d.name]),p+1).then(g).catch(()=>g({shortCircuit:!1,envelope:m})))},es);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:y=>g({shortCircuit:!0,payload:y}),timer:w,transformerName:d.name,method:f,envelope:m,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):es,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:Vr(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=ze(),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},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(),this.cancelOrphanTimer();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._titleSeedPending=!1,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._titleSeedPending||rt((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let r=wt((e??{}).prompt),o=Kr(r,200);!o||o.startsWith("/")||(this._titleSeedPending=!1,this.setTitle(o))}maybeApplyAgentModel(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="_hydra_current_model_update")return!1;let r=pn(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 i of r)this.applyOneConfigOptionEntry(i);let o=new Set(r.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i&&i!=="model"&&i!=="mode"&&i!=="agent"));return this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id)),this.fireConfigOptionsHandlers(),!0}applyAgentConfigOptionResponse(e,t){let n=e?.configOptions;if(!Array.isArray(n))return!1;let r=JSON.stringify(this.agentAdvertisedConfigOptions);for(let o of n){let i=o?.id;i==="model"||i==="mode"||i==="agent"||this.applyOneConfigOptionEntry(o)}if(gp(n,t)){let o=new Set(n.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i));this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id))}return JSON.stringify(this.agentAdvertisedConfigOptions)!==r}applyOneConfigOptionEntry(e){if(!e||typeof e!="object")return;let t=e;if(t.id==="model"){let f=pn(t.options);f.length>0&&this.setAgentAdvertisedModels(f);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(w)}`),this.applyModelChange(w))}return}if(t.id==="mode"){let f=ts(t.options);f.length>0&&this.setAgentAdvertisedModes(f);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(w)}`),this.applyModeChange(w))}return}if(typeof t.id!="string"||!t.id.trim())return;let n=t.id.trim(),r=Gr(t.options);if(r.length===0)return;let o=t.name,i=typeof o=="string"&&o.trim()?o.trim():n,a=t.category,d=typeof a=="string"&&a.trim()?a.trim():"other",c=t.description,u=typeof c=="string"&&c.trim()?c.trim():void 0,l=t.currentValue,p=typeof l=="string"&&l.trim()?l.trim():r[0].value,m={id:n,name:i,category:d,type:"select",currentValue:p,options:r,...u?{description:u}:{}},h=this.agentAdvertisedConfigOptions.findIndex(f=>f.id===n);h>=0?this.agentAdvertisedConfigOptions[h]=m:this.agentAdvertisedConfigOptions.push(m)}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,r){let o=this.retiringGenerationCost;this.retiringGenerationCost=void 0;let i=this.retiringGenerationUsed;this.retiringGenerationUsed=void 0;let a=this.rotationLifetimeCost;this.rotationLifetimeCost=void 0;for(let d of this.agentChangeHandlers)try{d({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...o!==void 0?{retiredCost:o}:{},...a!==void 0?{lifetimeCost:a}:{},...i!==void 0?{retiredUsed:i}:{},...r!==void 0?{startedUsed:r}:{},...t!==void 0?{reason:t}:{},...n!==void 0?{runId:n}:{}})}catch(c){this.logger?.warn(`${e}: agentChange handler failed: ${c.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=e);let t=this._currentUsage?.used;typeof t=="number"&&t>0&&(this.retiringGenerationUsed=t),this.rotationLifetimeCost=this.cumulativeCost;let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}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(xp(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Ep(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(",")}]`),Tp(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)}onConfigOptionsChange(e){this.configOptionsHandlers.push(e)}extraConfigOptionValues(){return Object.fromEntries(this.agentAdvertisedConfigOptions.map(e=>[e.id,e.currentValue]))}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:"_hydra_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}:{}}));this.currentModel&&!r.some(i=>i.value===this.currentModel)&&r.unshift({value:this.currentModel,name:this.currentModel});let o=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}:{}}));this.currentMode&&!r.some(i=>i.value===this.currentMode)&&r.unshift({value:this.currentMode,name:this.currentMode});let o=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()}}),this.fireConfigOptionsHandlers()}fireConfigOptionsHandlers(){for(let e of this.configOptionsHandlers)try{e(this.agentAdvertisedConfigOptions)}catch{}}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 jt){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 jt)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"||this._upstreamRespawned)return;let r=n.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0,this._titleSeedPending=!1;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(jt.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=E.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=jt.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:p}of this.extensionCommands.list())l.has(p)||(c.push(p),l.add(p))}let u=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw u.code=E.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(h=>h.verb===i)){let h=r.commands.map(f=>f.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 c=()=>{},u=new Promise(h=>{c=h});n!==void 0&&this.inFlightExtensionDispatches.set(n,{extensionName:e,connection:r.connection,cancel:h=>c({stopReason:"cancelled",reason:h})});let l,p=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",d),f=await Promise.race([h,u]);if(f&&typeof f=="object"&&f.stopReason==="cancelled"&&"reason"in f)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=f}catch(h){return this.emitExtensionReply(`${e} ${i}: ${h.message}`)}finally{n!==void 0&&!p&&this.inFlightExtensionDispatches.delete(n)}let m=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return m.length>0?this.emitExtensionReply(m):{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:`
49
+ `),this.workspacePreambleSent=!0}return r}async prompt(e,t,n,r){let o=this.clients.get(e);if(!o)throw be(new Error("client not attached"),E.SessionNotFound);if(this.closing)throw be(new Error("session is closing; new prompts cannot be accepted"),E.SessionClosing);let i=Je();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(rt((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0,this.cancelOrphanTimer();for(let d of this.interactiveHandlers)try{d(!0)}catch{}}return this.enqueueUserPrompt(o,t,i,n,r)}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.turnRanTool=!1,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let n=wt(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(()=>{})}originatorNeedsTurnComplete(e){return e.wasAmend===!0||e.wasSteer===!0}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:Je()};o!==void 0&&(i.stopReason=o);let a=rt(t?._meta).salvaged;a!==void 0&&(i._meta={[ae]:{salvaged:a}}),this.supersededAutonomousTurn=void 0;let d=this.amendInProgress;if(d&&n!==void 0&&d.cancelledMessageId===n&&(i._meta={[ae]:{...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);let c=this.pendingTurnNotifiers.get(n);c&&(this.pendingTurnNotifiers.delete(n),_r(c,{sessionId:this.sessionId,messageId:c.originalMessageId,stopReason:o,deliveredAt:Date.now(),...n!==c.originalMessageId?{amendedTo:n}:{}}))}o==="cancelled"||o==="error"||o==="refusal"?this.closeOpenToolCalls(o):this.armOpenToolCalls(),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(fp(e)||this.steerCausedTurnTerminal(e)){if(this.unsolicitedTurn!==void 0){this.closeUnsolicitedTurn("completed");return}this.salvageSupersededTerminal();return}this.pendingSteerDetach!==void 0&&this.currentEntry?.messageId===this.pendingSteerDetach.messageId&&Fa(e)&&(this.pendingSteerDetach=void 0),!zr("session/update",e)&&(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||pp(e)||this.openUnsolicitedTurn()))}}steerCausedTurnTerminal(e){return this.unsolicitedTurn?.steerCaused!==!0?!1:Fa(e)}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=Rp(t._meta);this.rememberToolLabel(n,t,r,o),this.noteBackgroundTaskStopped(t,r,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:Cp(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,p=Ap(t.title,o,r)||u?.repeating===!0;this.armedTasks.set(n,{label:d,...l!==void 0?{taskId:l}:{},repeating:p,armedAt:u?.armedAt??c}),this.onArmedTasksChanged()}applyBackgroundTaskLevel(e){let t=e?.message;if(!t||t.subtype!=="background_tasks_changed")return;let n=t.tasks;if(!Array.isArray(n))return;let r=Date.now(),o=new Map;for(let a of n){let d=a,c=typeof d?.task_id=="string"?d.task_id:void 0;c!==void 0&&o.set(c,{taskType:typeof d?.task_type=="string"?d.task_type:"unknown",description:typeof d?.description=="string"?d.description:"",firstSeen:this.liveBackgroundTasks.get(c)?.firstSeen??r})}let i=[...this.liveBackgroundTasks.keys()].filter(a=>!o.has(a));this.liveBackgroundTasks=o,this.sawBackgroundTaskLevel=!0,this.logger?.info(`session ${this.sessionId} background level: ${o.size} live`+(i.length>0?` (ended: ${i.join(", ")})`:"")),this.onArmedTasksChanged()}get armedBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.entries()].map(([e,t])=>({taskId:e,label:t.description||t.taskType,taskType:t.taskType,since:t.firstSeen})):[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{},since:t.armedAt}))}pendingOneShotBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.values()].filter(e=>yp.has(e.taskType)).map(e=>e.description||e.taskType):[...this.armedTasks.values()].filter(e=>!e.repeating).map(e=>e.label)}get armedSince(){let e;if(this.sawBackgroundTaskLevel){for(let t of this.liveBackgroundTasks.values())(e===void 0||t.firstSeen<e)&&(e=t.firstSeen);return e}for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedBackgroundTasks,t=e.length,n=this.armedSince,r=e.map(o=>o.taskId??o.toolCallId??o.label).sort().join("\0");r===this.lastArmedBroadcast?.key&&n===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={key:r,since:n},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:t,...n!==void 0?{since:n}:{},tasks:e}),this.dispatchIdle())}async retireAgent(e,t){return await e.kill().catch(()=>{}),this.resetBackgroundTaskLevel(),this.discardArmedTasks(t)}resetBackgroundTaskLevel(){this.liveBackgroundTasks.clear(),this.sawBackgroundTaskLevel=!1}discardArmedTasks(e){if(this.armedTasks.size===0)return[];let t=[...this.armedTasks.values()].map(n=>n.label);for(let[n,r]of this.armedTasks)r.openToolCall===!0&&this.openToolCalls.delete(n);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,qr),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,qr),fromDescription:!1})}for(;this.toolLabels.size>hp;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now();if(this.lastUnsolicitedCancelAt!==0&&e-this.lastUnsolicitedCancelAt<=s.UNSOLICITED_REOPEN_WINDOW_MS?this.cancelReopenStreak+=1:this.cancelReopenStreak=0,this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak>=s.UNSOLICITED_REOPEN_LIMIT){this.escalateUnresponsiveCancel();return}let t=this.lastBackgroundTask,n=!1;for(let[i,a]of this.armedTasks)a.repeating||a.openToolCall===!0||(this.armedTasks.delete(i),n=!0);n&&this.onArmedTasksChanged();let r={messageId:Je(),startedAt:e,cause:t,steerCaused:this.pendingSteerDetach!==void 0};this.pendingSteerDetach=void 0,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:"_hydra_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,wp);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,e==="cancelled"?this.lastUnsolicitedCancelAt=Date.now():(this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak=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"):e==="completed"&&this.armOpenToolCalls(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_ended",messageId:Je(),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:{[ae]:{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>up;){let n=this.recentlyTerminal.keys().next().value;if(n===void 0)break;this.recentlyTerminal.delete(n)}}registerTurnNotify(e,t,n){let r=this.recentlyTerminal.get(e);if(r)return{alreadyTerminal:!0,stopReason:r.stopReason};for(this.pendingTurnNotifiers.set(e,{callbackUrl:t,secret:n,registeredAt:Date.now(),originalMessageId:e});this.pendingTurnNotifiers.size>dp;){let o=this.pendingTurnNotifiers.keys().next().value;if(o===void 0)break;this.pendingTurnNotifiers.delete(o)}return{alreadyTerminal:!1}}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 be(new Error("client not attached"),E.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=Je(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let c=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}c.push(u)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:n,position:1}),this.amendInProgress={cancelledMessageId:n,newMessageId:o};let d=this.pendingTurnNotifiers.get(n);return d&&(this.pendingTurnNotifiers.delete(n),this.pendingTurnNotifiers.set(o,d)),this.cancelExtensionDispatch(n,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}async steer(e,t){let n=this.clients.get(e);if(!n)throw be(new Error("client not attached"),E.SessionNotFound);let r=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled;if(r&&this.agent.steeringSupported){this.pendingSteerDetach={messageId:this.currentEntry.messageId};let o;try{o=await this.forwardRequest("_session/steering",t)}catch(d){throw this.pendingSteerDetach=void 0,d}let i=o?.outcome,a=i==="injected"||i==="startedNewTurn"||i==="promptRequired"||i==="failed"?o:{outcome:"failed"};return a.outcome!=="startedNewTurn"&&(this.pendingSteerDetach=void 0),a.outcome==="injected"&&this.recordSteerAsUserMessageChunk(t.prompt,e),a.outcome==="startedNewTurn"?{...a,detached:!0}:a}return r?(this.amendOnHead(n,t.prompt,this.currentEntry.messageId,!1),{outcome:"startedNewTurn"}):t._meta?.steering?.idleBehavior==="promptRequired"?{outcome:"promptRequired",reason:"noRunningTurn"}:(this.prompt(e,{sessionId:t.sessionId,prompt:t.prompt},void 0,{steerOriginated:!0}).catch(o=>{this.logger?.warn(`steer-originated prompt failed to enqueue: ${o.message}`)}),{outcome:"startedNewTurn"})}recordSteerAsUserMessageChunk(e,t){let n=wt(e);n.length!==0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},_meta:{"hydra-acp":{steered:!0}}}},t)}enqueueAmendmentAsFollowUp(e,t){let n=Je(),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 be(new Error("client not attached"),E.SessionNotFound);this.logger?.info(`session ${this.sessionId} session/cancel from ${e} promptInFlight=${this.promptInFlight} agentTurnInFlight=${this.agentTurnInFlight} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length}`),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_${Wr()}`,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(m){this.logger?.warn(`transformer ${d.name} error on ${c}: ${m.message}`);continue}let p=l?.action??"continue";if(p==="stop")return o==="notification"?void 0:l?.payload??Vr(e);if(p==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),n.add(d.name);continue}if(p==="processing"){let m=a,h=i,f=new Set(n);return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:d.name}),this.forwardRequest(e,h,new Set([...f,d.name]),m+1,o).then(g).catch(()=>g(o==="notification"?void 0:Vr(e))))},es);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(u,{resolve:g,timer:w,transformerName:d.name,method:e,envelope:h,chainIdx:m,originatedBy:f,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 at({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??We,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_${Wr()}`,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(p){this.logger?.warn(`transformer ${d.name} error on ${i}: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:u?.payload??Lp(e)};if(l==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),n.add(d.name);continue}if(l==="processing"){let p=a,m=o,h=new Set(n),f=e;return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(f,m,new Set([...h,d.name]),p+1).then(g).catch(()=>g({shortCircuit:!1,envelope:m})))},es);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:y=>g({shortCircuit:!0,payload:y}),timer:w,transformerName:d.name,method:f,envelope:m,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):es,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:Vr(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=Je(),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},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(),this.cancelOrphanTimer();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._titleSeedPending=!1,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._titleSeedPending||rt((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let r=wt((e??{}).prompt),o=Kr(r,200);!o||o.startsWith("/")||(this._titleSeedPending=!1,this.setTitle(o))}maybeApplyAgentModel(e){let n=(e??{}).update??{};if(n.sessionUpdate!=="_hydra_current_model_update")return!1;let r=pn(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 i of r)this.applyOneConfigOptionEntry(i);let o=new Set(r.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i&&i!=="model"&&i!=="mode"&&i!=="agent"));return this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id)),this.fireConfigOptionsHandlers(),!0}applyAgentConfigOptionResponse(e,t){let n=e?.configOptions;if(!Array.isArray(n))return!1;let r=JSON.stringify(this.agentAdvertisedConfigOptions);for(let o of n){let i=o?.id;i==="model"||i==="mode"||i==="agent"||this.applyOneConfigOptionEntry(o)}if(gp(n,t)){let o=new Set(n.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i));this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id))}return JSON.stringify(this.agentAdvertisedConfigOptions)!==r}applyOneConfigOptionEntry(e){if(!e||typeof e!="object")return;let t=e;if(t.id==="model"){let f=pn(t.options);f.length>0&&this.setAgentAdvertisedModels(f);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(w)}`),this.applyModelChange(w))}return}if(t.id==="mode"){let f=ts(t.options);f.length>0&&this.setAgentAdvertisedModes(f);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(w)}`),this.applyModeChange(w))}return}if(typeof t.id!="string"||!t.id.trim())return;let n=t.id.trim(),r=Gr(t.options);if(r.length===0)return;let o=t.name,i=typeof o=="string"&&o.trim()?o.trim():n,a=t.category,d=typeof a=="string"&&a.trim()?a.trim():"other",c=t.description,u=typeof c=="string"&&c.trim()?c.trim():void 0,l=t.currentValue,p=typeof l=="string"&&l.trim()?l.trim():r[0].value,m={id:n,name:i,category:d,type:"select",currentValue:p,options:r,...u?{description:u}:{}},h=this.agentAdvertisedConfigOptions.findIndex(f=>f.id===n);h>=0?this.agentAdvertisedConfigOptions[h]=m:this.agentAdvertisedConfigOptions.push(m)}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,r){let o=this.retiringGenerationCost;this.retiringGenerationCost=void 0;let i=this.retiringGenerationUsed;this.retiringGenerationUsed=void 0;let a=this.rotationLifetimeCost;this.rotationLifetimeCost=void 0;for(let d of this.agentChangeHandlers)try{d({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...o!==void 0?{retiredCost:o}:{},...a!==void 0?{lifetimeCost:a}:{},...i!==void 0?{retiredUsed:i}:{},...r!==void 0?{startedUsed:r}:{},...t!==void 0?{reason:t}:{},...n!==void 0?{runId:n}:{}})}catch(c){this.logger?.warn(`${e}: agentChange handler failed: ${c.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=e);let t=this._currentUsage?.used;typeof t=="number"&&t>0&&(this.retiringGenerationUsed=t),this.rotationLifetimeCost=this.cumulativeCost;let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}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(xp(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Ep(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(",")}]`),Tp(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)}onConfigOptionsChange(e){this.configOptionsHandlers.push(e)}extraConfigOptionValues(){return Object.fromEntries(this.agentAdvertisedConfigOptions.map(e=>[e.id,e.currentValue]))}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:"_hydra_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}:{}}));this.currentModel&&!r.some(i=>i.value===this.currentModel)&&r.unshift({value:this.currentModel,name:this.currentModel});let o=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}:{}}));this.currentMode&&!r.some(i=>i.value===this.currentMode)&&r.unshift({value:this.currentMode,name:this.currentMode});let o=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()}}),this.fireConfigOptionsHandlers()}fireConfigOptionsHandlers(){for(let e of this.configOptionsHandlers)try{e(this.agentAdvertisedConfigOptions)}catch{}}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 jt){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 jt)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"||this._upstreamRespawned)return;let r=n.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0,this._titleSeedPending=!1;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(jt.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=E.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=jt.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:p}of this.extensionCommands.list())l.has(p)||(c.push(p),l.add(p))}let u=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw u.code=E.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(h=>h.verb===i)){let h=r.commands.map(f=>f.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 c=()=>{},u=new Promise(h=>{c=h});n!==void 0&&this.inFlightExtensionDispatches.set(n,{extensionName:e,connection:r.connection,cancel:h=>c({stopReason:"cancelled",reason:h})});let l,p=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",d),f=await Promise.race([h,u]);if(f&&typeof f=="object"&&f.stopReason==="cancelled"&&"reason"in f)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=f}catch(h){return this.emitExtensionReply(`${e} ${i}: ${h.message}`)}finally{n!==void 0&&!p&&this.inFlightExtensionDispatches.delete(n)}let m=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return m.length>0?this.emitExtensionReply(m):{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:`
50
50
  ${e}
51
51
  `},_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}):
52
52
  ${n.join(`
@@ -87,8 +87,8 @@ ${f}:
87
87
  `)}
88
88
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(n==="model"){if(c!==this.currentModel){let l=await this.forwardModelChange(c);this.applyAgentConfigOptionResponse(l,"model")}return this.applyModelChange(c),{stopReason:"end_turn"}}if(n==="mode")return c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"};if(n==="agent")return c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"};let u=await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:n,value:c});return this.applyAgentConfigOptionResponse(u,n)&&this.broadcastConfigOptions(),{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 be(new Error("/hydra agent requires an agent id"),E.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw be(new Error(`already on agent ${r}`),E.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 be(new Error("agent restart not configured for this session"),E.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=xa(n,t),o=Ea(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(`
89
89
  `)),{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(!Oa.includes(t))return this.emitExtensionReply(`Unknown workspace verb "${t}". Use one of: ${Oa.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=n.match(/^--verbatim(?:\s+([\s\S]*))?$/),o=r?"verbatim":void 0,i=(r?r[1]??"":n).trim();try{let a={};if(o&&(a.mode=o),i!==""&&(a.prompt=i),t&&this.historyStore){let u=await this.findMessageIdBefore(t).catch(()=>{});u&&(a.forkAt=u)}let c=(await this.forkHook(Object.keys(a).length>0?a:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(i!==""?`Forked to [\`${c}\`](hydra://sessions/${c}) and sent the prompt.`:`Forked to [\`${c}\`](hydra://sessions/${c}).`)}catch(a){this.emitExtensionReply(`Fork failed: ${a instanceof Error?a.message:String(a)}`)}return{stopReason:"end_turn"}}escalateUnresponsiveCancel(){this.cancelReopenStreak=0,this.logger?.warn(`session ${this.sessionId} agent ${this.agentId} reopened an unsolicited turn right after cancel ${s.UNSOLICITED_REOPEN_LIMIT} times in a row; forcing a restart`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,reason:"unresponsive",message:`${this.agentId} kept resuming after repeated cancels; restarting the agent`}),this.forceCancel().catch(e=>{this.logger?.warn(`session ${this.sessionId} forceCancel after unresponsive-cancel escalation failed: ${e instanceof Error?e.message:String(e)}`)})}async forceCancel(){if(this.closed||this.closing)throw be(new Error("session is closing"),E.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,{respawn:!0});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??[]),this.agentAdvertisedConfigOptions=r.initialConfigOptions??[],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 m=l.sessionUpdate;if(m==="prompt_received"){let h=wt(l.prompt);h&&n.push({speaker:"user",text:h})}else if(m==="agent_message_chunk"){let f=l.content?.text;f&&n.push({speaker:`agent: ${e}`,text:f})}else if(m==="tool_call"||m==="tool_call_update"){let h=l.status,f=l.title;(h==="completed"||h==="failed")&&n.push({speaker:"tool",text:`${f??"?"} ${h}`})}}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(`
90
- `)}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=Lr({synopsis:e,title:t,tail:n,tailK:ip,tailFloor:ap,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:"_hydra_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??Dt,Dt)),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=E.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.cancelOrphanTimer(),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.originatorNeedsTurnComplete(this.currentEntry)),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");let i=this.pendingTurnNotifiers.get(o.messageId);i&&(this.pendingTurnNotifiers.delete(o.messageId),_r(i,{sessionId:this.sessionId,messageId:i.originalMessageId,stopReason:"cancelled",deliveredAt:Date.now(),...o.messageId!==i.originalMessageId?{amendedTo:o.messageId}:{}}));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(()=>$a(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(()=>Wa.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()}scheduleOrphanCheck(){this.closed||this.orphanTimeoutMs<=0||this.clients.size>0||this._interactive===!0||this.armOrphanTimer(this.orphanTimeoutMs)}armOrphanTimer(e){this.orphanTimer&&clearTimeout(this.orphanTimer),this.orphanTimer=setTimeout(()=>{this.orphanTimer=void 0,this.checkOrphan()},e),typeof this.orphanTimer.unref=="function"&&this.orphanTimer.unref()}checkOrphan(){if(!this.closed&&!(this.clients.size>0||this._interactive===!0)){if(this.hasWorkInFlight){this.armOrphanTimer(this.orphanTimeoutMs);return}this.logger?.info(`session ${this.sessionId} orphan timeout fired after ${Math.round(this.orphanTimeoutMs/1e3)}s with no attached client and no prompt ever received \u2014 closing`),this.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}cancelOrphanTimer(){this.orphanTimer&&(clearTimeout(this.orphanTimer),this.orphanTimer=void 0)}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||this.armedBackgroundTasks.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)return;let o=typeof n.title=="string"&&n.title!==""?n.title:void 0;if(n.sessionUpdate==="tool_call"){this.turnRanTool=!0,n.status!=="completed"&&n.status!=="failed"&&this.openToolCalls.set(r,{startedAt:Date.now(),...o!==void 0?{title:o}:{}});return}if(n.sessionUpdate!=="tool_call_update")return;if(n.status==="completed"||n.status==="failed"){this.openToolCalls.delete(r),this.disarmOpenToolCall(r);return}let i=this.openToolCalls.get(r);i!==void 0&&o!==void 0&&(i.title=o)}armOpenToolCalls(){let e=!1;for(let[t,n]of this.openToolCalls){if(this.armedTasks.has(t))continue;let r=this.toolLabels.get(t),o=r?.fromDescription===!0?r.label:mp(n.title??r?.label??"").slice(0,qr);this.armedTasks.set(t,{label:o===""?"running tool":o,repeating:!1,armedAt:n.startedAt,openToolCall:!0}),e=!0}e&&this.onArmedTasksChanged()}disarmOpenToolCall(e){this.armedTasks.get(e)?.openToolCall===!0&&(this.armedTasks.delete(e),this.onArmedTasksChanged())}closeOpenToolCalls(e){if(this.openToolCalls.size===0||this.closed)return;let t=[...this.openToolCalls.keys()];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:{[ae]:{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===pa&&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 p=u.line,m={path:l,toolCallId:o};typeof p=="number"&&(m.line=p),this.notifyChain("file.edited",m),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=!zr(e,r),i=o?$p(e,r):r,a=Date.now(),d=o?this.lastSeq=Math.max(this.lastSeq+1,a):void 0,c=o?Ue(Le(i,a),d):i;if(o){this.noteRecordedToolCall(e,i);let u={method:e,params:i,recordedAt:a,seq:d};if(this.lastRecordedAt=u.recordedAt,this.appendCount+=1,this.historyStore){let l=this.historyStore;l.append(this.sessionId,u).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,l.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let l of this.broadcastHandlers)try{l(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,c).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw be(new Error("no clients attached to handle permission request"),E.PermissionDenied);let n=this.rewriteForClient(e),r=Da(n),o=ze(),{toolCall:i,options:a}=n??{};return new Promise((d,c)=>{let u=!1,l=[],p=0,m,h=this.sessionId,f=y=>{u||(u=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},g=y=>y?.code===E.MethodNotFound;function w(y){if(u)return;let k=y.connection.request("session/request_permission",n);l.push({client:y}),p++,k.then(b=>{p--,f(()=>{let I=Np({toolCallId:r,result:b,resolver:y});for(let v of l)v.client.clientId!==y.clientId&&v.client.connection.notify("session/update",{sessionId:h,update:I}).catch(()=>{});d(b)})}).catch(b=>{if(p--,g(b)||(m=b),p===0&&!u){let I=m??be(new Error("no client handled permission request"),E.PermissionDenied);f(()=>c(I))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,w);for(let y of t)w(y)})}async enqueuePrompt(e,t){return new Promise((n,r)=>{let o={kind:"internal",messageId:ze(),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,o){let i=(t??{}).prompt??[],a={clientId:e.clientId};e.clientInfo?.name&&(a.name=e.clientInfo.name),e.clientInfo?.version&&(a.version=e.clientInfo.version),r?.fromSession&&(a.fromSession=r.fromSession),r?.fromSessionTitle&&(a.fromSessionTitle=r.fromSessionTitle),r?.fromLabel&&(a.fromLabel=r.fromLabel),r?.depth!==void 0&&(a.depth=r.depth);let d=this.parseQueuePosition(t);return new Promise((c,u)=>{let l={kind:"user",messageId:n,originator:a,clientId:e.clientId,prompt:i,enqueuedAt:Date.now(),cancelled:!1,resolve:c,reject:u};o?.steerOriginated===!0&&(l.wasSteer=!0);let p=this.insertEntryAt(l,d);this.persistRewrite(),this.broadcastQueueAdded(l,{position:p}),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[ae];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(()=>fn(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=wt(e.prompt).replace(/\s+$/,""),n=!t.includes(`
91
- `)&&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,this.originatorNeedsTurnComplete(e)),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=Jr(e.prompt,Hp));let a;this.agentTurnInFlight=!0;try{i=this.applyWorkspacePromptRewrite(i),a=await this.dispatchPrompt(e,i)}catch(d){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),d}finally{this.agentTurnInFlight=!1}return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),a}async dispatchPrompt(e,t){let n=()=>this.awaitPromptResponse(this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:t},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0));try{return await n()}catch(r){if(this.loadExistingAgentSession&&vp(r))return this.logger?.warn(`agent ${this.agentId} no longer knows upstream session ${this.upstreamSessionId} for ${this.sessionId}; reloading it onto a fresh process and retrying the prompt once`),await this.reloadUpstreamAfterAgentLoss(),await n();if(!Sp(r)||this.turnRanTool||(this.logger?.warn(`agent ${this.agentId} hit a transient auth failure for ${this.sessionId}; retrying the prompt once in ${Na}ms`),await new Promise(o=>setTimeout(o,Na)),e.cancelled))throw r;return await n()}}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}},kp=["session not found","the claude agent session has ended"];function qa(s){let e=s;if(e?.code!==E.InternalError)return;let t=e.data?.details;return`${typeof e.message=="string"?e.message:""} ${typeof t=="string"?t:""}`.toLowerCase()}function vp(s){let e=qa(s);return e!==void 0&&kp.some(t=>e.includes(t))}var bp=["failed to refresh oauth token"],Na=6e4;function Sp(s){let e=qa(s);return e!==void 0&&bp.some(t=>e.includes(t))}function be(s,e){return s.code=e,s}var Ip=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction"]);function Ap(s,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||s==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function Cp(s){return typeof s!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(s)?.[1]}function Rp(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 zr(s,e){if(s!=="session/update")return!1;let n=(e??{}).update?.sessionUpdate;return typeof n=="string"&&Ip.has(n)}function xp(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 Ep(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 Tp(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 pn(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 ts(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 Gr(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=typeof n.name=="string"&&n.name.trim()?n.name.trim():r,i={value:r,name:o};typeof n.description=="string"&&n.description.length>0&&(i.description=n.description),e.push(i)}return e}function Pp(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="_hydra_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 Mp(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 _p(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 $p(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:ze()}}}function Op(s,e){if(s.length<=e)return s;let t=s.length-e;for(let n=t;n>=0;n--)if(s[n]?.params?.update?.sessionUpdate==="prompt_received")return s.slice(n);return s.slice(t)}function Fp(s,e){for(let t=s.length-1;t>=0;t--)if(s[t]?.seq===e)return t;return-1}function ns(s,e){for(let t=s.length-1;t>=0;t--){let n=s[t];if(!n||n.method!=="session/update")continue;if(n.params?.update?.messageId===e)return t}return-1}function Da(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 Np(s){let e=Dp(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=jp(s.resolver),t}function Dp(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 jp(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 wt(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}var Hp="\u200B";function ja(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 Jr(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 Vr(s){return s==="session/prompt"?{stopReason:"stopped"}:{}}function Lp(s){return s==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Ha(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}
90
+ `)}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=Lr({synopsis:e,title:t,tail:n,tailK:ip,tailFloor:ap,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:"_hydra_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??Dt,Dt)),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=E.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.cancelOrphanTimer(),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.originatorNeedsTurnComplete(this.currentEntry)),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");let i=this.pendingTurnNotifiers.get(o.messageId);i&&(this.pendingTurnNotifiers.delete(o.messageId),_r(i,{sessionId:this.sessionId,messageId:i.originalMessageId,stopReason:"cancelled",deliveredAt:Date.now(),...o.messageId!==i.originalMessageId?{amendedTo:o.messageId}:{}}));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(()=>$a(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(()=>Wa.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()}scheduleOrphanCheck(){this.closed||this.orphanTimeoutMs<=0||this.clients.size>0||this._interactive===!0||this.armOrphanTimer(this.orphanTimeoutMs)}armOrphanTimer(e){this.orphanTimer&&clearTimeout(this.orphanTimer),this.orphanTimer=setTimeout(()=>{this.orphanTimer=void 0,this.checkOrphan()},e),typeof this.orphanTimer.unref=="function"&&this.orphanTimer.unref()}checkOrphan(){if(!this.closed&&!(this.clients.size>0||this._interactive===!0)){if(this.hasWorkInFlight){this.armOrphanTimer(this.orphanTimeoutMs);return}this.logger?.info(`session ${this.sessionId} orphan timeout fired after ${Math.round(this.orphanTimeoutMs/1e3)}s with no attached client and no prompt ever received \u2014 closing`),this.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}cancelOrphanTimer(){this.orphanTimer&&(clearTimeout(this.orphanTimer),this.orphanTimer=void 0)}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||this.armedBackgroundTasks.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)return;let o=typeof n.title=="string"&&n.title!==""?n.title:void 0;if(n.sessionUpdate==="tool_call"){this.turnRanTool=!0,n.status!=="completed"&&n.status!=="failed"&&this.openToolCalls.set(r,{startedAt:Date.now(),...o!==void 0?{title:o}:{}});return}if(n.sessionUpdate!=="tool_call_update")return;if(n.status==="completed"||n.status==="failed"){this.openToolCalls.delete(r),this.disarmOpenToolCall(r);return}let i=this.openToolCalls.get(r);i!==void 0&&o!==void 0&&(i.title=o)}armOpenToolCalls(){let e=!1;for(let[t,n]of this.openToolCalls){if(this.armedTasks.has(t))continue;let r=this.toolLabels.get(t),o=r?.fromDescription===!0?r.label:mp(n.title??r?.label??"").slice(0,qr);this.armedTasks.set(t,{label:o===""?"running tool":o,repeating:!1,armedAt:n.startedAt,openToolCall:!0}),e=!0}e&&this.onArmedTasksChanged()}disarmOpenToolCall(e){this.armedTasks.get(e)?.openToolCall===!0&&(this.armedTasks.delete(e),this.onArmedTasksChanged())}closeOpenToolCalls(e){if(this.openToolCalls.size===0||this.closed)return;let t=[...this.openToolCalls.keys()];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:{[ae]:{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===pa&&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 p=u.line,m={path:l,toolCallId:o};typeof p=="number"&&(m.line=p),this.notifyChain("file.edited",m),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=!zr(e,r),i=o?$p(e,r):r,a=Date.now(),d=o?this.lastSeq=Math.max(this.lastSeq+1,a):void 0,c=o?Ue(Le(i,a),d):i;if(o){this.noteRecordedToolCall(e,i);let u={method:e,params:i,recordedAt:a,seq:d};if(this.lastRecordedAt=u.recordedAt,this.appendCount+=1,this.historyStore){let l=this.historyStore;l.append(this.sessionId,u).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,l.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let l of this.broadcastHandlers)try{l(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,c).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw be(new Error("no clients attached to handle permission request"),E.PermissionDenied);let n=this.rewriteForClient(e),r=Da(n),o=Je(),{toolCall:i,options:a}=n??{};return new Promise((d,c)=>{let u=!1,l=[],p=0,m,h=this.sessionId,f=y=>{u||(u=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},g=y=>y?.code===E.MethodNotFound;function w(y){if(u)return;let k=y.connection.request("session/request_permission",n);l.push({client:y}),p++,k.then(b=>{p--,f(()=>{let I=Np({toolCallId:r,result:b,resolver:y});for(let v of l)v.client.clientId!==y.clientId&&v.client.connection.notify("session/update",{sessionId:h,update:I}).catch(()=>{});d(b)})}).catch(b=>{if(p--,g(b)||(m=b),p===0&&!u){let I=m??be(new Error("no client handled permission request"),E.PermissionDenied);f(()=>c(I))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,w);for(let y of t)w(y)})}async enqueuePrompt(e,t){return new Promise((n,r)=>{let o={kind:"internal",messageId:Je(),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,o){let i=(t??{}).prompt??[],a={clientId:e.clientId};e.clientInfo?.name&&(a.name=e.clientInfo.name),e.clientInfo?.version&&(a.version=e.clientInfo.version),r?.fromSession&&(a.fromSession=r.fromSession),r?.fromSessionTitle&&(a.fromSessionTitle=r.fromSessionTitle),r?.fromLabel&&(a.fromLabel=r.fromLabel),r?.depth!==void 0&&(a.depth=r.depth);let d=this.parseQueuePosition(t);return new Promise((c,u)=>{let l={kind:"user",messageId:n,originator:a,clientId:e.clientId,prompt:i,enqueuedAt:Date.now(),cancelled:!1,resolve:c,reject:u};o?.steerOriginated===!0&&(l.wasSteer=!0);let p=this.insertEntryAt(l,d);this.persistRewrite(),this.broadcastQueueAdded(l,{position:p}),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[ae];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(()=>fn(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=wt(e.prompt).replace(/\s+$/,""),n=!t.includes(`
91
+ `)&&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,this.originatorNeedsTurnComplete(e)),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=Jr(e.prompt,Hp));let a;this.agentTurnInFlight=!0;try{i=this.applyWorkspacePromptRewrite(i),a=await this.dispatchPrompt(e,i)}catch(d){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),d}finally{this.agentTurnInFlight=!1}return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),a}async dispatchPrompt(e,t){let n=()=>this.awaitPromptResponse(this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:t},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0));try{return await n()}catch(r){if(this.loadExistingAgentSession&&vp(r))return this.logger?.warn(`agent ${this.agentId} no longer knows upstream session ${this.upstreamSessionId} for ${this.sessionId}; reloading it onto a fresh process and retrying the prompt once`),await this.reloadUpstreamAfterAgentLoss(),await n();if(!Sp(r)||this.turnRanTool||(this.logger?.warn(`agent ${this.agentId} hit a transient auth failure for ${this.sessionId}; retrying the prompt once in ${Na}ms`),await new Promise(o=>setTimeout(o,Na)),e.cancelled))throw r;return await n()}}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}},kp=["session not found","the claude agent session has ended"];function qa(s){let e=s;if(e?.code!==E.InternalError)return;let t=e.data?.details;return`${typeof e.message=="string"?e.message:""} ${typeof t=="string"?t:""}`.toLowerCase()}function vp(s){let e=qa(s);return e!==void 0&&kp.some(t=>e.includes(t))}var bp=["failed to refresh oauth token"],Na=6e4;function Sp(s){let e=qa(s);return e!==void 0&&bp.some(t=>e.includes(t))}function be(s,e){return s.code=e,s}var Ip=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction"]);function Ap(s,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||s==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function Cp(s){return typeof s!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(s)?.[1]}function Rp(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 zr(s,e){if(s!=="session/update")return!1;let n=(e??{}).update?.sessionUpdate;return typeof n=="string"&&Ip.has(n)}function xp(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 Ep(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 Tp(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 pn(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 ts(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 Gr(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=typeof n.name=="string"&&n.name.trim()?n.name.trim():r,i={value:r,name:o};typeof n.description=="string"&&n.description.length>0&&(i.description=n.description),e.push(i)}return e}function Pp(s){let t=(s??{}).update??{};if(t.sessionUpdate!=="_hydra_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 Mp(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 _p(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 $p(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:Je()}}}function Op(s,e){if(s.length<=e)return s;let t=s.length-e;for(let n=t;n>=0;n--)if(s[n]?.params?.update?.sessionUpdate==="prompt_received")return s.slice(n);return s.slice(t)}function Fp(s,e){for(let t=s.length-1;t>=0;t--)if(s[t]?.seq===e)return t;return-1}function ns(s,e){for(let t=s.length-1;t>=0;t--){let n=s[t];if(!n||n.method!=="session/update")continue;if(n.params?.update?.messageId===e)return t}return-1}function Da(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 Np(s){let e=Dp(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=jp(s.resolver),t}function Dp(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 jp(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 wt(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}var Hp="\u200B";function ja(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 Jr(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 Vr(s){return s==="session/prompt"?{stopReason:"stopped"}:{}}function Lp(s){return s==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Ha(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}
92
92
  ${n.join(`
93
93
  `)}`}function Kr(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}}G();Ne();import*as Pe from"fs/promises";import*as Ov from"path";import{customAlphabet as Wp}from"nanoid";import{z as P}from"zod";import{z as Wt}from"zod";var Up=Wt.object({source:Wt.string(),reason:Wt.string(),raisedAt:Wt.number(),payload:Wt.unknown()}),za=Wt.array(Up);import{z as Q}from"zod";var Ja=Q.object({status:Q.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Q.number(),runId:Q.string().optional(),iter:Q.number().int().nonnegative().optional(),attempts:Q.number().int().nonnegative().optional(),lastError:Q.string().optional(),worker:Q.object({upstreamSessionId:Q.string(),pid:Q.number().int().nonnegative()}).optional()}),gn=Q.object({goal:Q.string().optional(),outcome:Q.string().optional(),files_touched:Q.array(Q.string()).optional(),tools_used:Q.array(Q.string()).optional(),rejected_approaches:Q.array(Q.string()).optional(),open_threads:Q.array(Q.string()).optional(),decisions:Q.array(Q.string()).optional(),file_edit_intentions:Q.array(Q.string()).optional(),unresolved_errors:Q.array(Q.string()).optional(),tool_state:Q.array(Q.string()).optional()}),Va=200,Qr=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
94
94
  {
@@ -118,8 +118,8 @@ Use empty arrays/strings where a field doesn't apply.`;function Ka(s){let e=s.tr
118
118
  `).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 nd(n))return{ok:!1,reason:`source repository ${n} no longer exists`};let r=await j(["rev-parse","--verify","--quiet",`refs/heads/${t}`],n,z);if(!r.ok||r.stdout.trim().length===0)return{ok:!1,reason:`branch ${t} no longer exists in ${n}`};await j(["worktree","unlock",e.path],n,z),await j(["worktree","prune"],n,z);let o=await j(["worktree","add",e.path,t],n,ue);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=Y.resolve(e.sourceCwd),n=await j(["rev-parse","--show-toplevel"],t,z);if(!n.ok)return{ok:!1,reason:`${t} is not a git repository (or git is unavailable)`};let r=wn(n.stdout.trim());if(r.length===0)return{ok:!1,reason:`could not resolve the repository root for ${t}`};let o=await j(["rev-parse","HEAD"],r,z);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=is(e.label),d=zt(t);try{await $e.mkdir(d,{recursive:!0})}catch(m){return{ok:!1,reason:`could not create workspace root: ${String(m)}`}}let c=await os(a,async m=>await $e.access(Y.join(d,m)).then(()=>!0).catch(()=>!1)?!1:!(await j(["rev-parse","--verify","--quiet",`refs/heads/${io}/${m}`],r,z)).ok);if(c===void 0)return{ok:!1,reason:`no free name available for "${a}"`};let u=Y.join(d,c),l=`${io}/${c}`,p=await j(["worktree","add","--no-track","-b",l,u,i],r,ue);return p.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: ${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 j(["worktree","remove","--force",e.path],n,ue);t.discardLine===!0&&e.vcs?.branch!==void 0&&await j(["branch","-D",e.vcs.branch],n,z),r.ok||(await $e.rm(e.path,{recursive:!0,force:!0}),await j(["worktree","prune"],n,z))}async listWorkspaces(e){let t=Y.resolve(e),n=await j(["rev-parse","--show-toplevel"],t,z);if(!n.ok)return[];let r=wn(n.stdout.trim()),o=await j(["worktree","list","--porcelain"],r,z);if(!o.ok)return[];let i=zt(t),a=await ig(i),d=[];for(let c of Za(o.stdout)){let u=wn(c.path),l=Y.dirname(u);if(l!==i&&l!==a)continue;let p=Y.join(i,Y.basename(u)),m={kind:"git",repoRoot:r},h=ed(c.branch);h!==void 0&&(m.branch=h),c.head!==void 0&&(m.head=c.head),c.lockedReason!==void 0&&(m.locked=c.lockedReason);let f=c.lockedReason?.startsWith(td)===!0;d.push({path:p,sourceCwd:t,label:Y.basename(p),...f?{heldByUs:!0}:{},provider:this.kind,...h!==void 0?{line:h}:{},vcs:m})}return d}async status(e){let t=await j(["status","--porcelain","--untracked-files=all"],e.path,z);if(!t.ok)return{clean:!1,changedPaths:[],hasRecordedWork:!1};let n=co(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 j(["rev-list","--count",`${e.snapshot}..HEAD`],e.path,z);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 j(["worktree","lock","--reason",`${td}${t}`,e.path],n,z)}async unlock(e){let t=this.refRoot(e);await j(["worktree","unlock",e.path],t,z)}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 $e.access(Y.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 j(["status","--porcelain","--untracked-files=all"],e.path,z);if(n.ok){let r=co(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(...kt(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([j(["rev-parse","HEAD"],e.sourceCwd,z),j(["rev-parse","HEAD"],e.path,z)]),r=t.stdout.trim(),o=n.stdout.trim();if(!t.ok||!n.ok||r.length===0||o.length===0)return[];let i=O(e.sourceCwd);if(r===o)return[`in sync with ${i}`];let a=await j(["rev-list","--left-right","--count",`${r}...${o}`],e.path,z),d=a.stdout.trim().split(/\s+/).map(p=>Number.parseInt(p,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=Y.join(rd.tmpdir(),`hydra-index-${process.pid}-${og(6).toString("hex")}`),r={GIT_INDEX_FILE:n};try{let o=await j(["rev-parse","--verify","HEAD"],e,z),i=o.ok&&o.stdout.trim().length>0;if(i){let l=await j(["read-tree","HEAD"],e,ue,r);if(!l.ok)throw new Error(`could not seed the snapshot index: ${l.stderr.trim()}`)}let a=await j(["add","-A"],e,ue,r);if(!a.ok)throw new Error(`could not stage working state: ${a.stderr.trim()}`);let d=await j(["write-tree"],e,ue,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 j(c,e,ue,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 $e.rm(n,{force:!0}).catch(()=>{})}}async retainSnapshot(e,t,n){let r=this.refRoot(e);await j(["update-ref","--create-reflog",t,n],r,z)}async dropSnapshotRef(e,t){let n=this.refRoot(e);await j(["update-ref","-d",t],n,z)}async currentState(e){let t=await j(["rev-parse","HEAD"],e,z),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async contentId(e,t){let n=await j(["rev-parse",`${t}^{tree}`],e,z),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async currentLineName(e){let t=await j(["rev-parse","--abbrev-ref","HEAD"],e,z),n=t.stdout.trim();return t.ok&&n.length>0?n:void 0}async resolveRoot(e){let t=await j(["rev-parse","--show-toplevel"],e,z),n=wn(t.stdout.trim());return t.ok&&n.length>0?n:void 0}async resolveRetained(e,t){let n=await j(["rev-parse","--verify","--quiet",`${t}^{commit}`],this.refRoot(e),z),r=n.stdout.trim();return n.ok&&r.length>0?r:void 0}async contains(e,t){return(await j(["merge-base","--is-ancestor",t.state,t.within],e,z)).ok}async divergence(e,t,n){let r=await j(["rev-list","--left-right","--count",`${t}...${n}`],e,z);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 j(["diff","--name-only",t,n],e,z);return r.ok?r.stdout.split(`
119
119
  `).map(o=>o.replace(/\r$/,"").trim()).filter(o=>o.length>0):[]}async captureDelta(e,t,n){let r=await j(["diff","--binary","--ignore-submodules=all",t,n],e,ue);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 ao(["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 ao(["apply","--reverse","--check"],e,t)).ok)return{ok:!0,alreadyPresent:!0};let a=await ao(["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 j(["reset","--hard",t],e,ue);if(!r.ok)return{ok:!1,reason:r.stderr.trim()||"could not return to that state"};let o=await j(["clean",n?.purgeIgnored===!0?"-ffdx":"-fd"],e,ue);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 j(["rev-parse","-q","--verify","MERGE_HEAD"],e,z)).ok}async abortIntegration(e){await j(["merge","--abort"],e,ue)}async conflictedPaths(e){let t=await j(["diff","--name-only","--diff-filter=U"],e,z);return t.ok?t.stdout.split(`
120
120
  `).map(n=>n.replace(/\r$/,"").trim()).filter(n=>n.length>0):[]}async record(e,t){let n=await j(["add","-A"],e.path,ue);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 j(["commit","-m",t],e.path,ue);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 j(["rev-parse","--path-format=absolute","--git-common-dir"],e,z),n=wn(t.stdout.trim());if(!t.ok||n.length===0)return;let r=Y.dirname(n),o=await this.currentLineName(e);return{path:e,sourceCwd:r,label:Y.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 j(["branch","-D",t],n,z);return i.ok?{ok:!0,dropped:o}:{ok:!1,dropped:o,reason:i.stderr.trim()||"could not discard the line"}}async pruneStale(e){await j(["worktree","prune"],this.refRoot(e),z)}async changedPaths(){throw new _e(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 j(o,t,ue);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 j(["submodule","status","--recursive"],e,ue);if(!t.ok)return[];let n=[];for(let r of t.stdout.split(`
121
- `)){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||!ag(e,c))continue;let u=Y.join(e,c),[l,p,m]=await Promise.all([this.currentState(u),j(["rev-parse",`HEAD:${c}`],e,z),j(["status","--porcelain","--untracked-files=all"],u,z)]);if(l===void 0)continue;let h=p.ok?p.stdout.trim():"";n.push({relPath:c,actual:l,...h.length>0?{recorded:h}:{},changedPaths:m.ok?co(m.stdout).map(f=>f.path):[]})}return n}async captureNested(e,t){let n=[];for(let r of t){if(!so(r))continue;if(r.changedPaths.length===0){n.push(r);continue}let o=Y.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=Y.join(e,i.relPath),d=Y.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(g=>g.relPath===c),l=i.get(c);if(u===void 0){o.push({path:c,reason:"not populated in the receiving tree"});continue}let p=u.recorded!==void 0&&u.recorded!==u.actual,m=l?.delta!==void 0;if(!p&&!m)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 h=Y.join(e,c),f=Y.join(t,c);if(p&&u.recorded!==void 0){let g=await this.alignNested(h,f,u.recorded);if(g!==void 0){o.push({path:c,reason:g});continue}}if(l?.delta!==void 0){let g=await this.applyDelta(h,l.delta);if(!g.ok){o.push({path:c,reason:g.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 j(["cat-file","-e",`${n}^{commit}`],e,z)).ok&&!(await j(["fetch","--no-tags",t,n],e,ds)).ok)return`could not transfer ${n.slice(0,8)} from the other copy`;if(!(await j(["checkout","--detach",n],e,ue)).ok)return`could not move to ${n.slice(0,8)}`}};function ag(s,e){if(Y.isAbsolute(e))return!1;let t=Y.resolve(s),n=Y.resolve(t,e);return n!==t&&n.startsWith(t+Y.sep)}var dg=us,cg=new Map([[us,new cs],[oo,new as]]);function ne(s){return cg.get(s??dg)}var ls="refs/hydra";function Jt(s){let e=`${ls}/workspaces/${s}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function uo(s){return`${ls}/landing/${s}`}function od(s){return`${ls}/sync/${s}`}function id(s,e){return`${ls}/retired/${s}-${e.slice(0,12)}`}function ad(s){let e=Jt(s);return[e.autosave,e.start,e.baseline]}async function lo(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 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 vt(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 kn(s){s.capture.retainedRef===void 0||s.provider===void 0||await s.provider.dropSnapshotRef({...s.ws,path:s.source},s.capture.retainedRef).catch(()=>{})}Ne();import{exec as ug}from"child_process";import*as Je from"fs/promises";import*as Ce from"path";var lg=".hydra/worktree.json",fg=".worktreeinclude",pg=120;async function fs(s){let e=await ie(Ce.join(s,lg))??{},t=new Set(Array.isArray(e.carry)?e.carry:[]),n=await Je.readFile(Ce.join(s,fg),"utf8").catch(()=>{});if(n!==void 0)for(let o of n.split(`
122
- `)){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 fo(s,e,t){let n=[],r=[],o=Ce.resolve(s),i=Ce.resolve(e);for(let a of t){let d=Ce.resolve(o,a),c=Ce.resolve(i,a);if(!d.startsWith(o+Ce.sep)||!c.startsWith(i+Ce.sep)){r.push(a);continue}if(await Je.access(c).then(()=>!0).catch(()=>!1)){r.push(a);continue}let l=await Je.stat(d).catch(()=>{});if(l===void 0){r.push(a);continue}try{await Je.mkdir(Ce.dirname(c),{recursive:!0}),await Je.cp(d,c,{recursive:l.isDirectory(),dereference:!0}),n.push(a)}catch{r.push(a)}}return{copied:n,skipped:r}}async function ps(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??pg)*1e3;return new Promise(r=>{let o=ug(s,{cwd:e.workspacePath,timeout:n,maxBuffer:8388608,windowsHide:!0,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)})}G();Ne();import*as Ze from"fs/promises";import{z as Oe}from"zod";var gg=Oe.object({version:Oe.literal(1),agentId:Oe.string(),upstreamSessionId:Oe.string(),sessionId:Oe.string().optional(),deletedAt:Oe.string(),upstreamUpdatedAt:Oe.string().optional(),cwd:Oe.string().optional(),title:Oe.string().optional(),reason:Oe.enum(["user","expired"]).optional(),interactive:Oe.boolean().optional()}),gs=class{async add(e){let t={version:1,...e};await pe(x.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await Ze.access(x.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let n=x.tombstoneFile(e,t),r=await ie(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 gg.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await Ze.unlink(x.tombstoneFile(e,t))}catch(n){if(n.code!=="ENOENT")throw n}try{await Ze.rmdir(x.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 Ze.readdir(x.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 Ze.readdir(x.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 dd(s,e){return s.reason==="user"||e===void 0?!1:s.upstreamUpdatedAt===void 0?!0:e>s.upstreamUpdatedAt}import*as Sd from"fs/promises";import{customAlphabet as Ag}from"nanoid";import{fileURLToPath as mg}from"url";import*as vn from"path";import*as ms from"fs";function hg(){try{let s=vn.dirname(mg(import.meta.url));for(let e=0;e<8;e+=1){let t=vn.join(s,"package.json");if(ms.existsSync(t)){let r=JSON.parse(ms.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=vn.dirname(s);if(n===s)break;s=n}}catch{}return"0.0.0"}var le=hg(),hs="hydra-acp-cat";var yg=12e4;async function ud(s,e,t){let n=s.timeoutMs??yg,r,o,i=!1;try{let a=(async()=>{r=it.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:le}}),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 h=kg(c);if(h.size===0||h.has(s.modelId)){let f=r.connection;try{await at({request:(g,w)=>f.request(g,w),sessionId:u,modelId:s.modelId,verb:Nt(c),logger:s.logger})}catch(g){s.logger?.warn(`synopsis: agent ${s.agentId} rejected model change to ${JSON.stringify(s.modelId)}: ${g.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 f=wg(h);f.length>0&&l.push(f)}),await r.connection.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:e}]});let p=l.join(""),m=t(p);if(!m){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 f=p.slice(0,120).replace(/\s+/g," ").trim();s.onFailure?.(`agent ${s.agentId} returned unparseable JSON (${p.length} chars): ${f}${p.length>120?"\u2026":""}`)}return m})();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 ys(s){let e=Ut(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}
121
+ `)){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||!ag(e,c))continue;let u=Y.join(e,c),[l,p,m]=await Promise.all([this.currentState(u),j(["rev-parse",`HEAD:${c}`],e,z),j(["status","--porcelain","--untracked-files=all"],u,z)]);if(l===void 0)continue;let h=p.ok?p.stdout.trim():"";n.push({relPath:c,actual:l,...h.length>0?{recorded:h}:{},changedPaths:m.ok?co(m.stdout).map(f=>f.path):[]})}return n}async captureNested(e,t){let n=[];for(let r of t){if(!so(r))continue;if(r.changedPaths.length===0){n.push(r);continue}let o=Y.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=Y.join(e,i.relPath),d=Y.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(g=>g.relPath===c),l=i.get(c);if(u===void 0){o.push({path:c,reason:"not populated in the receiving tree"});continue}let p=u.recorded!==void 0&&u.recorded!==u.actual,m=l?.delta!==void 0;if(!p&&!m)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 h=Y.join(e,c),f=Y.join(t,c);if(p&&u.recorded!==void 0){let g=await this.alignNested(h,f,u.recorded);if(g!==void 0){o.push({path:c,reason:g});continue}}if(l?.delta!==void 0){let g=await this.applyDelta(h,l.delta);if(!g.ok){o.push({path:c,reason:g.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 j(["cat-file","-e",`${n}^{commit}`],e,z)).ok&&!(await j(["fetch","--no-tags",t,n],e,ds)).ok)return`could not transfer ${n.slice(0,8)} from the other copy`;if(!(await j(["checkout","--detach",n],e,ue)).ok)return`could not move to ${n.slice(0,8)}`}};function ag(s,e){if(Y.isAbsolute(e))return!1;let t=Y.resolve(s),n=Y.resolve(t,e);return n!==t&&n.startsWith(t+Y.sep)}var dg=us,cg=new Map([[us,new cs],[oo,new as]]);function ne(s){return cg.get(s??dg)}var ls="refs/hydra";function Jt(s){let e=`${ls}/workspaces/${s}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function uo(s){return`${ls}/landing/${s}`}function od(s){return`${ls}/sync/${s}`}function id(s,e){return`${ls}/retired/${s}-${e.slice(0,12)}`}function ad(s){let e=Jt(s);return[e.autosave,e.start,e.baseline]}async function lo(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 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 vt(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 kn(s){s.capture.retainedRef===void 0||s.provider===void 0||await s.provider.dropSnapshotRef({...s.ws,path:s.source},s.capture.retainedRef).catch(()=>{})}Ne();import{exec as ug}from"child_process";import*as Ve from"fs/promises";import*as Ce from"path";var lg=".hydra/worktree.json",fg=".worktreeinclude",pg=120;async function fs(s){let e=await ie(Ce.join(s,lg))??{},t=new Set(Array.isArray(e.carry)?e.carry:[]),n=await Ve.readFile(Ce.join(s,fg),"utf8").catch(()=>{});if(n!==void 0)for(let o of n.split(`
122
+ `)){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 fo(s,e,t){let n=[],r=[],o=Ce.resolve(s),i=Ce.resolve(e);for(let a of t){let d=Ce.resolve(o,a),c=Ce.resolve(i,a);if(!d.startsWith(o+Ce.sep)||!c.startsWith(i+Ce.sep)){r.push(a);continue}if(await Ve.access(c).then(()=>!0).catch(()=>!1)){r.push(a);continue}let l=await Ve.stat(d).catch(()=>{});if(l===void 0){r.push(a);continue}try{await Ve.mkdir(Ce.dirname(c),{recursive:!0}),await Ve.cp(d,c,{recursive:l.isDirectory(),dereference:!0}),n.push(a)}catch{r.push(a)}}return{copied:n,skipped:r}}async function ps(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??pg)*1e3;return new Promise(r=>{let o=ug(s,{cwd:e.workspacePath,timeout:n,maxBuffer:8388608,windowsHide:!0,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)})}G();Ne();import*as Ze from"fs/promises";import{z as Oe}from"zod";var gg=Oe.object({version:Oe.literal(1),agentId:Oe.string(),upstreamSessionId:Oe.string(),sessionId:Oe.string().optional(),deletedAt:Oe.string(),upstreamUpdatedAt:Oe.string().optional(),cwd:Oe.string().optional(),title:Oe.string().optional(),reason:Oe.enum(["user","expired"]).optional(),interactive:Oe.boolean().optional()}),gs=class{async add(e){let t={version:1,...e};await pe(x.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await Ze.access(x.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let n=x.tombstoneFile(e,t),r=await ie(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 gg.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await Ze.unlink(x.tombstoneFile(e,t))}catch(n){if(n.code!=="ENOENT")throw n}try{await Ze.rmdir(x.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 Ze.readdir(x.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 Ze.readdir(x.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 dd(s,e){return s.reason==="user"||e===void 0?!1:s.upstreamUpdatedAt===void 0?!0:e>s.upstreamUpdatedAt}import*as Sd from"fs/promises";import{customAlphabet as Ag}from"nanoid";import{fileURLToPath as mg}from"url";import*as vn from"path";import*as ms from"fs";function hg(){try{let s=vn.dirname(mg(import.meta.url));for(let e=0;e<8;e+=1){let t=vn.join(s,"package.json");if(ms.existsSync(t)){let r=JSON.parse(ms.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=vn.dirname(s);if(n===s)break;s=n}}catch{}return"0.0.0"}var le=hg(),hs="hydra-acp-cat";var yg=12e4;async function ud(s,e,t){let n=s.timeoutMs??yg,r,o,i=!1;try{let a=(async()=>{r=it.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:le}}),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 h=kg(c);if(h.size===0||h.has(s.modelId)){let f=r.connection;try{await at({request:(g,w)=>f.request(g,w),sessionId:u,modelId:s.modelId,verb:Nt(c),logger:s.logger})}catch(g){s.logger?.warn(`synopsis: agent ${s.agentId} rejected model change to ${JSON.stringify(s.modelId)}: ${g.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 f=wg(h);f.length>0&&l.push(f)}),await r.connection.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:e}]});let p=l.join(""),m=t(p);if(!m){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 f=p.slice(0,120).replace(/\s+/g," ").trim();s.onFailure?.(`agent ${s.agentId} returned unparseable JSON (${p.length} chars): ${f}${p.length>120?"\u2026":""}`)}return m})();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 ys(s){let e=Ut(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}
123
123
 
124
124
  ${e}
125
125
 
@@ -190,13 +190,13 @@ ${A}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),th
190
190
  `),a}function Oo(s,e){let t=s<0?e+s+1:s;return t<1?1:t>e?e:t}function th(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:m}of s)m.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=Oo(o-e.last+1,o):(e.from!==void 0&&(i=Oo(e.from,o)),e.to!==void 0&&(a=Oo(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((m,h)=>{m.recordedAt>=d&&c.add(n[h])});let u=[],l,p;return s.forEach((m,h)=>{let f=n[h];f<i||f>a||d!==void 0&&!c.has(f)||(u.push(m),l??=f,p=f)}),{events:u,window:{from:l??i,to:p??a,total:o}}}function nh(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=lc(n.update,{cwd:s.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function sh(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 rh(s,e){let t=e.session,n=Xe(t.sessionId),r=t.title?.trim()||`Hydra session ${n}`;s.push(`# ${$n(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?`${Fo(a.size)}`:void 0;d.push(u?`${Fo(a.used)} / ${u} tokens`:`${Fo(a.used)} tokens`)}let c=wo(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(`
191
191
  `)),s.push("")}function oh(s,e,t,n){let{includeTools:r,includeThoughts:o}=n;if(!e.some(f=>ih(f.event,o))){s.push("_No conversation history recorded._"),s.push("");return}let i=0,a="",d="",c=[],u=new Set,l=!1,p=()=>{if(c.length!==0){for(let f of c)s.push(f);s.push(""),c=[]}},m=()=>{p(),d.length>0&&(kc(s,d.trimEnd(),"*"),s.push(""),d=""),a.length!==0&&(s.push(a.trimEnd()),s.push(""),a="")},h=()=>{l||(l=!0)};for(let{event:f}of e)switch(f.kind){case"user-text":{m(),s.push("---"),s.push(""),i+=1,kc(s,f.text,"**"),s.push(""),l=!0;break}case"agent-text":h(),a+=f.text;break;case"agent-thought":{if(!o)break;h(),a.length>0&&(s.push(a.trimEnd()),s.push(""),a=""),d+=f.text;break}case"tool-call":{if(!r||(h(),(a.length>0||d.length>0)&&m(),u.has(f.toolCallId)))break;u.add(f.toolCallId);let g=t.get(f.toolCallId)??{title:f.title,status:f.status??"pending"};c.push(`- ${dh(g.status)} ${ah(g)}`);break}case"tool-call-update":break;case"plan":{h(),m(),s.push("**Plan:**"),s.push("");for(let g of f.entries){let w=g.status==="completed"?"[x]":"[ ]";s.push(`- ${w} ${$n(g.content)}`)}s.push("");break}case"mode-changed":h(),m(),s.push(`_mode: ${$n(f.mode)}_`),s.push("");break;case"model-changed":h(),m(),s.push(`_model: ${$n(f.model)}_`),s.push("");break;case"turn-complete":m();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}m()}function ih(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 ah(s){let e=s.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${$n(s.title)}${t}`}function dh(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 bc=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,ch=new RegExp(bc);function kc(s,e,t){if(ch.test(e)){uh(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(`
192
192
  `);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 uh(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(`
193
- `))s.push(o);s.push(r)}function $n(s){return s.replace(new RegExp(bc,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function Fo(s){return s.toLocaleString("en-US")}function Re(s){return s==="127.0.0.1"||s==="::1"||s==="localhost"||s==="[::1]"}function lh(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=>fh(u)).filter(u=>u.term.length>0);return{operator:o,terms:c}}function fh(s){let e=/^(\w+):"([^"]*)"$/.exec(s);if(e)return{scope:Sc(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:Sc(n[1]),term:n[2].trim()}:{scope:"all",term:s.trim()}}function Sc(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 ph(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 gh=5,mh=200,Ls=72,hh=24,yh=512;function xc(s){return Number.isFinite(s)?Math.max(hh,Math.min(yh,Math.floor(s))):Ls}async function Ec(s,e,t={}){let n=lh(e);if(n.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??gh,o=t.maxSessions??mh,i=xc(t.snippetWidth??Ls),a=t.sessionIds?new Set(t.sessionIds):null,d=await s.list(),c=a?d.filter(p=>a.has(p.sessionId)):d,u=[],l=!1;for(let p of c){if(u.length>=o){l=!0;break}let m=await s.loadHistory(p.sessionId,{tools:"references"}).catch(()=>[]),h=kh(m,n,r,i,wh(p));if(h.snippets.length===0)continue;let f={sessionId:p.sessionId,cwd:p.cwd,status:p.status,updatedAt:p.updatedAt,totalMatches:h.totalMatches,snippets:h.snippets};p.title!==void 0&&(f.title=p.title),u.push(f)}return{query:e,truncated:l,results:u}}function wh(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 kh(s,e,t,n=Ls,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=vh(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 vh(s,e,t,n,r,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let u of s){let l=bh(u).filter(p=>ph(t,p.kind));for(let p of l){let m=p.text.toLowerCase();if(p.kind==="edit"){let g=o?.(p.text);if(!(Ic(p.text,e)||(g!==void 0&&g!==p.text?Ic(g,e):!1))||c.has(p.text))continue;if(c.add(p.text),a+=1,d.length<n){let y={kind:"edit",text:p.text,recordedAt:u.recordedAt};p.toolName!==void 0&&(y.toolName=p.toolName),d.push(y)}continue}let h=m.indexOf(i);if(h===-1)continue;let f=0;for(;h!==-1;)f++,h=m.indexOf(i,h+i.length);if(a+=f,d.length<n){let g=m.indexOf(i),w={kind:p.kind,text:Eh(p.text,g,i.length,r),recordedAt:u.recordedAt};p.toolName!==void 0&&(w.toolName=p.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function bh(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=Hs(n.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof n.text=="string"?Me(n.text):Hs(n.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(Rh(n))return[];let o=Hs(n.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=xh(n.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return Sh(n);default:return[]}}function Sh(s){let e=Cc(s,"name"),t=Cc(s,"title"),n=[];if(t!==void 0){let a=re(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=re(e);a.length>0&&n.push({kind:"tool",toolName:e,text:a})}let r=s.rawInput;if(r&&typeof r=="object"){let a=Rc(r);if(a.length>0){let d={kind:"tool-input",text:re(a)};e!==void 0&&(d.toolName=e),n.push(d)}}for(let a of Ih(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=Rc(o);if(a.length>0){let d={kind:"tool-input",text:re(a)};e!==void 0&&(d.toolName=e),n.push(d)}}let i=Ah(s);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),n.push(a)}return n}function Ih(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 Ic(s,e){let t=Ac(s.toLowerCase()),n=Ac(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 Ac(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Ah(s){if(!Ch(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=re(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=re(n);if(r.length>0)return r}}return null}function Ch(s){return s==="failed"||s==="rejected"||s==="cancelled"}function Rh(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 Hs(s){if(typeof s=="string")return Me(s);if(!s||typeof s!="object"||Array.isArray(s))return"";let e=s;return typeof e.text=="string"?Me(e.text):""}function xh(s){if(!Array.isArray(s))return"";let e=[];for(let t of s){let n=Hs(t);n.length>0&&e.push(n)}return e.join("")}function Cc(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Rc(s){try{return JSON.stringify(s)}catch{return""}}function Eh(s,e,t,n=Ls){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=xc(n),c=Math.max(0,d-i.length),u=Math.floor(c/2),l=Math.min(u,a),p=Math.min(c-l,r.length-(a+i.length)),m=Math.max(0,a-(c-p)),h=Math.min(r.length,a+i.length+p),f=m>0?"\u2026":"",g=h<r.length?"\u2026":"";return`${f}${r.slice(m,h)}${g}`}import{randomBytes as Pc}from"crypto";function Tc(s){let e=Pc(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 No(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(Tc({name:"hydra-acp-stdin",session:n,tokenRegistry:e,getOrigin:t})),r.push(Tc({name:"hydra-acp-recall",session:n,tokenRegistry:e,getOrigin:t}));let o=Kt(s.deps);return o!==void 0&&(o.bindToSession(n),r=[...r,...o.descriptors]),r}}function Kt(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=Pc(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 Th=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function Mc(s,e){let t=e.fetchImpl??fetch;s.addHook("preHandler",async(n,r)=>{let o=n.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=n.params,a=i.id;if(typeof a!="string")return;let d=dt(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let w=e.localMiss.cache.findByLocalId(a);if(w.length===0)return;if(w.length>1){r.code(404).send({error:`Session "${a}" exists on more than one remote (${w.map(y=>y.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=w[0]}let c=e.store.get(d.name);if(!c){r.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let u=n.query;if(Th.has(o)&&Mh(u?.follow)){let w=c.port===Tt?"":`:${c.port}`;r.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${w}/${d.localId} instead.`});return}let l=_h(o,i,d.localId,n.url),m=`${Re(c.host)?"http":"https"}://${c.host}:${c.port}${l}`,h;try{h=await t(m,{method:n.method,headers:{Authorization:`Bearer ${c.token}`,...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0&&n.method!=="GET"?{body:JSON.stringify(n.body)}:{}})}catch(w){r.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${w.message}`});return}if(h.status===204){r.code(204).send();return}let f=await h.text(),g=h.headers.get("content-type");g&&r.header("content-type",g),r.code(h.status).send(f)})}var Ph=5e3,Us=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??Ph),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(n=>n.name));for(let n of[...this.perPeer.keys()])t.has(n)||this.perPeer.delete(n);await Promise.allSettled(this.store.list().map(async n=>{let r=this.store.get(n.name);if(!r)return;let o=this.perPeer.get(n.name),i=Re(r.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${r.host}:${r.port}/v1/sessions?${a.toString()}`,u;try{u=await e(c,{headers:{Authorization:`Bearer ${r.token}`}})}catch{return}if(!u.ok)return;let l=await u.json(),p=o?.sessions??new Map;if(d){for(let[m,h]of[...p])h.status!=="cold"&&p.delete(m);for(let m of l.removed??[])p.delete(Ye({name:n.name,localId:m}))}else p.clear();for(let m of l.sessions??[]){let h=Ye({name:n.name,localId:String(m.sessionId)});p.set(h,{...m,sessionId:h,remote:n.name})}this.perPeer.set(n.name,{cursor:l.cursor,sessions:p})}))}list(e){let t=[];for(let n of this.perPeer.values())t.push(...n.sessions.values());return t.filter(n=>!(e.status&&n.status!==e.status||!e.includeNonInteractive&&n.interactive!==!0))}findByLocalId(e){let t=e.startsWith(Ae)?[e]:[e,Ae+e],n=[];for(let[r,o]of this.perPeer)for(let i of t)if(o.sessions.has(Ye({name:r,localId:i}))){n.push({name:r,localId:i});break}return n}};async function _c(s,e,t,n=fetch){let r=s.get(e);if(!r)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Re(r.host)?"http":"https"}://${r.host}:${r.port}/v1/sessions`,a;try{a=await n(i,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(l){return{status:502,body:{error:`Could not reach remote "${e}" (${r.host}:${r.port}): ${l.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let u=c;return u&&typeof u.sessionId=="string"?{status:a.status,body:{...u,sessionId:Ye({name:e,localId:u.sessionId})}}:{status:a.status,body:c}}async function $c(s,e,t=fetch){let n;if(e.sessionIds===void 0)n=s.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=dt(d);if(!c)continue;let u=a.get(c.name)??[];u.push(c.localId),a.set(c.name,u)}n=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(n.length===0)return{query:e.q,truncated:!1,results:[]};let r=await Promise.all(n.map(async a=>{let d=s.get(a.name);if(!d)return null;let u=`${Re(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,l;try{l=await t(u,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!l.ok)return null;let p;try{p=await l.json()}catch{return null}let m=p;if(!m||!Array.isArray(m.results))return null;let h=m.results.map(f=>({...f,sessionId:Ye({name:a.name,localId:f.sessionId})}));return{query:e.q,truncated:m.truncated===!0,results:h}})),o=[],i=!1;for(let a of r)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function Mh(s){return s==="1"||s==="true"||s===!0}function _h(s,e,t,n){let r=s.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=n.indexOf("?");return o===-1?r:r+n.slice(o)}var Bs=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Oc(s){if(s.publicHost&&s.publicHost.length>0)return s.publicHost;if(s.host&&!Re(s.host))return s.port!==void 0?`${s.host}:${s.port}`:s.host}function Nc(s,e,t,n={},r,o){s.get("/v1/sessions",async(l,p)=>{let m=l.query,h=m?.includeNonInteractive==="1"||m?.includeNonInteractive==="true",f;if(m?.since!==void 0&&(f=Number(m.since),!Number.isFinite(f)||f<0))return p.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(m.since)}`});let g=m?.status==="warm"||m?.status==="cold"?m.status:void 0,w={cwd:m?.cwd,includeNonInteractive:h,...g?{status:g}:{}},y=o&&!w.cwd?o.list({includeNonInteractive:h,...g?{status:g}:{}}):[];if(f!==void 0){let b=await e.listSince(w,f);return{sessions:[...b.entries,...y],removed:b.removed,cursor:b.cursor}}let k=await e.listing(w);return{sessions:[...k.entries,...y],removed:[],cursor:k.cursor}}),s.get("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.getOne(h);return f||(p.code(404).send({error:"session not found"}),p)}),s.post("/v1/sessions/search",async(l,p)=>{let m=l.body??{},h=typeof m.q=="string"?m.q:"";if(h.trim().length===0)return p.code(400).send({error:"q is required"}),p;let f=Array.isArray(m.sessionIds)?m.sessionIds.filter(k=>typeof k=="string"&&k.length>0):void 0,g={sessionIds:f};typeof m.snippetWidth=="number"&&(g.snippetWidth=m.snippetWidth);let w=await Ec(e,h,g);if(!r)return w;let y=await $c(r,{q:h,...f?{sessionIds:f}:{},...g.snippetWidth!==void 0?{snippetWidth:g.snippetWidth}:{}});return{query:h,truncated:w.truncated||y.truncated,results:[...w.results,...y.results]}}),s.post("/v1/sessions",async(l,p)=>{let m=l.body??{};if(m.remote){if(!r)return p.code(404).send({error:`No remote named "${m.remote}". Run \`hydra remote add\` first.`});let k=await _c(r,m.remote,{cwd:m.cwd,agentId:m.agentId,mcpServers:m.mcpServers,workspace:m.workspace});return p.code(k.status).send(k.body)}let h=ce(m.cwd??t.cwd),f=await sn(h),g=m.agentId??f.agentId??t.agentId,w=Kt(n),y=w!==void 0?[...m.mcpServers??[],...w.descriptors]:m.mcpServers;try{let k=await e.create({cwd:h,agentId:g,mcpServers:y,...m.workspace!==void 0?{workspace:m.workspace}:{}});w!==void 0&&w.bindToSession(k),p.code(201).send({sessionId:k.sessionId,agentId:k.agentId,cwd:k.cwd,...k.workspace!==void 0?{workspace:k.workspace}:{},...k.workspaceError!==void 0?{workspaceError:k.workspaceError}:{}})}catch(k){w!==void 0&&w.abandon(k instanceof Error?k:void 0),p.code(500).send({error:k.message})}}),s.post("/v1/sessions/collect",async(l,p)=>{let m=l.body??{},h=typeof m.maxAgeDays=="number"&&m.maxAgeDays>0?m.maxAgeDays*24*60*60*1e3:0,f=typeof m.limit=="number"&&m.limit>0?m.limit:1e3,g=m.selection==="explicit"||m.selection==="unpromoted"?m.selection:"unpromoted";try{let w=await Po({manager:e,maxAgeMs:h,maxDeletions:f,selection:g,verbose:!1});p.code(200).send(w)}catch(w){p.code(500).send({error:w.message})}}),s.post("/v1/sessions/:id/kill",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(f){f.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),p.code(202).send();return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.post("/v1/sessions/:id/stdin/open",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(!f)return p.code(404).send({error:"session not found"}),p;let g=l.body??{},w={};(g.mode==="memory"||g.mode==="file")&&(w.mode=g.mode),typeof g.capacityBytes=="number"&&(w.capacityBytes=g.capacityBytes),typeof g.fileCapBytes=="number"&&(w.fileCapBytes=g.fileCapBytes),(w.mode??"memory")==="file"&&(w.filePathFor=y=>Ws.join(Fc.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return f.openStream(w)}catch(y){return p.code(409).send({error:y.message}),p}}),s.post("/v1/sessions/:id/stdin",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(!f)return p.code(404).send({error:"session not found"}),p;let g=l.body??{},w=typeof g.chunk=="string"?g.chunk:"",y=g.eof===!0;try{return f.streamWrite(w,y)}catch(k){return p.code(409).send({error:k.message}),p}}),s.patch("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{};if(f.cwd!==void 0){if(typeof f.cwd!="string"||!Ws.isAbsolute(f.cwd)){p.code(400).send({error:"cwd must be an absolute path"});return}let w=await e.setCwd(h,f.cwd);if(w==="missing"){p.code(404).send({error:"session not found"});return}if(w==="not-a-directory"){p.code(400).send({error:`${f.cwd} is not a directory`});return}if(w==="live"){p.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(w==="bound"){p.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}p.code(204).send();return}if("workspace"in f){if(f.workspace!==null){p.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let w=await e.clearWorkspaceBinding(h);if(w==="missing"){p.code(404).send({error:"session not found"});return}if(w==="live"){p.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}p.code(204).send();return}if(f.priority!==void 0){let w=f.priority,y;if(w===null||w===0)y=void 0;else if(typeof w=="number"&&Number.isInteger(w)&&w>0)y=w;else{p.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(h,y)){p.code(404).send({error:"session not found"});return}p.code(204).send();return}if(f.regen===!0){if(!(e.get(h)!==void 0||await e.hasRecord(h))){p.code(404).send({error:"session not found"});return}e.scheduleSynopsis(h),p.code(202).send();return}if(typeof f.title!="string"||f.title.trim().length===0){p.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(h,f.title)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.delete("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(f){await f.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(h),await e.hasRecord(h)&&await e.deleteRecord(h),p.code(204).send();return}if(!await e.deleteRecord(h)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.get("/v1/sessions/:id/export",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.query?.tools,g=f==="references"?"references":Id(f),w=await e.exportBundle(h,g==="references"?{tools:"references"}:{});if(!w){p.code(404).send({error:"session not found"});return}let y=bn({record:w.record,history:g==="summary"?Ad(w.history,"summary"):w.history,promptHistory:w.promptHistory.length>0?w.promptHistory:void 0,...w.toolBlobs!==void 0?{toolBlobs:w.toolBlobs}:{},hydraVersion:le,machine:cn(),hydraHost:Oc(t)}),k=new Date().toISOString().replace(/[:.]/g,"-");p.header("Content-Disposition",`attachment; filename="${h}-${k}.hydra"`),p.code(200).send(y)}),s.get("/v1/sessions/:id/diff",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.exportBundle(h);if(!f){p.code(404).send({error:"session not found"});return}let g=l.query??{},w=g.fold==="true"||g.fold==="1",y=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,k=yc(f.history);y&&(k=k.filter(b=>y.has(b.path))),w&&(k=k.map(b=>({...b,hunks:wc(b.hunks)}))),p.code(200).send(k)}),s.get("/v1/sessions/:id/tools/:hash",async(l,p)=>{let m=l.params,h=await e.resolveCanonicalId(m.id)??m.id,f=await e.loadToolBlob(h,m.hash);if(f===null){p.code(404).send({error:"tool blob not found"});return}p.header("Content-Type","text/plain; charset=utf-8"),p.code(200).send(f)}),s.get("/v1/sessions/:id/transcript",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.exportBundle(h);if(!f){p.code(404).send({error:"session not found"});return}let g=bn({record:f.record,history:f.history,promptHistory:f.promptHistory.length>0?f.promptHistory:void 0,hydraVersion:le,machine:cn(),hydraHost:Oc(t)}),w=l.query,y=I=>I==="1"||I==="true"||I==="yes",k=I=>{let v=w?.[I];if(v===void 0||v==="")return;let A=Number(v);return Number.isFinite(A)?A:"bad"},b={};for(let I of["from","to","last","since"]){let v=k(I);if(v==="bad"){p.code(400).send({error:`${I} must be a number`});return}v!==void 0&&(b[I==="since"?"sinceMs":I]=v)}p.header("Content-Type","text/markdown; charset=utf-8"),p.code(200).send(vc(g,{includeTools:y(w?.tools),includeThoughts:y(w?.thoughts),...b}))}),s.post("/v1/sessions/:id/fork",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{},g={};if(f.forkAt!==void 0){if(typeof f.forkAt!="string"||f.forkAt.length===0){p.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=f.forkAt}if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=ce(f.cwd)}if(f.agentId!==void 0){if(typeof f.agentId!="string"||f.agentId.length===0){p.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=f.agentId}if(f.title!==void 0){if(typeof f.title!="string"){p.code(400).send({error:"title must be a string"});return}g.title=f.title}if(f.mode!==void 0){if(f.mode!=="verbatim"&&f.mode!=="synthesis"){p.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=f.mode}if(f.model!==void 0){if(typeof f.model!="string"||f.model.length===0){p.code(400).send({error:"model must be a non-empty string"});return}g.model=f.model}try{let w=await e.forkSession(h,g);p.code(201).send(w)}catch(w){let y=w;if(y.code===E.SessionNotFound){p.code(404).send({error:y.message});return}if(y.code===E.InvalidParams||y.code===E.AgentNotInstalled){p.code(400).send({error:y.message});return}p.code(500).send({error:y.message})}}),s.post("/v1/sessions/import",async(l,p)=>{let m=l.body??{};if(m.bundle===void 0){p.code(400).send({error:"missing bundle"});return}let h;if(m.cwd!==void 0){if(typeof m.cwd!="string"||m.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}h=m.cwd}let f;try{f=_d(m.bundle)}catch(g){p.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(f,{replace:m.replace===!0,...h!==void 0?{cwd:h}:{}});p.code(201).send(g)}catch(g){let w=g;if(w.code===E.BundleAlreadyImported){p.code(409).send({error:"bundle already imported",existingSessionId:w.existingSessionId});return}p.code(500).send({error:w.message})}}),s.get("/v1/sessions/:id/compact/status",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h),g;if(f?g=f.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(h),g===void 0&&!await e.hasRecord(h))return p.code(404).send({error:"session not found"}),p;let w=await e.getCompactionState(h),y=await e.getRollbackBreadcrumb(h),k=await e.getPendingAgentSwap(h),b=!1,I,v=f?.currentUsage,A=typeof v?.used=="number"&&typeof v?.size=="number"&&v.size>0?{used:v.used,size:v.size}:void 0,C=await e.loadHistory(h,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(C.length>0&&t.compaction){let R=g??0,T=C.length,_=R<=C.length?R:0,H=C.slice(_),J=ic(H);I=Mo(J);let M=f?.currentModel,W=C.at(-1).recordedAt;b=ac({summarizedThroughEntry:R,totalEntries:T,unsummarizedChars:J,compactionInFlight:e.getCompactionInFlight(),currentModel:M,lastActivityMs:W,nowMs:Date.now(),config:t.compaction,...typeof v?.used=="number"?{agentReportedUsed:v.used}:{},...typeof v?.size=="number"?{agentReportedSize:v.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...I!=null?{approxTokens:I}:{},...A!=null?{currentUsage:A}:{},...w!=null?{compactionState:w}:{},...y!=null?{rollbackBreadcrumb:y}:{},...k!=null?{pendingAgentSwap:k}:{}}}),s.post("/v1/sessions/:id/compact",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m;if(e.get(h)){e.scheduleCompaction(h),p.code(202).send({scheduled:!0});return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}e.scheduleCompaction(h),p.code(202).send({scheduled:!0})}),s.post("/v1/sessions/:id/compact/rollback",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m;if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}try{await e.performUncompact(h),p.code(202).send({rolledBack:!0})}catch(f){let g=f instanceof Error?f.message:String(f);p.code(409).send({error:g})}}),s.post("/v1/sessions/:id/workspace/clean",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{};if(f.deep!==void 0&&typeof f.deep!="boolean"){p.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}if(e.get(h)===void 0){p.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(h,"clean",void 0,{deep:f.deep===!0});p.code(202).send({report:g})}catch(g){p.code(409).send({error:g instanceof Error?g.message:String(g)})}}),s.get("/v1/sessions/:id/history",async(l,p)=>{let m=l.params.id,h=l.query,f=h?.follow==="1"||h?.follow==="true",g=await e.resolveCanonicalId(m)??m,w=e.get(g),y,k,b=!1,I=1e4,v=[];if(w){f&&(k=w.onBroadcast(C=>{p.raw.writableEnded||(b?p.raw.write(JSON.stringify(C)+`
193
+ `))s.push(o);s.push(r)}function $n(s){return s.replace(new RegExp(bc,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function Fo(s){return s.toLocaleString("en-US")}function Re(s){return s==="127.0.0.1"||s==="::1"||s==="localhost"||s==="[::1]"}function lh(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=>fh(u)).filter(u=>u.term.length>0);return{operator:o,terms:c}}function fh(s){let e=/^(\w+):"([^"]*)"$/.exec(s);if(e)return{scope:Sc(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:Sc(n[1]),term:n[2].trim()}:{scope:"all",term:s.trim()}}function Sc(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 ph(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 gh=5,mh=200,Ls=72,hh=24,yh=512;function xc(s){return Number.isFinite(s)?Math.max(hh,Math.min(yh,Math.floor(s))):Ls}async function Ec(s,e,t={}){let n=lh(e);if(n.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??gh,o=t.maxSessions??mh,i=xc(t.snippetWidth??Ls),a=t.sessionIds?new Set(t.sessionIds):null,d=await s.list(),c=a?d.filter(p=>a.has(p.sessionId)):d,u=[],l=!1;for(let p of c){if(u.length>=o){l=!0;break}let m=await s.loadHistory(p.sessionId,{tools:"references"}).catch(()=>[]),h=kh(m,n,r,i,wh(p));if(h.snippets.length===0)continue;let f={sessionId:p.sessionId,cwd:p.cwd,status:p.status,updatedAt:p.updatedAt,totalMatches:h.totalMatches,snippets:h.snippets};p.title!==void 0&&(f.title=p.title),u.push(f)}return{query:e,truncated:l,results:u}}function wh(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 kh(s,e,t,n=Ls,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=vh(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 vh(s,e,t,n,r,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let u of s){let l=bh(u).filter(p=>ph(t,p.kind));for(let p of l){let m=p.text.toLowerCase();if(p.kind==="edit"){let g=o?.(p.text);if(!(Ic(p.text,e)||(g!==void 0&&g!==p.text?Ic(g,e):!1))||c.has(p.text))continue;if(c.add(p.text),a+=1,d.length<n){let y={kind:"edit",text:p.text,recordedAt:u.recordedAt};p.toolName!==void 0&&(y.toolName=p.toolName),d.push(y)}continue}let h=m.indexOf(i);if(h===-1)continue;let f=0;for(;h!==-1;)f++,h=m.indexOf(i,h+i.length);if(a+=f,d.length<n){let g=m.indexOf(i),w={kind:p.kind,text:Eh(p.text,g,i.length,r),recordedAt:u.recordedAt};p.toolName!==void 0&&(w.toolName=p.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function bh(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=Hs(n.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof n.text=="string"?Me(n.text):Hs(n.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(Rh(n))return[];let o=Hs(n.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=xh(n.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return Sh(n);default:return[]}}function Sh(s){let e=Cc(s,"name"),t=Cc(s,"title"),n=[];if(t!==void 0){let a=re(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=re(e);a.length>0&&n.push({kind:"tool",toolName:e,text:a})}let r=s.rawInput;if(r&&typeof r=="object"){let a=Rc(r);if(a.length>0){let d={kind:"tool-input",text:re(a)};e!==void 0&&(d.toolName=e),n.push(d)}}for(let a of Ih(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=Rc(o);if(a.length>0){let d={kind:"tool-input",text:re(a)};e!==void 0&&(d.toolName=e),n.push(d)}}let i=Ah(s);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),n.push(a)}return n}function Ih(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 Ic(s,e){let t=Ac(s.toLowerCase()),n=Ac(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 Ac(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Ah(s){if(!Ch(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=re(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=re(n);if(r.length>0)return r}}return null}function Ch(s){return s==="failed"||s==="rejected"||s==="cancelled"}function Rh(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 Hs(s){if(typeof s=="string")return Me(s);if(!s||typeof s!="object"||Array.isArray(s))return"";let e=s;return typeof e.text=="string"?Me(e.text):""}function xh(s){if(!Array.isArray(s))return"";let e=[];for(let t of s){let n=Hs(t);n.length>0&&e.push(n)}return e.join("")}function Cc(s,e){let t=s[e];return typeof t=="string"?t:void 0}function Rc(s){try{return JSON.stringify(s)}catch{return""}}function Eh(s,e,t,n=Ls){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=xc(n),c=Math.max(0,d-i.length),u=Math.floor(c/2),l=Math.min(u,a),p=Math.min(c-l,r.length-(a+i.length)),m=Math.max(0,a-(c-p)),h=Math.min(r.length,a+i.length+p),f=m>0?"\u2026":"",g=h<r.length?"\u2026":"";return`${f}${r.slice(m,h)}${g}`}import{randomBytes as Pc}from"crypto";function Tc(s){let e=Pc(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 No(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(Tc({name:"hydra-acp-stdin",session:n,tokenRegistry:e,getOrigin:t})),r.push(Tc({name:"hydra-acp-recall",session:n,tokenRegistry:e,getOrigin:t}));let o=Kt(s.deps);return o!==void 0&&(o.bindToSession(n),r=[...r,...o.descriptors]),r}}function Kt(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=Pc(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 Th=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function Mc(s,e){let t=e.fetchImpl??fetch;s.addHook("preHandler",async(n,r)=>{let o=n.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=n.params,a=i.id;if(typeof a!="string")return;let d=dt(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let w=e.localMiss.cache.findByLocalId(a);if(w.length===0)return;if(w.length>1){r.code(404).send({error:`Session "${a}" exists on more than one remote (${w.map(y=>y.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=w[0]}let c=e.store.get(d.name);if(!c){r.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let u=n.query;if(Th.has(o)&&Mh(u?.follow)){let w=c.port===Tt?"":`:${c.port}`;r.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${w}/${d.localId} instead.`});return}let l=_h(o,i,d.localId,n.url),m=`${Re(c.host)?"http":"https"}://${c.host}:${c.port}${l}`,h;try{h=await t(m,{method:n.method,headers:{Authorization:`Bearer ${c.token}`,...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0&&n.method!=="GET"?{body:JSON.stringify(n.body)}:{}})}catch(w){r.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${w.message}`});return}if(n.method==="DELETE"&&o==="/v1/sessions/:id"&&(h.ok||h.status===404)&&e.localMiss?.cache.evict(d.name,d.localId),h.status===204){r.code(204).send();return}let f=await h.text(),g=h.headers.get("content-type");g&&r.header("content-type",g),r.code(h.status).send(f)})}var Ph=5e3,Us=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??Ph),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(n=>n.name));for(let n of[...this.perPeer.keys()])t.has(n)||this.perPeer.delete(n);await Promise.allSettled(this.store.list().map(async n=>{let r=this.store.get(n.name);if(!r)return;let o=this.perPeer.get(n.name),i=Re(r.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${r.host}:${r.port}/v1/sessions?${a.toString()}`,u;try{u=await e(c,{headers:{Authorization:`Bearer ${r.token}`}})}catch{return}if(!u.ok)return;let l=await u.json(),p=o?.sessions??new Map;if(d){for(let[m,h]of[...p])h.status!=="cold"&&p.delete(m);for(let m of l.removed??[])p.delete(qe({name:n.name,localId:m}))}else p.clear();for(let m of l.sessions??[]){let h=qe({name:n.name,localId:String(m.sessionId)});p.set(h,{...m,sessionId:h,remote:n.name})}this.perPeer.set(n.name,{cursor:l.cursor,sessions:p})}))}list(e){let t=[];for(let n of this.perPeer.values())t.push(...n.sessions.values());return t.filter(n=>!(e.status&&n.status!==e.status||!e.includeNonInteractive&&n.interactive!==!0))}evict(e,t){this.perPeer.get(e)?.sessions.delete(qe({name:e,localId:t}))}findByLocalId(e){let t=e.startsWith(Ae)?[e]:[e,Ae+e],n=[];for(let[r,o]of this.perPeer)for(let i of t)if(o.sessions.has(qe({name:r,localId:i}))){n.push({name:r,localId:i});break}return n}};async function _c(s,e,t,n=fetch){let r=s.get(e);if(!r)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Re(r.host)?"http":"https"}://${r.host}:${r.port}/v1/sessions`,a;try{a=await n(i,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(l){return{status:502,body:{error:`Could not reach remote "${e}" (${r.host}:${r.port}): ${l.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let u=c;return u&&typeof u.sessionId=="string"?{status:a.status,body:{...u,sessionId:qe({name:e,localId:u.sessionId})}}:{status:a.status,body:c}}async function $c(s,e,t=fetch){let n;if(e.sessionIds===void 0)n=s.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=dt(d);if(!c)continue;let u=a.get(c.name)??[];u.push(c.localId),a.set(c.name,u)}n=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(n.length===0)return{query:e.q,truncated:!1,results:[]};let r=await Promise.all(n.map(async a=>{let d=s.get(a.name);if(!d)return null;let u=`${Re(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,l;try{l=await t(u,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!l.ok)return null;let p;try{p=await l.json()}catch{return null}let m=p;if(!m||!Array.isArray(m.results))return null;let h=m.results.map(f=>({...f,sessionId:qe({name:a.name,localId:f.sessionId})}));return{query:e.q,truncated:m.truncated===!0,results:h}})),o=[],i=!1;for(let a of r)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function Mh(s){return s==="1"||s==="true"||s===!0}function _h(s,e,t,n){let r=s.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=n.indexOf("?");return o===-1?r:r+n.slice(o)}var Bs=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Oc(s){if(s.publicHost&&s.publicHost.length>0)return s.publicHost;if(s.host&&!Re(s.host))return s.port!==void 0?`${s.host}:${s.port}`:s.host}function Nc(s,e,t,n={},r,o){s.get("/v1/sessions",async(l,p)=>{let m=l.query,h=m?.includeNonInteractive==="1"||m?.includeNonInteractive==="true",f;if(m?.since!==void 0&&(f=Number(m.since),!Number.isFinite(f)||f<0))return p.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(m.since)}`});let g=m?.status==="warm"||m?.status==="cold"?m.status:void 0,w={cwd:m?.cwd,includeNonInteractive:h,...g?{status:g}:{}},y=o&&!w.cwd?o.list({includeNonInteractive:h,...g?{status:g}:{}}):[];if(f!==void 0){let b=await e.listSince(w,f);return{sessions:[...b.entries,...y],removed:b.removed,cursor:b.cursor}}let k=await e.listing(w);return{sessions:[...k.entries,...y],removed:[],cursor:k.cursor}}),s.get("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.getOne(h);return f||(p.code(404).send({error:"session not found"}),p)}),s.post("/v1/sessions/search",async(l,p)=>{let m=l.body??{},h=typeof m.q=="string"?m.q:"";if(h.trim().length===0)return p.code(400).send({error:"q is required"}),p;let f=Array.isArray(m.sessionIds)?m.sessionIds.filter(k=>typeof k=="string"&&k.length>0):void 0,g={sessionIds:f};typeof m.snippetWidth=="number"&&(g.snippetWidth=m.snippetWidth);let w=await Ec(e,h,g);if(!r)return w;let y=await $c(r,{q:h,...f?{sessionIds:f}:{},...g.snippetWidth!==void 0?{snippetWidth:g.snippetWidth}:{}});return{query:h,truncated:w.truncated||y.truncated,results:[...w.results,...y.results]}}),s.post("/v1/sessions",async(l,p)=>{let m=l.body??{};if(m.remote){if(!r)return p.code(404).send({error:`No remote named "${m.remote}". Run \`hydra remote add\` first.`});let k=await _c(r,m.remote,{cwd:m.cwd,agentId:m.agentId,mcpServers:m.mcpServers,workspace:m.workspace});return p.code(k.status).send(k.body)}let h=ce(m.cwd??t.cwd),f=await sn(h),g=m.agentId??f.agentId??t.agentId,w=Kt(n),y=w!==void 0?[...m.mcpServers??[],...w.descriptors]:m.mcpServers;try{let k=await e.create({cwd:h,agentId:g,mcpServers:y,...m.workspace!==void 0?{workspace:m.workspace}:{}});w!==void 0&&w.bindToSession(k),p.code(201).send({sessionId:k.sessionId,agentId:k.agentId,cwd:k.cwd,...k.workspace!==void 0?{workspace:k.workspace}:{},...k.workspaceError!==void 0?{workspaceError:k.workspaceError}:{}})}catch(k){w!==void 0&&w.abandon(k instanceof Error?k:void 0),p.code(500).send({error:k.message})}}),s.post("/v1/sessions/collect",async(l,p)=>{let m=l.body??{},h=typeof m.maxAgeDays=="number"&&m.maxAgeDays>0?m.maxAgeDays*24*60*60*1e3:0,f=typeof m.limit=="number"&&m.limit>0?m.limit:1e3,g=m.selection==="explicit"||m.selection==="unpromoted"?m.selection:"unpromoted";try{let w=await Po({manager:e,maxAgeMs:h,maxDeletions:f,selection:g,verbose:!1});p.code(200).send(w)}catch(w){p.code(500).send({error:w.message})}}),s.post("/v1/sessions/:id/kill",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(f){f.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),p.code(202).send();return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.post("/v1/sessions/:id/stdin/open",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(!f)return p.code(404).send({error:"session not found"}),p;let g=l.body??{},w={};(g.mode==="memory"||g.mode==="file")&&(w.mode=g.mode),typeof g.capacityBytes=="number"&&(w.capacityBytes=g.capacityBytes),typeof g.fileCapBytes=="number"&&(w.fileCapBytes=g.fileCapBytes),(w.mode??"memory")==="file"&&(w.filePathFor=y=>Ws.join(Fc.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return f.openStream(w)}catch(y){return p.code(409).send({error:y.message}),p}}),s.post("/v1/sessions/:id/stdin",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(!f)return p.code(404).send({error:"session not found"}),p;let g=l.body??{},w=typeof g.chunk=="string"?g.chunk:"",y=g.eof===!0;try{return f.streamWrite(w,y)}catch(k){return p.code(409).send({error:k.message}),p}}),s.patch("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{};if(f.cwd!==void 0){if(typeof f.cwd!="string"||!Ws.isAbsolute(f.cwd)){p.code(400).send({error:"cwd must be an absolute path"});return}let w=await e.setCwd(h,f.cwd);if(w==="missing"){p.code(404).send({error:"session not found"});return}if(w==="not-a-directory"){p.code(400).send({error:`${f.cwd} is not a directory`});return}if(w==="live"){p.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(w==="bound"){p.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}p.code(204).send();return}if("workspace"in f){if(f.workspace!==null){p.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let w=await e.clearWorkspaceBinding(h);if(w==="missing"){p.code(404).send({error:"session not found"});return}if(w==="live"){p.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}p.code(204).send();return}if(f.priority!==void 0){let w=f.priority,y;if(w===null||w===0)y=void 0;else if(typeof w=="number"&&Number.isInteger(w)&&w>0)y=w;else{p.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(h,y)){p.code(404).send({error:"session not found"});return}p.code(204).send();return}if(f.regen===!0){if(!(e.get(h)!==void 0||await e.hasRecord(h))){p.code(404).send({error:"session not found"});return}e.scheduleSynopsis(h),p.code(202).send();return}if(typeof f.title!="string"||f.title.trim().length===0){p.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(h,f.title)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.delete("/v1/sessions/:id",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);if(f){await f.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(h),await e.hasRecord(h)&&await e.deleteRecord(h),p.code(204).send();return}if(!await e.deleteRecord(h)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),s.get("/v1/sessions/:id/export",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.query?.tools,g=f==="references"?"references":Id(f),w=await e.exportBundle(h,g==="references"?{tools:"references"}:{});if(!w){p.code(404).send({error:"session not found"});return}let y=bn({record:w.record,history:g==="summary"?Ad(w.history,"summary"):w.history,promptHistory:w.promptHistory.length>0?w.promptHistory:void 0,...w.toolBlobs!==void 0?{toolBlobs:w.toolBlobs}:{},hydraVersion:le,machine:cn(),hydraHost:Oc(t)}),k=new Date().toISOString().replace(/[:.]/g,"-");p.header("Content-Disposition",`attachment; filename="${h}-${k}.hydra"`),p.code(200).send(y)}),s.get("/v1/sessions/:id/diff",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.exportBundle(h);if(!f){p.code(404).send({error:"session not found"});return}let g=l.query??{},w=g.fold==="true"||g.fold==="1",y=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,k=yc(f.history);y&&(k=k.filter(b=>y.has(b.path))),w&&(k=k.map(b=>({...b,hunks:wc(b.hunks)}))),p.code(200).send(k)}),s.get("/v1/sessions/:id/tools/:hash",async(l,p)=>{let m=l.params,h=await e.resolveCanonicalId(m.id)??m.id,f=await e.loadToolBlob(h,m.hash);if(f===null){p.code(404).send({error:"tool blob not found"});return}p.header("Content-Type","text/plain; charset=utf-8"),p.code(200).send(f)}),s.get("/v1/sessions/:id/transcript",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=await e.exportBundle(h);if(!f){p.code(404).send({error:"session not found"});return}let g=bn({record:f.record,history:f.history,promptHistory:f.promptHistory.length>0?f.promptHistory:void 0,hydraVersion:le,machine:cn(),hydraHost:Oc(t)}),w=l.query,y=I=>I==="1"||I==="true"||I==="yes",k=I=>{let v=w?.[I];if(v===void 0||v==="")return;let A=Number(v);return Number.isFinite(A)?A:"bad"},b={};for(let I of["from","to","last","since"]){let v=k(I);if(v==="bad"){p.code(400).send({error:`${I} must be a number`});return}v!==void 0&&(b[I==="since"?"sinceMs":I]=v)}p.header("Content-Type","text/markdown; charset=utf-8"),p.code(200).send(vc(g,{includeTools:y(w?.tools),includeThoughts:y(w?.thoughts),...b}))}),s.post("/v1/sessions/:id/fork",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{},g={};if(f.forkAt!==void 0){if(typeof f.forkAt!="string"||f.forkAt.length===0){p.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=f.forkAt}if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=ce(f.cwd)}if(f.agentId!==void 0){if(typeof f.agentId!="string"||f.agentId.length===0){p.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=f.agentId}if(f.title!==void 0){if(typeof f.title!="string"){p.code(400).send({error:"title must be a string"});return}g.title=f.title}if(f.mode!==void 0){if(f.mode!=="verbatim"&&f.mode!=="synthesis"){p.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=f.mode}if(f.model!==void 0){if(typeof f.model!="string"||f.model.length===0){p.code(400).send({error:"model must be a non-empty string"});return}g.model=f.model}try{let w=await e.forkSession(h,g);p.code(201).send(w)}catch(w){let y=w;if(y.code===E.SessionNotFound){p.code(404).send({error:y.message});return}if(y.code===E.InvalidParams||y.code===E.AgentNotInstalled){p.code(400).send({error:y.message});return}p.code(500).send({error:y.message})}}),s.post("/v1/sessions/import",async(l,p)=>{let m=l.body??{};if(m.bundle===void 0){p.code(400).send({error:"missing bundle"});return}let h;if(m.cwd!==void 0){if(typeof m.cwd!="string"||m.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}h=m.cwd}let f;try{f=_d(m.bundle)}catch(g){p.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(f,{replace:m.replace===!0,...h!==void 0?{cwd:h}:{}});p.code(201).send(g)}catch(g){let w=g;if(w.code===E.BundleAlreadyImported){p.code(409).send({error:"bundle already imported",existingSessionId:w.existingSessionId});return}p.code(500).send({error:w.message})}}),s.get("/v1/sessions/:id/compact/status",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h),g;if(f?g=f.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(h),g===void 0&&!await e.hasRecord(h))return p.code(404).send({error:"session not found"}),p;let w=await e.getCompactionState(h),y=await e.getRollbackBreadcrumb(h),k=await e.getPendingAgentSwap(h),b=!1,I,v=f?.currentUsage,A=typeof v?.used=="number"&&typeof v?.size=="number"&&v.size>0?{used:v.used,size:v.size}:void 0,C=await e.loadHistory(h,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(C.length>0&&t.compaction){let R=g??0,T=C.length,_=R<=C.length?R:0,H=C.slice(_),J=ic(H);I=Mo(J);let M=f?.currentModel,W=C.at(-1).recordedAt;b=ac({summarizedThroughEntry:R,totalEntries:T,unsummarizedChars:J,compactionInFlight:e.getCompactionInFlight(),currentModel:M,lastActivityMs:W,nowMs:Date.now(),config:t.compaction,...typeof v?.used=="number"?{agentReportedUsed:v.used}:{},...typeof v?.size=="number"?{agentReportedSize:v.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...I!=null?{approxTokens:I}:{},...A!=null?{currentUsage:A}:{},...w!=null?{compactionState:w}:{},...y!=null?{rollbackBreadcrumb:y}:{},...k!=null?{pendingAgentSwap:k}:{}}}),s.post("/v1/sessions/:id/compact",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m;if(e.get(h)){e.scheduleCompaction(h),p.code(202).send({scheduled:!0});return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}e.scheduleCompaction(h),p.code(202).send({scheduled:!0})}),s.post("/v1/sessions/:id/compact/rollback",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m;if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}try{await e.performUncompact(h),p.code(202).send({rolledBack:!0})}catch(f){let g=f instanceof Error?f.message:String(f);p.code(409).send({error:g})}}),s.post("/v1/sessions/:id/workspace/clean",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=l.body??{};if(f.deep!==void 0&&typeof f.deep!="boolean"){p.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}if(e.get(h)===void 0){p.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(h,"clean",void 0,{deep:f.deep===!0});p.code(202).send({report:g})}catch(g){p.code(409).send({error:g instanceof Error?g.message:String(g)})}}),s.get("/v1/sessions/:id/history",async(l,p)=>{let m=l.params.id,h=l.query,f=h?.follow==="1"||h?.follow==="true",g=await e.resolveCanonicalId(m)??m,w=e.get(g),y,k,b=!1,I=1e4,v=[];if(w){f&&(k=w.onBroadcast(C=>{p.raw.writableEnded||(b?p.raw.write(JSON.stringify(C)+`
194
194
  `):(v.push(C),v.length>I&&v.shift()))})),l.raw.on("close",()=>{k?.(),p.raw.writableEnded||p.raw.end()});try{y=await w.getHistorySnapshot()}catch(C){throw k?.(),C}}else{let C=await e.getHistory(g);if(C===void 0)return p.code(404).send({error:"session not found"}),p;y=C}p.raw.setHeader("Content-Type","application/x-ndjson"),p.raw.setHeader("Cache-Control","no-cache"),p.raw.statusCode=200;let A=new Set;for(let C of y??[]){p.raw.write(JSON.stringify(C)+`
195
195
  `);let R=C;typeof R.recordedAt=="number"&&A.add(String(R.recordedAt))}for(;v.length>0;){let C=v.splice(0,v.length);for(let R of C){let T=R,_=typeof T.recordedAt=="number"?String(T.recordedAt):"";_&&A.has(_)||p.raw.write(JSON.stringify(R)+`
196
196
  `)}}return b=!0,k||p.raw.end(),p});function i(l,p,m){let h=typeof l=="string"?l.trim():"";if(h.length===0)return null;let f;try{f=JSON.parse(h)}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 g=f;if(typeof g.recordedAt!="number"||m!==void 0&&g.recordedAt<m||typeof g.params!="object"||g.params===null||Array.isArray(g.params))return null;let w=g.params;if(typeof w.update!="object"||w.update===null||Array.isArray(w.update))return null;let k=w.update.sessionUpdate;return typeof k!="string"||!p.has(k)?null:{recordedAt:g.recordedAt,entry:f}}function a(l,p,m){let f=p.params.update,g={sessionId:l,ts:new Date(p.recordedAt).toISOString(),kind:m,update:f};return f.messageId!==void 0&&f.messageId!==null&&(g.messageId=f.messageId),g}async function*d(l,p,m,h){for await(let f of p){let g=i(f,m,h);if(g){let w=g.entry.params.update.sessionUpdate;yield{ts:g.recordedAt,row:a(l,g.entry,w)}}}}async function c(l,p,m,h){let f=jo.createInterface({input:Do.createReadStream(p),crlfDelay:1/0}),g=d(l,f,m,h),w=await g.next(),y=w.done?null:w.value;return{sessionId:l,rl:f,gen:g,current:y,exhausted:y===null}}async function u(l){let p=await l.gen.next();p.done?(l.exhausted=!0,l.current=null):l.current=p.value}s.get("/v1/sessions/events",async(l,p)=>{let m=l.query,h=m.kinds;if(!h||h.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let f=h.split(",").map(I=>I.trim());if(f.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let I of f)if(!Bs.has(I))return p.code(400).send({error:`kind "${I}" is not queryable; allowed kinds: ${[...Bs].join(", ")}`}),p;let g=new Set(f),w;if(m.since!==void 0&&m.since.trim().length>0){let I=new Date(m.since);if(isNaN(I.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;w=I.getTime()}let y=await e.list({includeNonInteractive:!0}),k=w!==void 0?y.filter(I=>new Date(I.updatedAt).getTime()>=w):y;p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;let b=[];for(let I of k)try{let v=x.historyFile(I.sessionId),A=await c(I.sessionId,v,g,w);A.exhausted||b.push(A)}catch(v){if(v.code==="ENOENT")continue;throw v}l.raw.on("close",()=>{for(let I of b)try{I.rl.close()}catch{}p.raw.writableEnded||p.raw.end()});try{for(;b.length>0;){let I=-1,v=1/0;for(let C=0;C<b.length;C++){let R=b[C];R.current!==null&&R.current.ts<v&&(v=R.current.ts,I=C)}if(I===-1)break;let A=b[I];if(p.raw.write(JSON.stringify(A.current.row)+`
197
197
  `),await u(A),A.exhausted){try{A.rl.close()}catch{}b.splice(I,1)}}}catch(I){for(let v of b)try{v.rl.close()}catch{}throw I}return p.raw.end(),p}),s.get("/v1/sessions/:id/events",async(l,p)=>{let m=l.params.id,h=l.query,f=await e.resolveCanonicalId(m)??m;if(!e.get(f)&&!await e.hasRecord(f))return p.code(404).send({error:"session not found"}),p;let w=h.kinds;if(!w||w.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let y=w.split(",").map(C=>C.trim());if(y.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let C of y)if(!Bs.has(C))return p.code(400).send({error:`kind "${C}" is not queryable; allowed kinds: ${[...Bs].join(", ")}`}),p;let k=new Set(y),b;if(h.since!==void 0&&h.since.trim().length>0){let C=new Date(h.since);if(isNaN(C.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;b=C.getTime()}let I=x.historyFile(f),v=Do.createReadStream(I),A=jo.createInterface({input:v,crlfDelay:1/0});p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;try{for await(let C of A){let R=typeof C=="string"?C.trim():"";if(R.length===0)continue;let T;try{T=JSON.parse(R)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",I);continue}if(!T||typeof T!="object"||Array.isArray(T)){console.debug("events endpoint: skipping non-object JSONL line in %s",I);continue}let _=T;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let H=_.params;if(typeof H.update!="object"||H.update===null||Array.isArray(H.update))continue;let J=H.update,M=J.sessionUpdate;if(typeof M!="string"||!k.has(M)||b!==void 0&&_.recordedAt<b)continue;let W={ts:new Date(_.recordedAt).toISOString(),kind:M,update:J};J.messageId!==void 0&&J.messageId!==null&&(W.messageId=J.messageId),p.raw.write(JSON.stringify(W)+`
198
- `)}}catch(C){if(C.code==="ENOENT")return p.raw.end(),p;throw C}return p.raw.end(),p}),s.post("/v1/sessions/:id/prompt/:messageId/notify",async(l,p)=>{let m=l.params,h=m.id,f=await e.resolveCanonicalId(h)??h,g=m.messageId,w=l.body,y=typeof w?.callbackUrl=="string"?w.callbackUrl:"",k=typeof w?.secret=="string"?w.secret:"";if(!g||!y||!k){p.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let b;try{b=new URL(y)}catch{p.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(b.protocol!=="https:"&&b.protocol!=="http:"){p.code(400).send({error:"callbackUrl must be http or https"});return}let I=e.get(f);if(!I){p.code(404).send({error:"session not found or not warm"});return}let v=I.registerTurnNotify(g,y,k);if(v.alreadyTerminal){p.code(200).send({status:"already_terminal",stopReason:v.stopReason});return}p.code(202).send({status:"registered"})}),s.get("/v1/sessions/:id/attention",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);return!f&&!await e.hasRecord(h)?(p.code(404).send({error:"session not found"}),p):f?{flags:f.listAttentionFlags()}:{flags:(await e.store.read(h))?.attentionFlags??[]}}),s.get("/v1/sessions/attention",async(l,p)=>{let m=l.query;if(!m.source||m.source.trim().length===0)return p.code(400).send({error:"source query parameter is required"}),p;let h=await e.list({includeNonInteractive:!0}),f=[];for(let g of h){let w=e.get(g.sessionId),y;w?y=w.listAttentionFlags():y=(await e.store.read(g.sessionId))?.attentionFlags??[];for(let k of y)k.source===m.source&&f.push({...k,sessionId:g.sessionId})}return{flags:f}}),s.post("/v1/sessions/:id/attention/clear",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,g=l.body??{},w=typeof g.source=="string"?g.source:"",y=typeof g.reason=="string"?g.reason:"";if((w.length>0||y.length>0)&&!(w.length>0&&y.length>0)){p.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}w.length===0&&y.length;let k=e.get(h);if(k){if(w.length>0&&y.length>0)k.clearAttentionFlag(w,y);else{let C=Array.from(k.listAttentionFlags()).map(R=>`${R.source}::${R.reason}`);for(let R of C)k.clearAttentionFlag(R.split("::")[0],R.split("::").slice(1).join("::"))}p.code(204).send();return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}let b=e.store,I=await b.read(h);if(!I){p.code(404).send({error:"session not found"});return}let v=I.attentionFlags??[],A;if(w.length>0&&y.length>0){let C=`${w}::${y}`;A=v.filter(R=>`${R.source}::${R.reason}`!==C)}else A=[];if(A.length===v.length&&A.every((C,R)=>C.source===v[R].source&&C.reason===v[R].reason)){p.code(204).send();return}await b.write({...I,attentionFlags:A}),p.code(204).send()})}function Dc(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 Te(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===E.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}G();function jc(s,e,t,n=()=>[]){s.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:x.home(),driftedKeys:n()}))}var $h=/^[A-Za-z0-9._-]+$/;function qs(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=Oh(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){On(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){On(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){On(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){On(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){On(i,d)}})}function On(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 Oh(s){let e=s.name;if(typeof e!="string"||!$h.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 Hc(s,e){qs(s,"extension",e)}function Lc(s,e){qs(s,"transformer",e)}function Uc(s,e){s.get("/v1/config",async()=>e())}import{z as ft}from"zod";G();import*as Qt from"fs/promises";import*as Bc from"path";import{randomBytes as mA,scrypt as Fh,timingSafeEqual as Nh}from"crypto";import{promisify as Dh}from"util";var jh=Dh(Fh);function Wc(){return Bc.join(x.home(),"password-hash")}var Hh=128*1024*1024;async function qc(){try{return(await Qt.readFile(Wc(),"utf8")).trim().length>0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function zc(s){if(typeof s!="string"||s.length===0)return!1;let e;try{e=(await Qt.readFile(Wc(),"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 jh(s,i,a.length,{N:n,r,p:o,maxmem:Hh});return d.length!==a.length?!1:Nh(d,a)}var Lh=ft.object({password:ft.string().min(1),label:ft.string().min(1).max(256).optional(),ttlSec:ft.number().int().positive().optional()}),Uh=ft.object({id:ft.string().optional()}).optional(),Bh=ft.object({token:ft.string().min(32)});function Jc(s,e){s.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,n)=>{let r=Wh(t);if(e.rateLimiter.isBlocked(r))return n.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=Lh.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}if(!await qc())return n.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await zc(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=Uh.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",async(t,n)=>{let r=await e.store.revokeAll();return n.code(200).send({revoked:r})}),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"})}),s.post("/v1/auth/rotate-token",async(t,n)=>{if(t.authIdentity!=="service")return n.code(403).send({error:"Requires the service token"});let r;try{r=Bh.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(r.token),n.code(200).send({rotated:!0})})}function Wh(s){return s.ip||"unknown"}import{z as pt}from"zod";G();Ne();var Ho=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,zs=class s{data;constructor(e){this.data=e}static async load(){let e=await ie(x.peers());return new s(qh(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await Vc(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await Vc(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:n,expiresAt:r,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:n,expiresAt:r,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function qh(s){if(!s||typeof s!="object")return{version:1,entries:{}};let e=s,t=e.entries&&typeof e.entries=="object"?e.entries:{},n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),n[r]=a}return{version:1,entries:n}}async function Vc(s){await pe(x.peers(),s,{mode:384})}var zh=3600*24*365,Ve=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function Gc(s,e){return`${Re(s)?"http":"https"}://${s}:${e}`}async function Kc(s){let e=s.fetchImpl??fetch,t=`${s.host}:${s.port}`,n=Gc(s.host,s.port),r;try{r=await e(`${n}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s.password,label:s.label,ttlSec:s.ttlSec??zh})})}catch(i){throw new Ve(`Could not reach ${t}: ${i.message}`,502)}if(r.status===401)throw new Ve(`Wrong password for ${t}.`,401);if(r.status===403)throw new Ve(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(r.status===429)throw new Ve(`Too many failed login attempts on ${t}; try again later.`,429);if(!r.ok)throw new Ve(`Login to ${t} failed: HTTP ${r.status}`,502);let o=await r.json();if(!o.session_token||!o.expires_at)throw new Ve(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function Qc(s){let e=s.fetchImpl??fetch,t=Gc(s.host,s.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}Nn();var sy=pt.object({name:pt.string().min(1).max(64).regex(Ho),host:pt.string().min(1),port:pt.number().int().positive().optional(),password:pt.string().min(1),label:pt.string().min(1).max(256).optional(),ttlSec:pt.number().int().positive().optional(),pinnedFingerprint:pt.string().min(1).optional()});function ou(s,e){s.post("/v1/remotes",async(t,n)=>{let r;try{r=sy.parse(t.body)}catch{return n.code(400).send({error:`Invalid request body (name must match ${Ho} and the rest is a normal login request)`})}let o=r.port??Tt;r.pinnedFingerprint&&Fn(r.host,o,r.pinnedFingerprint);let i;try{i=await Kc({host:r.host,port:o,password:r.password,label:r.label,ttlSec:r.ttlSec})}catch(c){if(c instanceof Ve)return n.code(c.status).send({error:c.message});throw c}let a=new Date().toISOString(),d={name:r.name,host:r.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:a,...r.label!==void 0?{label:r.label}:{},...r.pinnedFingerprint!==void 0?{pinnedFingerprint:r.pinnedFingerprint,pinnedAt:a}:{}};return await e.store.set(d),e.health?.markOk(d.name),n.code(201).send({name:d.name,host:d.host,port:d.port,expiresAt:d.expiresAt,label:d.label,addedAt:d.addedAt,pinnedFingerprint:d.pinnedFingerprint,status:e.health?.get(d.name)?.status??"unknown"})}),s.get("/v1/remotes",async(t,n)=>{let r=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{}}});return n.code(200).send({remotes:r})}),s.delete("/v1/remotes/:name",async(t,n)=>{let r=t.params.name,o=e.store.get(r);return o?(await Qc({host:o.host,port:o.port,token:o.token}),await e.store.delete(r),e.health?.forget(r),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||Uo(o.host,o.port),n.code(204).send()):n.code(404).send({error:"Not found"})})}function Vs(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:E.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())}}}Nn();import{WebSocket as ry}from"ws";var oy=1e4,Jo=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}};async function iu(s,e,t=oy){let n={};try{let r=new URL(s);if(r.protocol==="wss:"){let o=zo(r.hostname);o.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=o.rejectUnauthorized),o.autoSelectFamily!==void 0&&(n.autoSelectFamily=o.autoSelectFamily),o.checkServerIdentity!==void 0&&(n.checkServerIdentity=o.checkServerIdentity)}}catch{}return new Promise((r,o)=>{let i=new ry(s,e,n),a=Date.now(),d=setTimeout(()=>{i.off("open",c),i.off("error",u),i.on("error",()=>{});try{i.terminate()}catch{}o(new Jo(s,Date.now()-a))},t),c=()=>{clearTimeout(d),i.off("error",u),r(i)},u=l=>{clearTimeout(d),i.off("open",c),o(l)};i.once("open",c),i.once("error",u)})}var iy=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function ay(s){return iy.has(s)}function du(s,e,t,n){let r=[],o=a=>{for(let d of r)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:n}).then(c=>c?s.send(c):void 0).catch(()=>{})};return s.onMessage(a=>{if("method"in a&&ay(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(dt(c)){i(a,c);return}if(a.method==="session/attach"){let u="id"in a;e.resolveLocalMiss(c).then(l=>{if(l.ok){i(a,l.foreignId);return}if(l.ambiguous&&u){s.send(Dn(a.id,E.SessionNotFound,`Session "${c}" exists on more than one remote (${l.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>s.send(a),onMessage:a=>r.push(a),onClose:a=>s.onClose(a),close:()=>s.close()}}var Gs=class{constructor(e,t=cy,n){this.store=e;this.dial=t;this.localMiss=n}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(n=>n.name)}:{ok:!0,foreignId:Ye(t[0])}}async handleLocalMessage(e,t,n){let r="id"in e,o=r?e.id:void 0,i=dt(t);if(!i)return r?Dn(o,E.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=au(n.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let u=this.store.get(i.name);if(!u)return r?Dn(o,E.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let l=this.attachments.get(a);l&&(this.attachments.delete(a),l.peerConnection.close().catch(()=>{}));let p;try{p=await this.dial(u)}catch(g){return r?Dn(o,E.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let m={peerConnection:p,localId:i.localId,target:n};this.wireAttachment(i.name,m);let h;try{h=await p.request("session/attach",d)}catch(g){return p.close().catch(()=>{}),r?Vo(o,g):void 0}this.attachments.set(a,m);let f=h&&typeof h.sessionId=="string"?{...h,sessionId:t}:h;return r?{jsonrpc:"2.0",id:o,result:f}:void 0}let c=this.attachments.get(a);if(!c)return r?Dn(o,E.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let u,l;try{u=await c.peerConnection.request("session/detach",d)}catch(p){l=p}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),l?r?Vo(o,l):void 0:r?{jsonrpc:"2.0",id:o,result:u??{}}:void 0}if(r)try{let u=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:u}}catch(u){return Vo(o,u)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,n]of[...this.attachments.entries()])n.target.clientId===e&&(this.attachments.delete(t),n.peerConnection.request("session/detach",{sessionId:n.localId}).catch(()=>{}),n.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:n,localId:r,target:o}=t,i=Ye({name:e,localId:r}),a=()=>{this.attachments.delete(au(o.clientId,i))};n.onAnyNotification((d,c)=>{let u=d;!u||u.sessionId!==r||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...u,sessionId:i}).catch(()=>{}))}),n.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==r)throw{code:E.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),n.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function au(s,e){return`${s} ${e}`}function Dn(s,e,t){return{jsonrpc:"2.0",id:s,error:{code:e,message:t}}}function Vo(s,e){let t=e,n=typeof t?.code=="number"?t.code:E.InternalError,r=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:s,error:{code:n,message:r,...t?.data!==void 0?{data:t.data}:{}}}}var dy=1e4;async function cy(s){let t=`${Re(s.host)?"ws":"wss"}://${s.host}:${s.port}/acp`,n=await iu(t,["acp.v1",`hydra-acp-token.${s.token}`],dy);return new Be(Vs(n))}var uy=3e4,ly=5e3,Ks=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??uy),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString()})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let n=this.store.get(t.name);if(!n)return;let o=`${Re(n.host)?"http":"https"}://${n.host}:${n.port}/v1/auth/verify`,i=new AbortController,a=setTimeout(()=>i.abort(),ly);try{let d=await e(o,{headers:{Authorization:`Bearer ${n.token}`},signal:i.signal});this.snapshots.set(t.name,{status:d.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(d){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:d.message})}finally{clearTimeout(a)}}))}};Nn();import{z as cu}from"zod";var fy=cu.object({sessionLabel:cu.string().min(1).max(256)});function uu(s,e){s.post("/v1/process-tokens",async(t,n)=>{if(t.authIdentity!=="service")return n.code(403).send({error:"Requires the service token"});let r;try{r=fy.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(r.sessionLabel,"script");return n.code(201).send({token:o})}),s.delete("/v1/process-tokens/:sessionLabel",async(t,n)=>t.authIdentity!=="service"?n.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),n.code(204).send()))}import{nanoid as Go}from"nanoid";import{randomBytes as mu}from"crypto";import*as hu from"os";import*as yu from"path";var py=200;function gy(s){if(!s||typeof s!="object")return;let e=s._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[ae];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,py)),r.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function lu(s,e,t){let n=gy(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 jn=new Map;function fu(s,e){let t=jn.get(s);t||(t=new Set,jn.set(s,t)),t.add(e);let n=!1;return()=>{if(n)return;n=!0;let r=jn.get(s);r&&(r.delete(e),r.size===0&&jn.delete(s))}}function pu(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=jn.get(r);if(o){if(o.has(s))return!0;for(let i of o)n.push(i)}}return!1}function N(s,e,t){let n=new Error(e);return n.code=s,t!==void 0&&(n.data=t),n}function ky(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 xe(s,e,t){let n=s.get(e);if(!n)throw N(E.SessionNotFound,t??`session ${e} not found`);return n}async function xt(s,e){let t=Kt(s),n,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&s.mcpTokenRegistry!==void 0&&s.getDaemonOrigin!==void 0&&(n=mu(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=No({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 Ty(c,s),ku(c.sessionId,s),c}function wu(s,e){s.get("/acp",{websocket:!0},async(t,n)=>{let r=rc({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=`hydra_client_${Go(12)}`,a=Vs(t),d={},c=e.foreignSessions?du(a,e.foreignSessions,d,i):a,u=new Be(c);d.connection=u;let l={clientId:i,processIdentity:o,attached:new Map};u.onClose(()=>{for(let h of l.attached.values())e.manager.get(h.sessionId)?.detach(h.clientId);l.attached.clear(),e.foreignSessions?.detachClient(i)});let p=(h,f)=>{if(l.attached.get(h)?.readonly)throw N(E.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(u.onRequest("initialize",async h=>{let f=qi.parse(h??{});f.clientInfo?.name&&(l.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let g=f.clientInfo?.version;return g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g)),Ey()}),o&&e.extensionCommands){let h=e.extensionCommands;u.onRequest("hydra-acp/commands/register",async f=>{let g=f??{},w=Array.isArray(g.commands)?g.commands.map(y=>{if(!y||typeof y!="object")return;let k=y;if(typeof k.verb!="string")return;let b={verb:k.verb};return typeof k.argsHint=="string"&&(b.argsHint=k.argsHint),typeof k.description=="string"&&(b.description=k.description),b}).filter(y=>y!==void 0):[];return h.register(o.name,u,w),{ok:!0,registered:w.length}}),u.onClose(()=>{h.clear(o.name)})}if(o&&e.extensionMcp){let h=e.extensionMcp;u.onRequest("hydra-acp/mcp_tools/register",async g=>{let w=g??{},y=typeof w.instructions=="string"?w.instructions:void 0,k=Array.isArray(w.tools)?w.tools.map(b=>{if(!b||typeof b!="object")return;let I=b;if(typeof I.name!="string"||I.name.length===0||typeof I.description!="string"||I.inputSchema===null||typeof I.inputSchema!="object")return;let v={name:I.name,description:I.description,inputSchema:I.inputSchema};return I.outputSchema!==null&&typeof I.outputSchema=="object"&&(v.outputSchema=I.outputSchema),v}).filter(b=>b!==void 0):[];if(k.length===0)throw new Error("register_mcp_tools requires at least one tool");return h.register(o.name,u,y,k),{ok:!0,registered:k.length}});let f=g=>{let w=g??{};if(typeof w.sessionId!="string"||w.sessionId.length===0)throw N(E.InvalidParams,"sessionId is required");return w.sessionId};if(u.onRequest("hydra-acp/session/extension_state/get",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(!e.manager)throw N(E.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(w,o.name,y.key)??null}}),u.onRequest("hydra-acp/session/extension_state/list",async g=>{let w=f(g);if(!e.manager)throw N(E.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(w,o.name)}}),u.onRequest("hydra-acp/session/extension_state/set",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(y.value===void 0)throw N(E.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw N(E.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(w,o.name,y.key,y.value)}catch(k){throw N(E.InvalidParams,k.message)}return{ok:!0}}),u.onRequest("hydra-acp/session/extension_state/delete",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(!e.manager)throw N(E.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(w,o.name,y.key),{ok:!0}}),e.extensionMcpControls){let g=e.extensionMcpControls;u.onRequest("hydra-acp/mcp_tools/refresh_session",async w=>{let y=w??{};if(typeof y.sessionId!="string"||y.sessionId.length===0)throw N(E.InvalidParams,"refresh_session requires sessionId");return await g.notifyToolListChanged(y.sessionId,o.name),{ok:!0}})}u.onClose(()=>{h.clear(o.name)})}if(o?.kind==="transformer"){u.onRequest("hydra-acp/transformer/initialize",async f=>{let g=f??{},w=Array.isArray(g.intercepts)?g.intercepts.filter(y=>typeof y=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,u,w),e.manager?.defaultTransformers.includes(o.name))){let y=e.transformers.resolveChain([o.name])[0];if(y)for(let k of e.manager.liveSessions())k.addTransformer(y)}return{ack:!0}}),u.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),u.onRequest("hydra-acp/message/emit",async f=>{let g=f??{},w=typeof g.sessionId=="string"?g.sessionId:void 0,y=typeof g.method=="string"?g.method:void 0,k=g.envelope,b=g.route;if(!w)throw N(-32602,"emit_message requires sessionId");if(!y&&b!=="client_broadcast")throw N(-32602,"emit_message requires method");let I=xe(e.manager,w),v=typeof g.respondsTo=="string"?g.respondsTo:void 0;if(v)return I.dischargeClaim(v,k),{ok:!0};if(b==="chain")return{ok:!0,response:await I.emitToChain(o.name,y,k)};if(b==="queue"){if(y!=="session/prompt")throw N(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await I.emitToQueue(o.name,k)}}if(b==="daemon")return{ok:!0,response:await I.emitToChain(o.name,y,k)};if(b==="client_broadcast"){if(!k||typeof k!="object")throw N(-32602,"client_broadcast requires an envelope object");return I.broadcastClientUpdate(k),{ok:!0}}throw N(-32602,`unsupported route: ${JSON.stringify(b)}`)}),u.onRequest("hydra-acp/session/request_permission",async f=>{let g=f??{},w=typeof g.sessionId=="string"?g.sessionId:void 0;if(!w)throw N(-32602,"hydra-acp/session/request_permission requires sessionId");return xe(e.manager,w).requestPermissionFromClients(g)}),u.onRequest("hydra-acp/transformer/attach",async f=>Ay(f,o.name,e)),u.onRequest("hydra-acp/child_session/spawn",async f=>{let g=f??{},w=typeof g.agentId=="string"?g.agentId:void 0,y=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.parentSessionId=="string"?g.parentSessionId:void 0,b=rt(g._meta??void 0),I=b.title,v=b.model,A=b.workspace;if(!y&&k){let W=e.manager.get(k);W&&(y=W.cwd)}if(!y)throw N(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let C=await sn(y),R=w??C.agentId??e.defaultAgent,T=await e.registry?.getAgent(R),_=an(C.configDefaults,T??{id:R})?.value,H=v??_?.model,J=typeof g.interactive=="boolean"?g.interactive:!1,M=await e.manager.create({agentId:R,cwd:y,parentSessionId:k,interactive:J,transformChain:[],title:I,model:H,configDefaults:_,...A!==void 0?{workspace:A}:{}});return{childSessionId:M.sessionId,...M.workspace!==void 0||M.workspaceError!==void 0?{_meta:{[ae]:{...M.workspace!==void 0?{workspaceInfo:M.workspace}:{},...M.workspaceError!==void 0?{workspaceError:M.workspaceError}:{}}}}:{}}}),u.onRequest("hydra-acp/session/fork",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"fork_session requires sessionId");let w=typeof g.forkAt=="string"?g.forkAt:void 0,y=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.agentId=="string"?g.agentId:void 0,b=typeof g.mode=="string"&&(g.mode==="verbatim"||g.mode==="synthesis")?g.mode:void 0,I=typeof g.model=="string"&&g.model.length>0?g.model:void 0,v=await e.manager.forkSession(g.sessionId,{...w!==void 0?{forkAt:w}:{},...y!==void 0?{cwd:y}:{},...k!==void 0?{agentId:k}:{},...b!==void 0?{mode:b}:{},...I!==void 0?{model:I}:{}}),A=e.manager.get(v.sessionId);if(!A){let T=await e.manager.loadFromDisk(v.sessionId);if(!T)throw N(E.InternalError,`fork ${v.sessionId} vanished before it could be attached`);A=await xt(e,{...T,onInstallProgress:Qs(u)})}Yt(l,A,A.sessionId);let C=gt(u,A,l),{entries:R}=await A.attach(C,"full");l.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:C.clientId,readonly:!1});for(let T of R){if(u.isClosed())break;await u.notify(T.method,Ue(Le(T.params,T.recordedAt),T.seq)).catch(()=>{})}return{...v,sessionId:A.sessionId}}),u.onRequest("session/fork",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"session/fork requires sessionId");let w=typeof g.cwd=="string"?g.cwd:void 0,y=await e.manager.forkSession(g.sessionId,{...w!==void 0?{cwd:w}:{},mode:"verbatim"}),k=e.manager.get(y.sessionId);if(!k){let v=await e.manager.loadFromDisk(y.sessionId);if(!v)throw N(E.InternalError,`fork ${y.sessionId} vanished before it could be attached`);k=await xt(e,{...v,onInstallProgress:Qs(u)})}Yt(l,k,k.sessionId);let b=gt(u,k,l),{entries:I}=await k.attach(b,"full");l.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:b.clientId,readonly:!1});for(let v of I){if(u.isClosed())break;await u.notify(v.method,Ue(Le(v.params,v.recordedAt),v.seq)).catch(()=>{})}return{sessionId:k.sessionId}});let h=async(f,g)=>{let w=f??{};if(typeof w.sessionId!="string")throw N(E.InvalidParams,`${g} requires sessionId`);let y=await e.manager.resolveCanonicalId(w.sessionId)??w.sessionId,k=e.manager.get(y);if(k)return await k.close({deleteRecord:!0,by:`session/delete ${l.clientId}`}),await e.manager.waitForDeletion(y),await e.manager.hasRecord(y)&&await e.manager.deleteRecord(y),{id:y,existed:!0};let b=await e.manager.deleteRecord(y);return{id:y,existed:b}};u.onRequest("session/delete",async f=>(await h(f,"session/delete"),{})),u.onRequest("session/close",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"session/close requires sessionId");p(g.sessionId,"session/close");let w=await e.manager.resolveCanonicalId(g.sessionId)??g.sessionId,y=e.manager.get(w);if(y)return await y.close({deleteRecord:!1,by:`session/close ${l.clientId}`+(l.processIdentity?` (${l.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(w))return{};throw N(E.SessionNotFound,`session ${w} not found`)}),u.onRequest("hydra-acp/session/delete",async f=>{let{id:g,existed:w}=await h(f,"hydra-acp/session/delete");if(!w)throw N(E.SessionNotFound,`session ${g} not found`);return{deleted:!0,sessionId:g}}),u.onRequest("hydra-acp/child_session/await",async f=>{let g=f??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0,y=g.until==="idle"?"idle":"turn_complete",k=typeof g.timeoutMs=="number"?Math.min(g.timeoutMs,18e5):3e5;if(!w)throw N(-32602,"await_child requires childSessionId");let b=xe(e.manager,w,`child session ${w} not found`);return new Promise(I=>{let C=[],R=[],T=0,_=!1,H,J,M=!1,W=()=>{M||(M=!0,clearTimeout(q),H?.(),J?.(),I(_?{entries:C,truncated:!0}:{entries:C}))};H=b.onBroadcast(te=>{let de=ky(te);for(C.push(te),R.push(de),T+=de;C.length>0&&(C.length>1e3||T>1048576);)C.shift(),T-=R.shift()??0,_=!0;y==="turn_complete"&&te.params?.update?.sessionUpdate==="turn_complete"&&W()});let q=setTimeout(W,k);typeof q.unref=="function"&&q.unref(),J=b.onClose(()=>W())})}),u.onRequest("hydra-acp/child_session/close",async f=>{let g=f??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0;if(!w)throw N(-32602,"close_child_session requires childSessionId");let y=e.manager.get(w);return y&&await y.close({deleteRecord:!1,by:`child_session/close ${l.clientId}`}),{ok:!0}}),u.onRequest("hydra-acp/attention/set",async f=>Cy(f,o.name,e)),u.onRequest("hydra-acp/attention/clear",async f=>Ry(f,o.name,e)),u.onRequest("hydra-acp/connection/keep_alive",async f=>{let g=f??{},w=typeof g.token=="string"?g.token:void 0,y=typeof g.sessionId=="string"?g.sessionId:void 0,k=typeof g.estimatedRemainingMs=="number"?g.estimatedRemainingMs:void 0;return w&&y&&e.manager.get(y)?.keepAliveClaim(w,k),{ok:!0}})}u.onRequest("hydra-acp/session/tool_content",async h=>{let f=h??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw N(E.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let g=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,w=await e.manager.loadToolBlob(g,f.hash);if(w===null)throw N(E.SessionNotFound,"tool content not found");return{content:w}}),u.onRequest("authenticate",async h=>vy(h,e)),u.onRequest("logout",async h=>by(h,e)),u.onRequest("session/new",async h=>{let f=zi.parse(h),g=rt(h?._meta),w=Array.isArray(g.transformers)&&g.transformers.every(Z=>typeof Z=="string")?g.transformers:e.manager.defaultTransformers??[],y=e.transformers?.resolveChain(w)??[],k=await sn(f.cwd),b=g.agentId??k.agentId??e.defaultAgent,I=await e.registry?.getAgent(b),v=an(k.configDefaults,I??{id:b})?.value,A,C,R=f.mcpServers;if(g.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){A=mu(32).toString("hex"),C=e.mcpTokenRegistry.reserve(A);let ke={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${A}`}]};R=[...f.mcpServers??[],ke]}let T,_,H=Kt(e);H!==void 0&&(R=[...R??[],...H.descriptors]);let J=No({baselineMcpServers:f.mcpServers,stdinEnabled:g.mcpStdin===!0,deps:e}),M;try{M=await e.manager.create({cwd:f.cwd,agentId:b,mcpServers:R,title:g.title,agentArgs:g.agentArgs,model:g.model??v?.model,configDefaults:v,onInstallProgress:Qs(u),transformChain:y,originatingClient:l.clientInfo,...g.interactive!==void 0?{interactive:g.interactive}:{},...g.env!==void 0?{forwardedEnv:g.env}:{},...g.workspace!==void 0?{workspace:g.workspace}:{},...J?{mintMcpServersForSwap:J}:{}})}catch(Z){throw C!==void 0&&C.abandon(Z instanceof Error?Z:void 0),_!==void 0&&_.abandon(Z instanceof Error?Z:void 0),H!==void 0&&H.abandon(Z instanceof Error?Z:void 0),Z}if(A!==void 0&&C!==void 0&&e.mcpTokenRegistry!==void 0){let Z=A,ke=e.mcpTokenRegistry;C.complete(M),M.onClose(()=>{ke.unbind(Z)})}if(T!==void 0&&_!==void 0&&e.mcpTokenRegistry!==void 0){let Z=T,ke=e.mcpTokenRegistry;_.complete(M),M.onClose(()=>{ke.unbind(Z)})}H!==void 0&&H.bindToSession(M),ku(M.sessionId,e);let W,q;try{Yt(l,M,M.sessionId),W=gt(u,M,l),{entries:q}=await M.attach(W,"full")}catch(Z){throw await M.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),Z}l.attached.set(M.sessionId,{sessionId:M.sessionId,clientId:W.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let Z of q){if(u.isClosed())break;await u.notify(Z.method,Ue(Le(Z.params,Z.recordedAt),Z.seq)).catch(()=>{})}})()});let te=Ys(M),de=Xs(M);return{sessionId:M.sessionId,...te?{modes:te}:{},...de?{models:de}:{},configOptions:M.buildConfigOptions(),_meta:Zs(e.manager,M,{clientId:W.clientId})}}),u.onRequest("session/attach",async h=>{let f=Vi.parse(h),g=f.clientInfo?.version;g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g));let w=rt(f._meta),y=w.resume,k=w.readonly===!0,b=w.env;s.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!y} readonly=${k}`);let I=y?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,v=e.manager.get(I);if(!v&&k){let M=await e.manager.loadFromDisk(I);if(!M)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);let W=await e.manager.loadHistory(I,{...w.historyLimit!==void 0?{maxEntries:w.historyLimit}:{}}),q=f.clientId??`cli_${Go(8)}`;l.attached.set(M.hydraSessionId,{sessionId:M.hydraSessionId,clientId:q,readonly:!0}),s.log.info(`session/attach OK (viewer) sessionId=${M.hydraSessionId} clientId=${q} attachedCount=${l.attached.size} replayed=${W.length}`);for(let te of W)await u.notify(te.method,Ue(Le(te.params,te.recordedAt),te.seq)).catch(()=>{});return{sessionId:M.hydraSessionId,clientId:q,connectedClients:[q],historyPolicy:"full",replayed:W.length,_meta:xy(M)}}let A=!v;if(!v){let M=await e.manager.loadFromDisk(I),W=await Sy(I,y,M?.upstreamSessionId,e.manager);W.kind==="ignore"&&s.log.warn(W.logMessage);let q=M;if(y&&W.kind==="honor"&&(q={...M,hydraSessionId:f.sessionId,upstreamSessionId:y.upstreamSessionId,agentId:y.agentId,cwd:M?.workspace?.path??y.cwd,...y.title!==void 0?{title:y.title}:{},...y.agentArgs!==void 0?{agentArgs:y.agentArgs}:{}}),!q)throw N(E.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(q.agentId,q.upstreamSessionId))throw N(E.SessionNotFound,`session ${f.sessionId} was deleted`);let te=q.originatingClient?q:{...q,originatingClient:l.clientInfo},de=b!==void 0?{...te,forwardedEnv:b}:te;v=await xt(e,{...de,onInstallProgress:Qs(u)})}Yt(l,v,v.sessionId);let C=gt(u,v,l,f.clientInfo,f.clientId),R=w.replayMode==="drip",{entries:T,appliedPolicy:_}=await v.attach(C,f.historyPolicy,{afterMessageId:f.afterMessageId,afterSeq:f.afterSeq,raw:R,...w.historyLimit!==void 0?{historyLimit:w.historyLimit}:{},...w.toolContent!==void 0?{toolContent:w.toolContent}:{}});if(l.attached.set(v.sessionId,{sessionId:v.sessionId,clientId:C.clientId,readonly:k}),b!==void 0&&await e.manager.setForwardedEnv(v.sessionId,b).catch(()=>{}),s.log.info(`session/attach OK sessionId=${v.sessionId} clientId=${C.clientId} attachedCount=${l.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${_} replayed=${T.length} readonly=${k}${R?" replayMode=drip":""}`),R){let M=w.dripSpeed&&w.dripSpeed>0?w.dripSpeed:1,W=750;(async()=>{let q=null;for(let te of T){let de=typeof te.recordedAt=="number"?te.recordedAt:null;if(q!==null&&de!==null){let Z=Math.min(W,Math.max(0,(de-q)/M));Z>0&&await new Promise(ke=>setTimeout(ke,Z))}de!==null&&(q=de);try{await u.notify(te.method,Ue(Le(te.params,de??void 0),te.seq))}catch{return}}})()}else for(let M=0;M<T.length&&!u.isClosed();M++){let W=T[M],q=u.notify(W.method,Ue(Le(W.params,W.recordedAt),W.seq)).catch(()=>{});(M+1)%200===0&&await q}v.replayPendingPermissions(C);let H=Ys(v),J=Xs(v);return{sessionId:v.sessionId,clientId:C.clientId,connectedClients:v.connectedClients(C.clientId),historyPolicy:_,replayed:T.length,...H?{modes:H}:{},...J?{models:J}:{},configOptions:v.buildConfigOptions(),_meta:Zs(e.manager,v,{resurrected:A})}}),u.onRequest("session/detach",async h=>{let f=Gi.parse(h),g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"client not attached to that session");let w=e.manager.get(f.sessionId);return w?.detach(g.clientId),l.attached.delete(f.sessionId),w&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[ae]:{detachStatus:"detached"}}}}),u.onRequest("session/list",async h=>{let f=Ki.parse(h??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(k=>k.originatingClient?.name!==hs).map(Qi)}}),u.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw N(E.InternalError,"agent registry unavailable");return Ot(e.registry)}),u.onRequest("hydra-acp/agents/auth_methods",async h=>{let f=h??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw N(E.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),u.onRequest("session/prompt",async h=>{let f=Yi.parse(h);p(f.sessionId,"session/prompt");let g=await lu(f,e.manager,b=>{s.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${b} sessionId=${f.sessionId}`)});if(g?.fromSession!==void 0){if((g.depth??0)>3)throw s.log.warn(`session/prompt: refusing depth ${g.depth} chain from ${g.fromSession} to ${f.sessionId}`),N(E.InvalidRequest,`message chain too deep (${g.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(g.awaiting===!0&&pu(g.fromSession,f.sessionId))throw s.log.warn(`session/prompt: refusing deadlock ${g.fromSession} -> ${f.sessionId}`),N(E.InvalidRequest,`would deadlock: ${f.sessionId} is already blocked waiting on ${g.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let w=l.attached.get(f.sessionId);if(!w)throw s.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...l.attached.keys()].join(",")}]`),N(E.SessionNotFound,"not attached to session");let y=e.manager.get(f.sessionId);if(!y){let b=await e.manager.loadFromDisk(f.sessionId);if(!b)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);s.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),y=await xt(e,b);let I=gt(u,y,l,void 0,w.clientId);await y.attach(I,"none")}let k=g?.awaiting===!0&&g.fromSession!==void 0?fu(g.fromSession,f.sessionId):void 0;try{return await y.prompt(w.clientId,f,g)}finally{k?.()}});let m=h=>{let f;try{f=Gn.parse(h)}catch(y){s.log.warn(`session/cancel: invalid params: ${y.message}`);return}let g=l.attached.get(f.sessionId);if(!g)return;if(g.readonly){s.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let w=e.manager.get(f.sessionId);w&&w.cancel(g.clientId).catch(y=>{s.log.warn(`session/cancel for ${f.sessionId}: ${y.message}`)})};u.onNotification("session/cancel",m),u.onRequest("session/cancel",async h=>{let f=Gn.parse(h);return p(f.sessionId,"session/cancel"),m(h),null}),u.onRequest("hydra-acp/prompt/cancel",async h=>{let f=Zi.parse(h);return p(f.sessionId,"hydra-acp/prompt/cancel"),xe(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),u.onRequest("hydra-acp/session/force_cancel",async h=>{let f=Gn.parse(h);return p(f.sessionId,"hydra-acp/session/force_cancel"),xe(e.manager,f.sessionId).forceCancel()}),u.onRequest("hydra-acp/prompt/update",async h=>{let f=ea.parse(h);return p(f.sessionId,"hydra-acp/prompt/update"),xe(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),u.onRequest("hydra-acp/prompt/amend",async h=>{let f=ta.parse(h);p(f.sessionId,"hydra-acp/prompt/amend");let g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"not attached to session");return xe(e.manager,f.sessionId).amendPrompt(g.clientId,f)}),u.onRequest("_session/steering",async h=>{let f=na.parse(h);p(f.sessionId,"_session/steering");let g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"not attached to session");let w=e.manager.get(f.sessionId);if(!w){let y=await e.manager.loadFromDisk(f.sessionId);if(!y)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);w=await xt(e,y);let k=gt(u,w,l,void 0,g.clientId);await w.attach(k,"none")}return w.steer(g.clientId,f)}),u.onRequest("session/resume",async h=>{let f=h??{},g=typeof f.sessionId=="string"?f.sessionId:void 0;if(!g)throw N(E.InvalidParams,"session/resume requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,y=e.manager.get(w);if(!y){let v=await e.manager.loadFromDisk(w);if(!v)throw N(E.SessionNotFound,`session ${g} not found in memory or on disk`);y=await xt(e,v)}Yt(l,y,y.sessionId);let k=gt(u,y,l);await y.attach(k,"pending_only"),l.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:k.clientId,readonly:!1}),y.replayPendingPermissions(k);let b=Ys(y),I=Xs(y);return{sessionId:y.sessionId,...b?{modes:b}:{},...I?{models:I}:{},configOptions:y.buildConfigOptions(),_meta:Zs(e.manager,y,{clientId:k.clientId})}}),u.onRequest("session/load",async h=>{let f=h??{},g=typeof f.sessionId=="string"?f.sessionId:void 0;if(!g)throw N(E.InvalidParams,"session/load requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,y=e.manager.get(w);if(!y){let A=await e.manager.loadFromDisk(w);if(!A)throw N(E.SessionNotFound,`session ${g} not found in memory or on disk`);y=await xt(e,A)}Yt(l,y,y.sessionId);let k=gt(u,y,l),{entries:b}=await y.attach(k,"full");l.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:k.clientId,readonly:!1});for(let A of b){if(u.isClosed())break;await u.notify(A.method,Ue(Le(A.params,A.recordedAt),A.seq)).catch(()=>{})}y.replayPendingPermissions(k);let I=Ys(y),v=Xs(y);return{sessionId:y.sessionId,...I?{modes:I}:{},...v?{models:v}:{},configOptions:y.buildConfigOptions(),_meta:Zs(e.manager,y,{clientId:k.clientId})}}),u.onRequest("session/set_model",async h=>{let f=h?.sessionId;typeof f=="string"&&p(f,"session/set_model");let g=Iy(h,e.manager);if(g.kind==="error")throw s.log.warn(g.logMessage),N(g.code,g.message);if(g.kind==="no_op")return s.log.warn(g.logMessage),await u.notify("session/update",{sessionId:g.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:g.currentModel}}).catch(()=>{}),null;s.log.info(g.logMessage);let{modelId:w}=g,y=await g.session.forwardModelChange(w,h);return g.session.applyAgentConfigOptionResponse(y,"model"),g.session.applyModelChange(w),y}),u.onRequest("session/set_mode",async h=>{let f=h,g=f?.sessionId;if(typeof g=="string"&&p(g,"session/set_mode"),!f||typeof f.sessionId!="string")throw N(E.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw N(E.InvalidParams,"session/set_mode requires string modeId");let w=xe(e.manager,f.sessionId),y=await w.forwardRequest("session/set_mode",h);return w.applyModeChange(f.modeId),y}),u.onRequest("session/set_config_option",async h=>{let f=h,g=b=>N(E.InvalidParams,b),w=f?.sessionId;if(typeof w=="string"&&p(w,"session/set_config_option"),!f||typeof f.sessionId!="string")throw g("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw g("session/set_config_option requires string configId");if(typeof f.value!="string")throw g("session/set_config_option requires string value");let y=xe(e.manager,f.sessionId),k=y.buildConfigOptions().find(b=>b.id===f.configId);if(!k)throw g(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!k.options.some(b=>b.value===f.value))throw g(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{if(f.value!==y.currentModel){let b=await y.forwardModelChange(f.value);y.applyAgentConfigOptionResponse(b,"model")}y.applyModelChange(f.value);break}case"mode":{f.value!==y.currentMode&&await y.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),y.applyModeChange(f.value);break}case"agent":{f.value!==y.agentId&&await y.setAgent(f.value);break}default:{let b=await y.forwardRequest("session/set_config_option",{sessionId:f.sessionId,configId:f.configId,value:f.value});y.applyAgentConfigOptionResponse(b,f.configId)&&y.broadcastConfigOptions()}}return{configOptions:y.buildConfigOptions()}}),u.setDefaultHandler(async(h,f)=>{let g=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),w=f.startsWith("session/"),y=f.startsWith("hydra-acp/");if(!w&&!y||h===null||typeof h!="object"||g.has(f))throw N(E.MethodNotFound,`Method not found: ${f}`);let k=h.sessionId;if(typeof k!="string")throw N(E.MethodNotFound,`Method not found: ${f}`);return p(k,f),xe(e.manager,k).forwardRequest(f,h)})})}async function vy(s,e){let t=s??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw N(E.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 m=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(m)}let d=a.authMethods??[],c=d.find(m=>m.id===n);if(!c){let m=d.map(h=>h.id);throw N(E.InvalidParams,`authenticate: methodId ${JSON.stringify(n)} is not advertised by agent ${a.agentId}; valid: [${m.map(h=>JSON.stringify(h)).join(", ")}]`)}let u=c._meta?.type,l=(()=>{let m=c._meta?.["terminal-auth"];if(m&&typeof m=="object"&&!Array.isArray(m))return m})();if((c.type??(u==="agent"||u==="terminal"?u:l!==void 0?"terminal":"agent"))==="terminal"){let m=(k,b)=>{if(!Array.isArray(k))throw N(E.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw N(E.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},h=await e.manager.planSpawnForAgent(a.agentId),f,g;if(l?.args!==void 0){let k=typeof l.command=="string"?l.command:void 0;f=k!==void 0&&yu.isAbsolute(k)?k:h.command,g=m(l.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,b=k!==void 0?m(k.raw,k.label):[];f=h.command,g=[...h.args,...b]}let w={};for(let[k,b]of Object.entries(process.env))typeof b=="string"&&(w[k]=b);Object.assign(w,h.env);let y=hu.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${n}`),{kind:"terminal",command:f,args:g,env:w,cwd:y}}try{return await a.connection.request("authenticate",{methodId:n})}catch(m){throw lt(m,a)}}async function by(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 Qs(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(sa,t).catch(()=>{})}}function Ys(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 Xs(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}}async function Sy(s,e,t,n){return e?await n.isRetiredGeneration(s,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${s} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function Iy(s,e){if(!s||typeof s!="object")return{kind:"error",code:E.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:E.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:E.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:E.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=n.availableModels(),o=Ht(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:E.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 Ay(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0;if(!r)throw N(E.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw N(E.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw N(E.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return xe(t.manager,r).addTransformer(o),{ok:!0}}async function Cy(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 N(E.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw N(E.InvalidParams,"hydra-acp/attention/set requires string reason");return xe(t.manager,r).setAttentionFlag(e,o,n.payload),{ok:!0}}async function Ry(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 N(E.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw N(E.InvalidParams,"hydra-acp/attention/clear requires string reason");return xe(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function xy(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:Sn(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,armedTaskList:[]};return{[ae]:Vn(e,t)}}function Zs(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(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return dn(e.agentMeta,Vn(n,r))}function Ey(){return{protocolVersion:1,agentInfo:{name:"hydra",version:le},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:{...dn(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}}}),steering:{supported:!0}}}}function Ty(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 ku(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 gt(s,e,t,n,r){return{clientId:r??`cli_${Go(8)}`,connection:s,clientInfo:n}}function Yt(s,e,t){let n=s.attached.get(t);n&&(e.detach(n.clientId),s.attached.delete(t))}var er=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 Py}from"crypto";import{McpServer as My}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as _y}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as me}from"zod";function Ko(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 Se(s){return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}var vu="Bearer ";function Xt(s){let e=s.headers.authorization;if(typeof e!="string"||!e.startsWith(vu))return;let t=e.slice(vu.length).trim();return t.length>0?t:void 0}function $y(s){let e=new My({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:me.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let n=s.streamTail(t);return Se(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:me.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let n=s.streamHead(t);return Se(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:me.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:me.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:me.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 Se(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:me.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:me.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 Se({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:me.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:me.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:me.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:me.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:me.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:me.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:me.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:me.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:me.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 Se(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 Se(t)}),e}var Oy=1e4;function bu(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=$y(a),u=new _y({sessionIdGenerator:()=>Py()});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=Xt(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 p,m=new Promise(f=>{p=setTimeout(()=>f(void 0),Oy)}),h=await Promise.race([c.sessionReady.catch(()=>{}),m]);if(p!==void 0&&clearTimeout(p),h===void 0){a.code(503).send({error:"session not ready"});return}u=h}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 Fy}from"crypto";import{McpServer as Ny}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Dy}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ge}from"zod";function jy(s){switch(s){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var Su=2e3,Iu=2e4;function Hy(s,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return Ut([s]);let n=[],r=un(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=Xn(t);return i!==void 0&&n.push(i),n.join(`
199
- `)}function Ly(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 Uy(s){let e=new Ny({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:Ge.string().min(1).describe("Case-insensitive substring to search for."),limit:Ge.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ge.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 Se({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=Ko(u);if(!l)continue;let{kind:p,update:m}=l;if((p==="tool_call"||p==="tool_call_update")&&!r)continue;let h=Hy(u,p,m),f=h.toLowerCase().indexOf(a);if(f<0)continue;let g=jy(p),w=Ly(h,f),y=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:w,timestamp:y}),i.length>=n)break}i.sort((c,u)=>c.entryId-u.entryId);let d=i.length>=n;return Se({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:Ge.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ge.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 Se({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 Se({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=Ut(u,{toolOutput:{maxPerCall:Su,maxTotal:Iu}});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:Ge.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:Ge.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:Ge.string().optional(),limit:Ge.number().int().min(1).max(100).optional(),include_output:Ge.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 Se({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,p=Math.max(o*4,200);for await(let{entryId:y,entry:k}of a.iterRecallNewestFirst()){let b=Ko(k);if(!b)continue;let{kind:I,update:v}=b;if(I!=="tool_call"&&I!=="tool_call_update")continue;let A=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:`__noid_${y}`,C=l.get(A);if(C||(C={entryId:y,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},l.set(A,C)),y<C.entryId&&(C.entryId=y),!C.nameAuthoritative){let T=un(v);T!==void 0?(C.toolName=T,C.nameAuthoritative=!0):typeof v.name=="string"&&v.name.length>0?(C.toolName=v.name,C.nameAuthoritative=!0):I==="tool_call"&&typeof v.title=="string"&&v.title.length>0&&(C.toolName=v.title,C.nameAuthoritative=!0)}if(C.kind===void 0&&typeof v.kind=="string"&&v.kind.length>0&&(C.kind=v.kind),C.output===void 0){let T=Xn(v);T!==void 0&&(C.output=T)}let R=v.rawInput;if(R&&typeof R=="object"&&!Array.isArray(R)&&Object.keys(R).length>0)for(let[T,_]of Object.entries(R))C.rawInput[T]===void 0&&(C.rawInput[T]=_);if(Array.isArray(v.locations))for(let T of v.locations){let _=T?.path;typeof _=="string"&&_.length>0&&!C.locations.includes(_)&&C.locations.push(_)}if(typeof v.status=="string"&&C.status==="in_progress"&&(C.status=v.status),k.recordedAt!==void 0&&C.timestamp===void 0&&(C.timestamp=String(k.recordedAt)),l.size>=p)break}let m=[...l.keys()].sort((y,k)=>l.get(y).entryId-l.get(k).entryId),h=[],f=Iu,g=!1;for(let y of m){let k=l.get(y);if(k.toolName=Fr({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==n.toLowerCase())continue;if(u){let v=r.toLowerCase(),A=["file_path","filePath","path"],C=!1;for(let R of A){let T=k.rawInput[R];if(typeof T=="string"&&T.toLowerCase().includes(v)){C=!0;break}}if(!C){for(let R of k.locations)if(R.toLowerCase().includes(v)){C=!0;break}}if(!C)continue}let b={};for(let[v,A]of Object.entries(k.rawInput))typeof A=="string"?b[v]=A.length>500?A.slice(0,497)+"\u2026":A:(typeof A=="number"||typeof A=="boolean")&&(b[v]=A);k.locations.length>0&&b.locations===void 0&&(b.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:b,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let v=k.output,A=Math.min(Su,f);if(A<=0)g=!0;else{let C=v.length<=A?v:v.slice(0,A-1)+"\u2026";I.output=C,I.outputBytes=v.length,I.outputTruncated=C.length<v.length,f-=C.length}}if(h.push(I),h.length>=o)break}let w=h.length>=o;return Se({calls:h,truncated:w,...g?{outputBudgetExhausted:g}:{}})}),e}var By=1e4;function Au(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=Uy(a),u=new Dy({sessionIdGenerator:()=>Fy()});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=Xt(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 p,m=new Promise(f=>{p=setTimeout(()=>f(void 0),By)}),h=await Promise.race([c.sessionReady.catch(()=>{}),m]);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 tr=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 Qy}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Yy}from"crypto";import{Server as Wy}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as qy,ListToolsRequestSchema as zy}from"@modelcontextprotocol/sdk/types.js";function Cu(s,e,t,n){let r=typeof t=="function"?async()=>t():async()=>t,o=new Wy({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(zy,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(qy,async(a,d)=>{let c=a.params.name,u=d._meta?.progressToken??d.requestId,l=Vy(u,d.sendNotification);try{let p=await r(),m=await Gy(e.connection,s,c,a.params.arguments??{},p);return Ky(m,c)}catch(p){return Qo(p instanceof Error?p.message:String(p))}finally{l()}}),o}var Jy=15e3;function Vy(s,e,t=Jy){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 Gy(s,e,t,n,r){return await s.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:n,sessionId:r})}function Ky(s,e){if(s===null||typeof s!="object")return Qo(`extension ${e} returned non-object`);let t=s;return Array.isArray(t.content)?t:Qo(`extension ${e} omitted content array`)}function Qo(s){return{content:[{type:"text",text:s}],isError:!0}}var Xy=1e4;function Ru(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 p=l.get(u);p!==void 0&&(l.delete(u),r(p))}}async function i(u,l){for(let[p,m]of n){if(e.lookup(p)?.session?.sessionId!==u)continue;let f=m.get(l);if(f!==void 0)try{await f.server.sendToolListChanged()}catch{}}}t.onChange(u=>{o(u)});async function a(u,l){let p=n.get(u);p===void 0&&(p=new Map,n.set(u,p),e.addDisposer(u,async()=>{let b=n.get(u);if(b!==void 0){n.delete(u);for(let I of b.values())await r(I)}}));let m=p.get(l);if(m!==void 0)return m.transport;let h=t.lookup(l);if(h===void 0)return;let y=Cu(l,h,async()=>{let b=e.lookup(u);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let I,v=new Promise(C=>{I=setTimeout(()=>C(void 0),Xy)}),A=await Promise.race([b.sessionReady.catch(()=>{}),v]);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 b=>{let I=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!I||typeof I!="object")return;let v=I.tools;if(!Array.isArray(v))return;let A=[];for(let C of v){if(!C||typeof C!="object")continue;let R=C;if(typeof R.name!="string"||R.name.length===0||typeof R.description!="string"||R.inputSchema===null||typeof R.inputSchema!="object")continue;let T={name:R.name,description:R.description,inputSchema:R.inputSchema};R.outputSchema!==null&&typeof R.outputSchema=="object"&&(T.outputSchema=R.outputSchema),A.push(T)}return A}}),k=new Qy({sessionIdGenerator:()=>Yy()});return await y.connect(k),p.set(l,{server:y,transport:k}),k}async function d(u,l){let p=Xt(u);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=u.params.name,f=await a(p,h);if(f===void 0){l.code(404).send({error:`unknown mcp server: ${h}`});return}l.hijack(),await f.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 _u(s,e){ow(s),gr(s.daemon.scrubEnv);let t=s,n=s.daemon.tls?await Ke.readFile(ce(s.daemon.tls.key)):void 0,r=s.daemon.tls?await Ke.readFile(ce(s.daemon.tls.cert)):void 0;await Ke.mkdir(x.home(),{recursive:!0});let{stream:o,fileStream:i}=await sw(s.daemon.logLevel),a=Zy({logger:{level:s.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(ew,{options:{handleProtocols:yi}}),vr(F=>{a.log.info(F)}),Ir(F=>{a.log.info(F)});let d=await Ms.load(),c=await zs.load();qo(),Bo(c);let u=new Ks(c);u.start();let l=new Us(c);l.start();let p=new Ns,m=new Fs,h=new _s(e),f=new Os([h,new $s(d),m]),g=sc({validator:f});a.addHook("onRequest",async(F,ve)=>{F.routeOptions.config?.skipAuth||F.url==="/acp"||F.url?.startsWith("/acp?")||(await g(F,ve),!ve.sent&&F.authIdentity?.startsWith("script:")&&!oc(F.method,F.routeOptions.url)&&ve.code(403).send({error:"script tokens may only access read-only session data"}))});let w=setInterval(()=>{d.sweepExpired()},300*1e3);w.unref();let y=setInterval(()=>{p.sweepExpired()},300*1e3);y.unref();let k=new zn(s,{onFetched:()=>{Wd(k,A)},onStaleFallback:(F,ve)=>{let en=Math.round(ve/36e5),tn=en>=48?`${Math.round(en/24)}d`:`${en}h`;a.log.warn(`registry fetch failed (${F.message}); serving stale cache last synced ${tn} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});To(F=>a.log.info(F));let b={info:F=>a.log.info(F),warn:F=>a.log.warn(F)},I=F=>it.spawn({...F,stderrTailBytes:s.daemon.agentStderrTailBytes,logger:b});Ii(s.compressToolContent);let v=new Ts,A=new bs(k,I,void 0,{idleTimeoutMs:s.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:s.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:s.sessionDefaults,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:b,npmRegistry:s.npmRegistry,extensionCommands:v,defaultCwd:s.defaultCwd,disableWorkspaceSnapshots:s.disableWorkspaceSnapshots}),C=new Gs(c,void 0,{resolvesLocally:async F=>await A.resolveCanonicalId(F)!==void 0,cache:l}),R=new xs(fi(s),void 0,{tokenRegistry:m}),T=new Es(pi(s),void 0,{tokenRegistry:m}),_=[];jc(a,le,Jd(s),()=>_);let H=new er,J=new tr,M,W=()=>{if(M!==void 0)return M;let F=a.server.address();return M=`http://127.0.0.1:${F&&typeof F=="object"?F.port:s.daemon.port}`,M},q={agentId:s.defaultAgent,cwd:s.defaultCwd,publicHost:s.daemon.publicHost,host:s.daemon.host,port:s.daemon.port,compaction:s.compaction};Nc(a,A,q,{extensionMcp:J,mcpTokenRegistry:H,getDaemonOrigin:W},c,l),Mc(a,{store:c,localMiss:{resolvesLocally:async F=>await A.resolveCanonicalId(F)!==void 0,cache:l}}),Dc(a,k,A,{npmRegistry:s.npmRegistry}),Hc(a,R),Lc(a,T),Uc(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]})),Jc(a,{store:d,rateLimiter:p,staticTokenValidator:h}),ou(a,{store:c,health:u}),uu(a,{processRegistry:m}),bu(a,H),Au(a,H);let te=Ru(a,H,J);wu(a,{validator:f,manager:A,defaultAgent:s.defaultAgent,processRegistry:m,onExtensionVersion:(F,ve)=>R.reportVersion(F,ve),onTransformerVersion:(F,ve)=>T.reportVersion(F,ve),transformers:T,extensionCommands:v,mcpTokenRegistry:H,extensionMcp:J,extensionMcpControls:te,getDaemonOrigin:W,registry:k,foreignSessions:C});let de=!!s.daemon.tls;await a.listen({host:de?"127.0.0.1":s.daemon.host,port:de?0:s.daemon.port});let Z=a.server.address(),ke=Z&&typeof Z=="object"?Z.port:s.daemon.port,Hn,$u=s.daemon.host,Yo=ke;if(de&&n&&r){Hn=rw({listenHost:s.daemon.host,listenPort:s.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:ke,tlsOptions:{key:n,cert:r},logger:a.log});let F=Hn.address();F&&typeof F=="object"&&(Yo=F.port)}await Ke.mkdir(x.home(),{recursive:!0}),await Bd({pid:process.pid,host:$u,port:Yo,loopbackPort:ke,startedAt:new Date().toISOString()});let Xo={daemonUrl:`http://127.0.0.1:${ke}`,daemonHost:"127.0.0.1",daemonPort:ke,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${ke}/acp`,hydraHome:x.home()};R.setContext(Xo),T.setContext(Xo),await R.start(),await T.start();try{await A.reconcilePermissionFlags()}catch(F){a.log.warn(`permission flag reconcile failed: ${F.message}`)}try{await A.seedSessionIndex()}catch(F){a.log.warn(`session index seed failed: ${F.message}`)}A.resurrectPendingQueues().catch(F=>{a.log.warn(`queue replay scan failed: ${F.message}`)}),A.resumePendingCompactions().catch(F=>{a.log.warn(`compaction resume scan failed: ${F.message}`)}),A.resumePendingAgentSwaps().catch(F=>{a.log.warn(`agent-swap resume scan failed: ${F.message}`)});let Zo=s.daemon.agentSyncIntervalMinutes*60*1e3,ei=Zo>0?qd({registry:k,manager:A,intervalMs:Zo,logger:b}):void 0,ti=s.daemon.sessionGcIntervalMinutes*60*1e3,Ou=s.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ni=ti>0?zd({manager:A,intervalMs:ti,maxAgeMs:Ou,logger:b}):void 0,Fu=Qd({bootConfig:s,apply:F=>{t=F,k.setConfig(F),A.setLiveConfig({sessionDefaults:F.sessionDefaults}),q.agentId=F.defaultAgent,q.cwd=F.defaultCwd,gr(F.daemon.scrubEnv)},onDrift:F=>{_=F},logger:b});return{app:a,manager:A,registry:k,extensions:R,transformers:T,mcpTokenRegistry:H,extensionMcp:J,processRegistry:m,shutdown:async()=>{u.stop(),l.stop(),Fu(),ni&&ni(),ei&&ei(),clearInterval(w),clearInterval(y);let F=async(ve,en)=>{try{await en()}catch(tn){a.log.warn(`shutdown step ${ve} failed: ${tn instanceof Error?tn.message:String(tn)}`)}};await F("sessionTokenStore.flush",()=>d.flush()),await F("extensions.stop",()=>R.stop()),await F("transformers.stop",()=>T.stop()),await F("manager.closeAll",()=>A.closeAll()),await F("manager.flushSynopsis",()=>A.flushSynopsis(3e4)),await F("manager.shutdownSynopsis",()=>A.shutdownSynopsis()),await F("manager.flushMetaWrites",()=>A.flushMetaWrites()),await F("manager.flushHistoryWrites",()=>A.flushHistoryWrites()),vr(null),Ir(null),To(null),Hn&&await F("tlsTerminator.close",()=>new Promise(ve=>Hn.close(()=>ve()))),await F("app.close",()=>a.close());try{Tu.unlinkSync(x.pidFile())}catch{}await F("fileStream.flushSync",()=>i.flushSync())}}}var Eu=20;async function nw(s,e){let t=Zt.dirname(s),n=Zt.basename(s,".log"),r=new RegExp(`^${n}\\.(\\d+)\\.log$`),o;try{o=await Ke.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=>Ke.unlink(Zt.join(t,d.name))))}async function sw(s){await nw(x.logFile(),Eu);let e=await tw({file:x.logFile(),size:"10m",mkdir:!0,symlink:As,limit:{count:Eu,removeOtherLogFiles:!0}}),t=xu.destination(2);return{stream:xu.multistream([{stream:e,level:s},{stream:t,level:s}]),fileStream:e}}function rw(s){let e=Mu.createServer(s.tlsOptions,t=>{let n=Pu.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 ow(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 iw(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:s}=await Promise.resolve().then(()=>(Nn(),ru));s();let e=await rn(),t=await oi(),n=await _u(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
198
+ `)}}catch(C){if(C.code==="ENOENT")return p.raw.end(),p;throw C}return p.raw.end(),p}),s.post("/v1/sessions/:id/prompt/:messageId/notify",async(l,p)=>{let m=l.params,h=m.id,f=await e.resolveCanonicalId(h)??h,g=m.messageId,w=l.body,y=typeof w?.callbackUrl=="string"?w.callbackUrl:"",k=typeof w?.secret=="string"?w.secret:"";if(!g||!y||!k){p.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let b;try{b=new URL(y)}catch{p.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(b.protocol!=="https:"&&b.protocol!=="http:"){p.code(400).send({error:"callbackUrl must be http or https"});return}let I=e.get(f);if(!I){p.code(404).send({error:"session not found or not warm"});return}let v=I.registerTurnNotify(g,y,k);if(v.alreadyTerminal){p.code(200).send({status:"already_terminal",stopReason:v.stopReason});return}p.code(202).send({status:"registered"})}),s.get("/v1/sessions/:id/attention",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,f=e.get(h);return!f&&!await e.hasRecord(h)?(p.code(404).send({error:"session not found"}),p):f?{flags:f.listAttentionFlags()}:{flags:(await e.store.read(h))?.attentionFlags??[]}}),s.get("/v1/sessions/attention",async(l,p)=>{let m=l.query;if(!m.source||m.source.trim().length===0)return p.code(400).send({error:"source query parameter is required"}),p;let h=await e.list({includeNonInteractive:!0}),f=[];for(let g of h){let w=e.get(g.sessionId),y;w?y=w.listAttentionFlags():y=(await e.store.read(g.sessionId))?.attentionFlags??[];for(let k of y)k.source===m.source&&f.push({...k,sessionId:g.sessionId})}return{flags:f}}),s.post("/v1/sessions/:id/attention/clear",async(l,p)=>{let m=l.params.id,h=await e.resolveCanonicalId(m)??m,g=l.body??{},w=typeof g.source=="string"?g.source:"",y=typeof g.reason=="string"?g.reason:"";if((w.length>0||y.length>0)&&!(w.length>0&&y.length>0)){p.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}w.length===0&&y.length;let k=e.get(h);if(k){if(w.length>0&&y.length>0)k.clearAttentionFlag(w,y);else{let C=Array.from(k.listAttentionFlags()).map(R=>`${R.source}::${R.reason}`);for(let R of C)k.clearAttentionFlag(R.split("::")[0],R.split("::").slice(1).join("::"))}p.code(204).send();return}if(!await e.hasRecord(h)){p.code(404).send({error:"session not found"});return}let b=e.store,I=await b.read(h);if(!I){p.code(404).send({error:"session not found"});return}let v=I.attentionFlags??[],A;if(w.length>0&&y.length>0){let C=`${w}::${y}`;A=v.filter(R=>`${R.source}::${R.reason}`!==C)}else A=[];if(A.length===v.length&&A.every((C,R)=>C.source===v[R].source&&C.reason===v[R].reason)){p.code(204).send();return}await b.write({...I,attentionFlags:A}),p.code(204).send()})}function Dc(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 Te(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===E.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}G();function jc(s,e,t,n=()=>[]){s.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:x.home(),driftedKeys:n()}))}var $h=/^[A-Za-z0-9._-]+$/;function qs(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=Oh(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){On(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){On(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){On(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){On(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){On(i,d)}})}function On(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 Oh(s){let e=s.name;if(typeof e!="string"||!$h.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 Hc(s,e){qs(s,"extension",e)}function Lc(s,e){qs(s,"transformer",e)}function Uc(s,e){s.get("/v1/config",async()=>e())}import{z as ft}from"zod";G();import*as Qt from"fs/promises";import*as Bc from"path";import{randomBytes as mA,scrypt as Fh,timingSafeEqual as Nh}from"crypto";import{promisify as Dh}from"util";var jh=Dh(Fh);function Wc(){return Bc.join(x.home(),"password-hash")}var Hh=128*1024*1024;async function qc(){try{return(await Qt.readFile(Wc(),"utf8")).trim().length>0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function zc(s){if(typeof s!="string"||s.length===0)return!1;let e;try{e=(await Qt.readFile(Wc(),"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 jh(s,i,a.length,{N:n,r,p:o,maxmem:Hh});return d.length!==a.length?!1:Nh(d,a)}var Lh=ft.object({password:ft.string().min(1),label:ft.string().min(1).max(256).optional(),ttlSec:ft.number().int().positive().optional()}),Uh=ft.object({id:ft.string().optional()}).optional(),Bh=ft.object({token:ft.string().min(32)});function Jc(s,e){s.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,n)=>{let r=Wh(t);if(e.rateLimiter.isBlocked(r))return n.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=Lh.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}if(!await qc())return n.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await zc(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=Uh.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",async(t,n)=>{let r=await e.store.revokeAll();return n.code(200).send({revoked:r})}),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"})}),s.post("/v1/auth/rotate-token",async(t,n)=>{if(t.authIdentity!=="service")return n.code(403).send({error:"Requires the service token"});let r;try{r=Bh.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(r.token),n.code(200).send({rotated:!0})})}function Wh(s){return s.ip||"unknown"}import{z as pt}from"zod";G();Ne();var Ho=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,zs=class s{data;constructor(e){this.data=e}static async load(){let e=await ie(x.peers());return new s(qh(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await Vc(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await Vc(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:n,expiresAt:r,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:n,expiresAt:r,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function qh(s){if(!s||typeof s!="object")return{version:1,entries:{}};let e=s,t=e.entries&&typeof e.entries=="object"?e.entries:{},n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),n[r]=a}return{version:1,entries:n}}async function Vc(s){await pe(x.peers(),s,{mode:384})}var zh=3600*24*365,Ge=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function Gc(s,e){return`${Re(s)?"http":"https"}://${s}:${e}`}async function Kc(s){let e=s.fetchImpl??fetch,t=`${s.host}:${s.port}`,n=Gc(s.host,s.port),r;try{r=await e(`${n}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s.password,label:s.label,ttlSec:s.ttlSec??zh})})}catch(i){throw new Ge(`Could not reach ${t}: ${i.message}`,502)}if(r.status===401)throw new Ge(`Wrong password for ${t}.`,401);if(r.status===403)throw new Ge(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(r.status===429)throw new Ge(`Too many failed login attempts on ${t}; try again later.`,429);if(!r.ok)throw new Ge(`Login to ${t} failed: HTTP ${r.status}`,502);let o=await r.json();if(!o.session_token||!o.expires_at)throw new Ge(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function Qc(s){let e=s.fetchImpl??fetch,t=Gc(s.host,s.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}Nn();var sy=pt.object({name:pt.string().min(1).max(64).regex(Ho),host:pt.string().min(1),port:pt.number().int().positive().optional(),password:pt.string().min(1),label:pt.string().min(1).max(256).optional(),ttlSec:pt.number().int().positive().optional(),pinnedFingerprint:pt.string().min(1).optional()});function ou(s,e){s.post("/v1/remotes",async(t,n)=>{let r;try{r=sy.parse(t.body)}catch{return n.code(400).send({error:`Invalid request body (name must match ${Ho} and the rest is a normal login request)`})}let o=r.port??Tt;r.pinnedFingerprint&&Fn(r.host,o,r.pinnedFingerprint);let i;try{i=await Kc({host:r.host,port:o,password:r.password,label:r.label,ttlSec:r.ttlSec})}catch(c){if(c instanceof Ge)return n.code(c.status).send({error:c.message});throw c}let a=new Date().toISOString(),d={name:r.name,host:r.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:a,...r.label!==void 0?{label:r.label}:{},...r.pinnedFingerprint!==void 0?{pinnedFingerprint:r.pinnedFingerprint,pinnedAt:a}:{}};return await e.store.set(d),e.health?.markOk(d.name),n.code(201).send({name:d.name,host:d.host,port:d.port,expiresAt:d.expiresAt,label:d.label,addedAt:d.addedAt,pinnedFingerprint:d.pinnedFingerprint,status:e.health?.get(d.name)?.status??"unknown"})}),s.get("/v1/remotes",async(t,n)=>{let r=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{}}});return n.code(200).send({remotes:r})}),s.delete("/v1/remotes/:name",async(t,n)=>{let r=t.params.name,o=e.store.get(r);return o?(await Qc({host:o.host,port:o.port,token:o.token}),await e.store.delete(r),e.health?.forget(r),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||Uo(o.host,o.port),n.code(204).send()):n.code(404).send({error:"Not found"})})}function Vs(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:E.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())}}}Nn();import{WebSocket as ry}from"ws";var oy=1e4,Jo=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}};async function iu(s,e,t=oy){let n={};try{let r=new URL(s);if(r.protocol==="wss:"){let o=zo(r.hostname);o.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=o.rejectUnauthorized),o.autoSelectFamily!==void 0&&(n.autoSelectFamily=o.autoSelectFamily),o.checkServerIdentity!==void 0&&(n.checkServerIdentity=o.checkServerIdentity)}}catch{}return new Promise((r,o)=>{let i=new ry(s,e,n),a=Date.now(),d=setTimeout(()=>{i.off("open",c),i.off("error",u),i.on("error",()=>{});try{i.terminate()}catch{}o(new Jo(s,Date.now()-a))},t),c=()=>{clearTimeout(d),i.off("error",u),r(i)},u=l=>{clearTimeout(d),i.off("open",c),o(l)};i.once("open",c),i.once("error",u)})}var iy=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function ay(s){return iy.has(s)}function du(s,e,t,n){let r=[],o=a=>{for(let d of r)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:n}).then(c=>c?s.send(c):void 0).catch(()=>{})};return s.onMessage(a=>{if("method"in a&&ay(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(dt(c)){i(a,c);return}if(a.method==="session/attach"){let u="id"in a;e.resolveLocalMiss(c).then(l=>{if(l.ok){i(a,l.foreignId);return}if(l.ambiguous&&u){s.send(Dn(a.id,E.SessionNotFound,`Session "${c}" exists on more than one remote (${l.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>s.send(a),onMessage:a=>r.push(a),onClose:a=>s.onClose(a),close:()=>s.close()}}var Gs=class{constructor(e,t=cy,n){this.store=e;this.dial=t;this.localMiss=n}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(n=>n.name)}:{ok:!0,foreignId:qe(t[0])}}async handleLocalMessage(e,t,n){let r="id"in e,o=r?e.id:void 0,i=dt(t);if(!i)return r?Dn(o,E.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=au(n.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let u=this.store.get(i.name);if(!u)return r?Dn(o,E.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let l=this.attachments.get(a);l&&(this.attachments.delete(a),l.peerConnection.close().catch(()=>{}));let p;try{p=await this.dial(u)}catch(g){return r?Dn(o,E.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let m={peerConnection:p,localId:i.localId,target:n};this.wireAttachment(i.name,m);let h;try{h=await p.request("session/attach",d)}catch(g){return p.close().catch(()=>{}),r?Vo(o,g):void 0}this.attachments.set(a,m);let f=h&&typeof h.sessionId=="string"?{...h,sessionId:t}:h;return r?{jsonrpc:"2.0",id:o,result:f}:void 0}let c=this.attachments.get(a);if(!c)return r?Dn(o,E.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let u,l;try{u=await c.peerConnection.request("session/detach",d)}catch(p){l=p}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),l?r?Vo(o,l):void 0:r?{jsonrpc:"2.0",id:o,result:u??{}}:void 0}if(r)try{let u=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:u}}catch(u){return Vo(o,u)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,n]of[...this.attachments.entries()])n.target.clientId===e&&(this.attachments.delete(t),n.peerConnection.request("session/detach",{sessionId:n.localId}).catch(()=>{}),n.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:n,localId:r,target:o}=t,i=qe({name:e,localId:r}),a=()=>{this.attachments.delete(au(o.clientId,i))};n.onAnyNotification((d,c)=>{let u=d;!u||u.sessionId!==r||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...u,sessionId:i}).catch(()=>{}))}),n.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==r)throw{code:E.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),n.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function au(s,e){return`${s} ${e}`}function Dn(s,e,t){return{jsonrpc:"2.0",id:s,error:{code:e,message:t}}}function Vo(s,e){let t=e,n=typeof t?.code=="number"?t.code:E.InternalError,r=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:s,error:{code:n,message:r,...t?.data!==void 0?{data:t.data}:{}}}}var dy=1e4;async function cy(s){let t=`${Re(s.host)?"ws":"wss"}://${s.host}:${s.port}/acp`,n=await iu(t,["acp.v1",`hydra-acp-token.${s.token}`],dy);return new Be(Vs(n))}var uy=3e4,ly=5e3,Ks=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??uy),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString()})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let n=this.store.get(t.name);if(!n)return;let o=`${Re(n.host)?"http":"https"}://${n.host}:${n.port}/v1/auth/verify`,i=new AbortController,a=setTimeout(()=>i.abort(),ly);try{let d=await e(o,{headers:{Authorization:`Bearer ${n.token}`},signal:i.signal});this.snapshots.set(t.name,{status:d.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(d){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:d.message})}finally{clearTimeout(a)}}))}};Nn();import{z as cu}from"zod";var fy=cu.object({sessionLabel:cu.string().min(1).max(256)});function uu(s,e){s.post("/v1/process-tokens",async(t,n)=>{if(t.authIdentity!=="service")return n.code(403).send({error:"Requires the service token"});let r;try{r=fy.parse(t.body)}catch{return n.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(r.sessionLabel,"script");return n.code(201).send({token:o})}),s.delete("/v1/process-tokens/:sessionLabel",async(t,n)=>t.authIdentity!=="service"?n.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),n.code(204).send()))}import{nanoid as Go}from"nanoid";import{randomBytes as mu}from"crypto";import*as hu from"os";import*as yu from"path";var py=200;function gy(s){if(!s||typeof s!="object")return;let e=s._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[ae];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,py)),r.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function lu(s,e,t){let n=gy(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 jn=new Map;function fu(s,e){let t=jn.get(s);t||(t=new Set,jn.set(s,t)),t.add(e);let n=!1;return()=>{if(n)return;n=!0;let r=jn.get(s);r&&(r.delete(e),r.size===0&&jn.delete(s))}}function pu(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=jn.get(r);if(o){if(o.has(s))return!0;for(let i of o)n.push(i)}}return!1}function N(s,e,t){let n=new Error(e);return n.code=s,t!==void 0&&(n.data=t),n}function ky(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 xe(s,e,t){let n=s.get(e);if(!n)throw N(E.SessionNotFound,t??`session ${e} not found`);return n}async function xt(s,e){let t=Kt(s),n,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&s.mcpTokenRegistry!==void 0&&s.getDaemonOrigin!==void 0&&(n=mu(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=No({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 Ty(c,s),ku(c.sessionId,s),c}function wu(s,e){s.get("/acp",{websocket:!0},async(t,n)=>{let r=rc({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=`hydra_client_${Go(12)}`,a=Vs(t),d={},c=e.foreignSessions?du(a,e.foreignSessions,d,i):a,u=new Be(c);d.connection=u;let l={clientId:i,processIdentity:o,attached:new Map};u.onClose(()=>{for(let h of l.attached.values())e.manager.get(h.sessionId)?.detach(h.clientId);l.attached.clear(),e.foreignSessions?.detachClient(i)});let p=(h,f)=>{if(l.attached.get(h)?.readonly)throw N(E.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(u.onRequest("initialize",async h=>{let f=qi.parse(h??{});f.clientInfo?.name&&(l.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let g=f.clientInfo?.version;return g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g)),Ey()}),o&&e.extensionCommands){let h=e.extensionCommands;u.onRequest("hydra-acp/commands/register",async f=>{let g=f??{},w=Array.isArray(g.commands)?g.commands.map(y=>{if(!y||typeof y!="object")return;let k=y;if(typeof k.verb!="string")return;let b={verb:k.verb};return typeof k.argsHint=="string"&&(b.argsHint=k.argsHint),typeof k.description=="string"&&(b.description=k.description),b}).filter(y=>y!==void 0):[];return h.register(o.name,u,w),{ok:!0,registered:w.length}}),u.onClose(()=>{h.clear(o.name)})}if(o&&e.extensionMcp){let h=e.extensionMcp;u.onRequest("hydra-acp/mcp_tools/register",async g=>{let w=g??{},y=typeof w.instructions=="string"?w.instructions:void 0,k=Array.isArray(w.tools)?w.tools.map(b=>{if(!b||typeof b!="object")return;let I=b;if(typeof I.name!="string"||I.name.length===0||typeof I.description!="string"||I.inputSchema===null||typeof I.inputSchema!="object")return;let v={name:I.name,description:I.description,inputSchema:I.inputSchema};return I.outputSchema!==null&&typeof I.outputSchema=="object"&&(v.outputSchema=I.outputSchema),v}).filter(b=>b!==void 0):[];if(k.length===0)throw new Error("register_mcp_tools requires at least one tool");return h.register(o.name,u,y,k),{ok:!0,registered:k.length}});let f=g=>{let w=g??{};if(typeof w.sessionId!="string"||w.sessionId.length===0)throw N(E.InvalidParams,"sessionId is required");return w.sessionId};if(u.onRequest("hydra-acp/session/extension_state/get",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(!e.manager)throw N(E.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(w,o.name,y.key)??null}}),u.onRequest("hydra-acp/session/extension_state/list",async g=>{let w=f(g);if(!e.manager)throw N(E.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(w,o.name)}}),u.onRequest("hydra-acp/session/extension_state/set",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(y.value===void 0)throw N(E.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw N(E.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(w,o.name,y.key,y.value)}catch(k){throw N(E.InvalidParams,k.message)}return{ok:!0}}),u.onRequest("hydra-acp/session/extension_state/delete",async g=>{let w=f(g),y=g??{};if(typeof y.key!="string"||y.key.length===0)throw N(E.InvalidParams,"key is required");if(!e.manager)throw N(E.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(w,o.name,y.key),{ok:!0}}),e.extensionMcpControls){let g=e.extensionMcpControls;u.onRequest("hydra-acp/mcp_tools/refresh_session",async w=>{let y=w??{};if(typeof y.sessionId!="string"||y.sessionId.length===0)throw N(E.InvalidParams,"refresh_session requires sessionId");return await g.notifyToolListChanged(y.sessionId,o.name),{ok:!0}})}u.onClose(()=>{h.clear(o.name)})}if(o?.kind==="transformer"){u.onRequest("hydra-acp/transformer/initialize",async f=>{let g=f??{},w=Array.isArray(g.intercepts)?g.intercepts.filter(y=>typeof y=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,u,w),e.manager?.defaultTransformers.includes(o.name))){let y=e.transformers.resolveChain([o.name])[0];if(y)for(let k of e.manager.liveSessions())k.addTransformer(y)}return{ack:!0}}),u.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),u.onRequest("hydra-acp/message/emit",async f=>{let g=f??{},w=typeof g.sessionId=="string"?g.sessionId:void 0,y=typeof g.method=="string"?g.method:void 0,k=g.envelope,b=g.route;if(!w)throw N(-32602,"emit_message requires sessionId");if(!y&&b!=="client_broadcast")throw N(-32602,"emit_message requires method");let I=xe(e.manager,w),v=typeof g.respondsTo=="string"?g.respondsTo:void 0;if(v)return I.dischargeClaim(v,k),{ok:!0};if(b==="chain")return{ok:!0,response:await I.emitToChain(o.name,y,k)};if(b==="queue"){if(y!=="session/prompt")throw N(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await I.emitToQueue(o.name,k)}}if(b==="daemon")return{ok:!0,response:await I.emitToChain(o.name,y,k)};if(b==="client_broadcast"){if(!k||typeof k!="object")throw N(-32602,"client_broadcast requires an envelope object");return I.broadcastClientUpdate(k),{ok:!0}}throw N(-32602,`unsupported route: ${JSON.stringify(b)}`)}),u.onRequest("hydra-acp/session/request_permission",async f=>{let g=f??{},w=typeof g.sessionId=="string"?g.sessionId:void 0;if(!w)throw N(-32602,"hydra-acp/session/request_permission requires sessionId");return xe(e.manager,w).requestPermissionFromClients(g)}),u.onRequest("hydra-acp/transformer/attach",async f=>Ay(f,o.name,e)),u.onRequest("hydra-acp/child_session/spawn",async f=>{let g=f??{},w=typeof g.agentId=="string"?g.agentId:void 0,y=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.parentSessionId=="string"?g.parentSessionId:void 0,b=rt(g._meta??void 0),I=b.title,v=b.model,A=b.workspace;if(!y&&k){let W=e.manager.get(k);W&&(y=W.cwd)}if(!y)throw N(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let C=await sn(y),R=w??C.agentId??e.defaultAgent,T=await e.registry?.getAgent(R),_=an(C.configDefaults,T??{id:R})?.value,H=v??_?.model,J=typeof g.interactive=="boolean"?g.interactive:!1,M=await e.manager.create({agentId:R,cwd:y,parentSessionId:k,interactive:J,transformChain:[],title:I,model:H,configDefaults:_,...A!==void 0?{workspace:A}:{}});return{childSessionId:M.sessionId,...M.workspace!==void 0||M.workspaceError!==void 0?{_meta:{[ae]:{...M.workspace!==void 0?{workspaceInfo:M.workspace}:{},...M.workspaceError!==void 0?{workspaceError:M.workspaceError}:{}}}}:{}}}),u.onRequest("hydra-acp/session/fork",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"fork_session requires sessionId");let w=typeof g.forkAt=="string"?g.forkAt:void 0,y=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.agentId=="string"?g.agentId:void 0,b=typeof g.mode=="string"&&(g.mode==="verbatim"||g.mode==="synthesis")?g.mode:void 0,I=typeof g.model=="string"&&g.model.length>0?g.model:void 0,v=await e.manager.forkSession(g.sessionId,{...w!==void 0?{forkAt:w}:{},...y!==void 0?{cwd:y}:{},...k!==void 0?{agentId:k}:{},...b!==void 0?{mode:b}:{},...I!==void 0?{model:I}:{}}),A=e.manager.get(v.sessionId);if(!A){let T=await e.manager.loadFromDisk(v.sessionId);if(!T)throw N(E.InternalError,`fork ${v.sessionId} vanished before it could be attached`);A=await xt(e,{...T,onInstallProgress:Qs(u)})}Yt(l,A,A.sessionId);let C=gt(u,A,l),{entries:R}=await A.attach(C,"full");l.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:C.clientId,readonly:!1});for(let T of R){if(u.isClosed())break;await u.notify(T.method,Ue(Le(T.params,T.recordedAt),T.seq)).catch(()=>{})}return{...v,sessionId:A.sessionId}}),u.onRequest("session/fork",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"session/fork requires sessionId");let w=typeof g.cwd=="string"?g.cwd:void 0,y=await e.manager.forkSession(g.sessionId,{...w!==void 0?{cwd:w}:{},mode:"verbatim"}),k=e.manager.get(y.sessionId);if(!k){let v=await e.manager.loadFromDisk(y.sessionId);if(!v)throw N(E.InternalError,`fork ${y.sessionId} vanished before it could be attached`);k=await xt(e,{...v,onInstallProgress:Qs(u)})}Yt(l,k,k.sessionId);let b=gt(u,k,l),{entries:I}=await k.attach(b,"full");l.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:b.clientId,readonly:!1});for(let v of I){if(u.isClosed())break;await u.notify(v.method,Ue(Le(v.params,v.recordedAt),v.seq)).catch(()=>{})}return{sessionId:k.sessionId}});let h=async(f,g)=>{let w=f??{};if(typeof w.sessionId!="string")throw N(E.InvalidParams,`${g} requires sessionId`);let y=await e.manager.resolveCanonicalId(w.sessionId)??w.sessionId,k=e.manager.get(y);if(k)return await k.close({deleteRecord:!0,by:`session/delete ${l.clientId}`}),await e.manager.waitForDeletion(y),await e.manager.hasRecord(y)&&await e.manager.deleteRecord(y),{id:y,existed:!0};let b=await e.manager.deleteRecord(y);return{id:y,existed:b}};u.onRequest("session/delete",async f=>(await h(f,"session/delete"),{})),u.onRequest("session/close",async f=>{let g=f??{};if(typeof g.sessionId!="string")throw N(E.InvalidParams,"session/close requires sessionId");p(g.sessionId,"session/close");let w=await e.manager.resolveCanonicalId(g.sessionId)??g.sessionId,y=e.manager.get(w);if(y)return await y.close({deleteRecord:!1,by:`session/close ${l.clientId}`+(l.processIdentity?` (${l.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(w))return{};throw N(E.SessionNotFound,`session ${w} not found`)}),u.onRequest("hydra-acp/session/delete",async f=>{let{id:g,existed:w}=await h(f,"hydra-acp/session/delete");if(!w)throw N(E.SessionNotFound,`session ${g} not found`);return{deleted:!0,sessionId:g}}),u.onRequest("hydra-acp/child_session/await",async f=>{let g=f??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0,y=g.until==="idle"?"idle":"turn_complete",k=typeof g.timeoutMs=="number"?Math.min(g.timeoutMs,18e5):3e5;if(!w)throw N(-32602,"await_child requires childSessionId");let b=xe(e.manager,w,`child session ${w} not found`);return new Promise(I=>{let C=[],R=[],T=0,_=!1,H,J,M=!1,W=()=>{M||(M=!0,clearTimeout(q),H?.(),J?.(),I(_?{entries:C,truncated:!0}:{entries:C}))};H=b.onBroadcast(te=>{let de=ky(te);for(C.push(te),R.push(de),T+=de;C.length>0&&(C.length>1e3||T>1048576);)C.shift(),T-=R.shift()??0,_=!0;y==="turn_complete"&&te.params?.update?.sessionUpdate==="turn_complete"&&W()});let q=setTimeout(W,k);typeof q.unref=="function"&&q.unref(),J=b.onClose(()=>W())})}),u.onRequest("hydra-acp/child_session/close",async f=>{let g=f??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0;if(!w)throw N(-32602,"close_child_session requires childSessionId");let y=e.manager.get(w);return y&&await y.close({deleteRecord:!1,by:`child_session/close ${l.clientId}`}),{ok:!0}}),u.onRequest("hydra-acp/attention/set",async f=>Cy(f,o.name,e)),u.onRequest("hydra-acp/attention/clear",async f=>Ry(f,o.name,e)),u.onRequest("hydra-acp/connection/keep_alive",async f=>{let g=f??{},w=typeof g.token=="string"?g.token:void 0,y=typeof g.sessionId=="string"?g.sessionId:void 0,k=typeof g.estimatedRemainingMs=="number"?g.estimatedRemainingMs:void 0;return w&&y&&e.manager.get(y)?.keepAliveClaim(w,k),{ok:!0}})}u.onRequest("hydra-acp/session/tool_content",async h=>{let f=h??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw N(E.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let g=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,w=await e.manager.loadToolBlob(g,f.hash);if(w===null)throw N(E.SessionNotFound,"tool content not found");return{content:w}}),u.onRequest("authenticate",async h=>vy(h,e)),u.onRequest("logout",async h=>by(h,e)),u.onRequest("session/new",async h=>{let f=zi.parse(h),g=rt(h?._meta),w=Array.isArray(g.transformers)&&g.transformers.every(Z=>typeof Z=="string")?g.transformers:e.manager.defaultTransformers??[],y=e.transformers?.resolveChain(w)??[],k=await sn(f.cwd),b=g.agentId??k.agentId??e.defaultAgent,I=await e.registry?.getAgent(b),v=an(k.configDefaults,I??{id:b})?.value,A,C,R=f.mcpServers;if(g.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){A=mu(32).toString("hex"),C=e.mcpTokenRegistry.reserve(A);let ke={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${A}`}]};R=[...f.mcpServers??[],ke]}let T,_,H=Kt(e);H!==void 0&&(R=[...R??[],...H.descriptors]);let J=No({baselineMcpServers:f.mcpServers,stdinEnabled:g.mcpStdin===!0,deps:e}),M;try{M=await e.manager.create({cwd:f.cwd,agentId:b,mcpServers:R,title:g.title,agentArgs:g.agentArgs,model:g.model??v?.model,configDefaults:v,onInstallProgress:Qs(u),transformChain:y,originatingClient:l.clientInfo,...g.interactive!==void 0?{interactive:g.interactive}:{},...g.env!==void 0?{forwardedEnv:g.env}:{},...g.workspace!==void 0?{workspace:g.workspace}:{},...J?{mintMcpServersForSwap:J}:{}})}catch(Z){throw C!==void 0&&C.abandon(Z instanceof Error?Z:void 0),_!==void 0&&_.abandon(Z instanceof Error?Z:void 0),H!==void 0&&H.abandon(Z instanceof Error?Z:void 0),Z}if(A!==void 0&&C!==void 0&&e.mcpTokenRegistry!==void 0){let Z=A,ke=e.mcpTokenRegistry;C.complete(M),M.onClose(()=>{ke.unbind(Z)})}if(T!==void 0&&_!==void 0&&e.mcpTokenRegistry!==void 0){let Z=T,ke=e.mcpTokenRegistry;_.complete(M),M.onClose(()=>{ke.unbind(Z)})}H!==void 0&&H.bindToSession(M),ku(M.sessionId,e);let W,q;try{Yt(l,M,M.sessionId),W=gt(u,M,l),{entries:q}=await M.attach(W,"full")}catch(Z){throw await M.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),Z}l.attached.set(M.sessionId,{sessionId:M.sessionId,clientId:W.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let Z of q){if(u.isClosed())break;await u.notify(Z.method,Ue(Le(Z.params,Z.recordedAt),Z.seq)).catch(()=>{})}})()});let te=Ys(M),de=Xs(M);return{sessionId:M.sessionId,...te?{modes:te}:{},...de?{models:de}:{},configOptions:M.buildConfigOptions(),_meta:Zs(e.manager,M,{clientId:W.clientId})}}),u.onRequest("session/attach",async h=>{let f=Vi.parse(h),g=f.clientInfo?.version;g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g));let w=rt(f._meta),y=w.resume,k=w.readonly===!0,b=w.env;s.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!y} readonly=${k}`);let I=y?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,v=e.manager.get(I);if(!v&&k){let M=await e.manager.loadFromDisk(I);if(!M)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);let W=await e.manager.loadHistory(I,{...w.historyLimit!==void 0?{maxEntries:w.historyLimit}:{}}),q=f.clientId??`cli_${Go(8)}`;l.attached.set(M.hydraSessionId,{sessionId:M.hydraSessionId,clientId:q,readonly:!0}),s.log.info(`session/attach OK (viewer) sessionId=${M.hydraSessionId} clientId=${q} attachedCount=${l.attached.size} replayed=${W.length}`);for(let te of W)await u.notify(te.method,Ue(Le(te.params,te.recordedAt),te.seq)).catch(()=>{});return{sessionId:M.hydraSessionId,clientId:q,connectedClients:[q],historyPolicy:"full",replayed:W.length,_meta:xy(M)}}let A=!v;if(!v){let M=await e.manager.loadFromDisk(I),W=await Sy(I,y,M?.upstreamSessionId,e.manager);W.kind==="ignore"&&s.log.warn(W.logMessage);let q=M;if(y&&W.kind==="honor"&&(q={...M,hydraSessionId:f.sessionId,upstreamSessionId:y.upstreamSessionId,agentId:y.agentId,cwd:M?.workspace?.path??y.cwd,...y.title!==void 0?{title:y.title}:{},...y.agentArgs!==void 0?{agentArgs:y.agentArgs}:{}}),!q)throw N(E.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(q.agentId,q.upstreamSessionId))throw N(E.SessionNotFound,`session ${f.sessionId} was deleted`);let te=q.originatingClient?q:{...q,originatingClient:l.clientInfo},de=b!==void 0?{...te,forwardedEnv:b}:te;v=await xt(e,{...de,onInstallProgress:Qs(u)})}Yt(l,v,v.sessionId);let C=gt(u,v,l,f.clientInfo,f.clientId),R=w.replayMode==="drip",{entries:T,appliedPolicy:_}=await v.attach(C,f.historyPolicy,{afterMessageId:f.afterMessageId,afterSeq:f.afterSeq,raw:R,...w.historyLimit!==void 0?{historyLimit:w.historyLimit}:{},...w.toolContent!==void 0?{toolContent:w.toolContent}:{}});if(l.attached.set(v.sessionId,{sessionId:v.sessionId,clientId:C.clientId,readonly:k}),b!==void 0&&await e.manager.setForwardedEnv(v.sessionId,b).catch(()=>{}),s.log.info(`session/attach OK sessionId=${v.sessionId} clientId=${C.clientId} attachedCount=${l.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${_} replayed=${T.length} readonly=${k}${R?" replayMode=drip":""}`),R){let M=w.dripSpeed&&w.dripSpeed>0?w.dripSpeed:1,W=750;(async()=>{let q=null;for(let te of T){let de=typeof te.recordedAt=="number"?te.recordedAt:null;if(q!==null&&de!==null){let Z=Math.min(W,Math.max(0,(de-q)/M));Z>0&&await new Promise(ke=>setTimeout(ke,Z))}de!==null&&(q=de);try{await u.notify(te.method,Ue(Le(te.params,de??void 0),te.seq))}catch{return}}})()}else for(let M=0;M<T.length&&!u.isClosed();M++){let W=T[M],q=u.notify(W.method,Ue(Le(W.params,W.recordedAt),W.seq)).catch(()=>{});(M+1)%200===0&&await q}v.replayPendingPermissions(C);let H=Ys(v),J=Xs(v);return{sessionId:v.sessionId,clientId:C.clientId,connectedClients:v.connectedClients(C.clientId),historyPolicy:_,replayed:T.length,...H?{modes:H}:{},...J?{models:J}:{},configOptions:v.buildConfigOptions(),_meta:Zs(e.manager,v,{resurrected:A})}}),u.onRequest("session/detach",async h=>{let f=Gi.parse(h),g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"client not attached to that session");let w=e.manager.get(f.sessionId);return w?.detach(g.clientId),l.attached.delete(f.sessionId),w&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[ae]:{detachStatus:"detached"}}}}),u.onRequest("session/list",async h=>{let f=Ki.parse(h??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(k=>k.originatingClient?.name!==hs).map(Qi)}}),u.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw N(E.InternalError,"agent registry unavailable");return Ot(e.registry)}),u.onRequest("hydra-acp/agents/auth_methods",async h=>{let f=h??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw N(E.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),u.onRequest("session/prompt",async h=>{let f=Yi.parse(h);p(f.sessionId,"session/prompt");let g=await lu(f,e.manager,b=>{s.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${b} sessionId=${f.sessionId}`)});if(g?.fromSession!==void 0){if((g.depth??0)>3)throw s.log.warn(`session/prompt: refusing depth ${g.depth} chain from ${g.fromSession} to ${f.sessionId}`),N(E.InvalidRequest,`message chain too deep (${g.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(g.awaiting===!0&&pu(g.fromSession,f.sessionId))throw s.log.warn(`session/prompt: refusing deadlock ${g.fromSession} -> ${f.sessionId}`),N(E.InvalidRequest,`would deadlock: ${f.sessionId} is already blocked waiting on ${g.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let w=l.attached.get(f.sessionId);if(!w)throw s.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...l.attached.keys()].join(",")}]`),N(E.SessionNotFound,"not attached to session");let y=e.manager.get(f.sessionId);if(!y){let b=await e.manager.loadFromDisk(f.sessionId);if(!b)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);s.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),y=await xt(e,b);let I=gt(u,y,l,void 0,w.clientId);await y.attach(I,"none")}let k=g?.awaiting===!0&&g.fromSession!==void 0?fu(g.fromSession,f.sessionId):void 0;try{return await y.prompt(w.clientId,f,g)}finally{k?.()}});let m=h=>{let f;try{f=Gn.parse(h)}catch(y){s.log.warn(`session/cancel: invalid params: ${y.message}`);return}let g=l.attached.get(f.sessionId);if(!g)return;if(g.readonly){s.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let w=e.manager.get(f.sessionId);w&&w.cancel(g.clientId).catch(y=>{s.log.warn(`session/cancel for ${f.sessionId}: ${y.message}`)})};u.onNotification("session/cancel",m),u.onRequest("session/cancel",async h=>{let f=Gn.parse(h);return p(f.sessionId,"session/cancel"),m(h),null}),u.onRequest("hydra-acp/prompt/cancel",async h=>{let f=Zi.parse(h);return p(f.sessionId,"hydra-acp/prompt/cancel"),xe(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),u.onRequest("hydra-acp/session/force_cancel",async h=>{let f=Gn.parse(h);return p(f.sessionId,"hydra-acp/session/force_cancel"),xe(e.manager,f.sessionId).forceCancel()}),u.onRequest("hydra-acp/prompt/update",async h=>{let f=ea.parse(h);return p(f.sessionId,"hydra-acp/prompt/update"),xe(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),u.onRequest("hydra-acp/prompt/amend",async h=>{let f=ta.parse(h);p(f.sessionId,"hydra-acp/prompt/amend");let g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"not attached to session");return xe(e.manager,f.sessionId).amendPrompt(g.clientId,f)}),u.onRequest("_session/steering",async h=>{let f=na.parse(h);p(f.sessionId,"_session/steering");let g=l.attached.get(f.sessionId);if(!g)throw N(E.SessionNotFound,"not attached to session");let w=e.manager.get(f.sessionId);if(!w){let y=await e.manager.loadFromDisk(f.sessionId);if(!y)throw N(E.SessionNotFound,`session ${f.sessionId} not found`);w=await xt(e,y);let k=gt(u,w,l,void 0,g.clientId);await w.attach(k,"none")}return w.steer(g.clientId,f)}),u.onRequest("session/resume",async h=>{let f=h??{},g=typeof f.sessionId=="string"?f.sessionId:void 0;if(!g)throw N(E.InvalidParams,"session/resume requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,y=e.manager.get(w);if(!y){let v=await e.manager.loadFromDisk(w);if(!v)throw N(E.SessionNotFound,`session ${g} not found in memory or on disk`);y=await xt(e,v)}Yt(l,y,y.sessionId);let k=gt(u,y,l);await y.attach(k,"pending_only"),l.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:k.clientId,readonly:!1}),y.replayPendingPermissions(k);let b=Ys(y),I=Xs(y);return{sessionId:y.sessionId,...b?{modes:b}:{},...I?{models:I}:{},configOptions:y.buildConfigOptions(),_meta:Zs(e.manager,y,{clientId:k.clientId})}}),u.onRequest("session/load",async h=>{let f=h??{},g=typeof f.sessionId=="string"?f.sessionId:void 0;if(!g)throw N(E.InvalidParams,"session/load requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,y=e.manager.get(w);if(!y){let A=await e.manager.loadFromDisk(w);if(!A)throw N(E.SessionNotFound,`session ${g} not found in memory or on disk`);y=await xt(e,A)}Yt(l,y,y.sessionId);let k=gt(u,y,l),{entries:b}=await y.attach(k,"full");l.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:k.clientId,readonly:!1});for(let A of b){if(u.isClosed())break;await u.notify(A.method,Ue(Le(A.params,A.recordedAt),A.seq)).catch(()=>{})}y.replayPendingPermissions(k);let I=Ys(y),v=Xs(y);return{sessionId:y.sessionId,...I?{modes:I}:{},...v?{models:v}:{},configOptions:y.buildConfigOptions(),_meta:Zs(e.manager,y,{clientId:k.clientId})}}),u.onRequest("session/set_model",async h=>{let f=h?.sessionId;typeof f=="string"&&p(f,"session/set_model");let g=Iy(h,e.manager);if(g.kind==="error")throw s.log.warn(g.logMessage),N(g.code,g.message);if(g.kind==="no_op")return s.log.warn(g.logMessage),await u.notify("session/update",{sessionId:g.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:g.currentModel}}).catch(()=>{}),null;s.log.info(g.logMessage);let{modelId:w}=g,y=await g.session.forwardModelChange(w,h);return g.session.applyAgentConfigOptionResponse(y,"model"),g.session.applyModelChange(w),y}),u.onRequest("session/set_mode",async h=>{let f=h,g=f?.sessionId;if(typeof g=="string"&&p(g,"session/set_mode"),!f||typeof f.sessionId!="string")throw N(E.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw N(E.InvalidParams,"session/set_mode requires string modeId");let w=xe(e.manager,f.sessionId),y=await w.forwardRequest("session/set_mode",h);return w.applyModeChange(f.modeId),y}),u.onRequest("session/set_config_option",async h=>{let f=h,g=b=>N(E.InvalidParams,b),w=f?.sessionId;if(typeof w=="string"&&p(w,"session/set_config_option"),!f||typeof f.sessionId!="string")throw g("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw g("session/set_config_option requires string configId");if(typeof f.value!="string")throw g("session/set_config_option requires string value");let y=xe(e.manager,f.sessionId),k=y.buildConfigOptions().find(b=>b.id===f.configId);if(!k)throw g(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!k.options.some(b=>b.value===f.value))throw g(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{if(f.value!==y.currentModel){let b=await y.forwardModelChange(f.value);y.applyAgentConfigOptionResponse(b,"model")}y.applyModelChange(f.value);break}case"mode":{f.value!==y.currentMode&&await y.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),y.applyModeChange(f.value);break}case"agent":{f.value!==y.agentId&&await y.setAgent(f.value);break}default:{let b=await y.forwardRequest("session/set_config_option",{sessionId:f.sessionId,configId:f.configId,value:f.value});y.applyAgentConfigOptionResponse(b,f.configId)&&y.broadcastConfigOptions()}}return{configOptions:y.buildConfigOptions()}}),u.setDefaultHandler(async(h,f)=>{let g=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),w=f.startsWith("session/"),y=f.startsWith("hydra-acp/");if(!w&&!y||h===null||typeof h!="object"||g.has(f))throw N(E.MethodNotFound,`Method not found: ${f}`);let k=h.sessionId;if(typeof k!="string")throw N(E.MethodNotFound,`Method not found: ${f}`);return p(k,f),xe(e.manager,k).forwardRequest(f,h)})})}async function vy(s,e){let t=s??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw N(E.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 m=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(m)}let d=a.authMethods??[],c=d.find(m=>m.id===n);if(!c){let m=d.map(h=>h.id);throw N(E.InvalidParams,`authenticate: methodId ${JSON.stringify(n)} is not advertised by agent ${a.agentId}; valid: [${m.map(h=>JSON.stringify(h)).join(", ")}]`)}let u=c._meta?.type,l=(()=>{let m=c._meta?.["terminal-auth"];if(m&&typeof m=="object"&&!Array.isArray(m))return m})();if((c.type??(u==="agent"||u==="terminal"?u:l!==void 0?"terminal":"agent"))==="terminal"){let m=(k,b)=>{if(!Array.isArray(k))throw N(E.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw N(E.InvalidParams,`authenticate: method ${JSON.stringify(n)} ${b} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},h=await e.manager.planSpawnForAgent(a.agentId),f,g;if(l?.args!==void 0){let k=typeof l.command=="string"?l.command:void 0;f=k!==void 0&&yu.isAbsolute(k)?k:h.command,g=m(l.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,b=k!==void 0?m(k.raw,k.label):[];f=h.command,g=[...h.args,...b]}let w={};for(let[k,b]of Object.entries(process.env))typeof b=="string"&&(w[k]=b);Object.assign(w,h.env);let y=hu.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${n}`),{kind:"terminal",command:f,args:g,env:w,cwd:y}}try{return await a.connection.request("authenticate",{methodId:n})}catch(m){throw lt(m,a)}}async function by(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 Qs(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(sa,t).catch(()=>{})}}function Ys(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 Xs(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}}async function Sy(s,e,t,n){return e?await n.isRetiredGeneration(s,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${s} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function Iy(s,e){if(!s||typeof s!="object")return{kind:"error",code:E.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:E.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:E.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:E.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=n.availableModels(),o=Ht(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:E.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 Ay(s,e,t){let n=s??{},r=typeof n.sessionId=="string"?n.sessionId:void 0;if(!r)throw N(E.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw N(E.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw N(E.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return xe(t.manager,r).addTransformer(o),{ok:!0}}async function Cy(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 N(E.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw N(E.InvalidParams,"hydra-acp/attention/set requires string reason");return xe(t.manager,r).setAttentionFlag(e,o,n.payload),{ok:!0}}async function Ry(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 N(E.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw N(E.InvalidParams,"hydra-acp/attention/clear requires string reason");return xe(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function xy(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:Sn(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,armedTaskList:[]};return{[ae]:Vn(e,t)}}function Zs(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(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return dn(e.agentMeta,Vn(n,r))}function Ey(){return{protocolVersion:1,agentInfo:{name:"hydra",version:le},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:{...dn(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}}}),steering:{supported:!0}}}}function Ty(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 ku(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 gt(s,e,t,n,r){return{clientId:r??`cli_${Go(8)}`,connection:s,clientInfo:n}}function Yt(s,e,t){let n=s.attached.get(t);n&&(e.detach(n.clientId),s.attached.delete(t))}var er=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 Py}from"crypto";import{McpServer as My}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as _y}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as me}from"zod";function Ko(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 Se(s){return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}var vu="Bearer ";function Xt(s){let e=s.headers.authorization;if(typeof e!="string"||!e.startsWith(vu))return;let t=e.slice(vu.length).trim();return t.length>0?t:void 0}function $y(s){let e=new My({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:me.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let n=s.streamTail(t);return Se(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:me.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let n=s.streamHead(t);return Se(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:me.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:me.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:me.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 Se(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:me.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:me.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 Se({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:me.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:me.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:me.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:me.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:me.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:me.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:me.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:me.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:me.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 Se(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 Se(t)}),e}var Oy=1e4;function bu(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=$y(a),u=new _y({sessionIdGenerator:()=>Py()});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=Xt(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 p,m=new Promise(f=>{p=setTimeout(()=>f(void 0),Oy)}),h=await Promise.race([c.sessionReady.catch(()=>{}),m]);if(p!==void 0&&clearTimeout(p),h===void 0){a.code(503).send({error:"session not ready"});return}u=h}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 Fy}from"crypto";import{McpServer as Ny}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Dy}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ke}from"zod";function jy(s){switch(s){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var Su=2e3,Iu=2e4;function Hy(s,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return Ut([s]);let n=[],r=un(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=Xn(t);return i!==void 0&&n.push(i),n.join(`
199
+ `)}function Ly(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 Uy(s){let e=new Ny({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:Ke.string().min(1).describe("Case-insensitive substring to search for."),limit:Ke.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ke.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 Se({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=Ko(u);if(!l)continue;let{kind:p,update:m}=l;if((p==="tool_call"||p==="tool_call_update")&&!r)continue;let h=Hy(u,p,m),f=h.toLowerCase().indexOf(a);if(f<0)continue;let g=jy(p),w=Ly(h,f),y=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:w,timestamp:y}),i.length>=n)break}i.sort((c,u)=>c.entryId-u.entryId);let d=i.length>=n;return Se({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:Ke.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ke.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 Se({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 Se({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=Ut(u,{toolOutput:{maxPerCall:Su,maxTotal:Iu}});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:Ke.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:Ke.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:Ke.string().optional(),limit:Ke.number().int().min(1).max(100).optional(),include_output:Ke.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 Se({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,p=Math.max(o*4,200);for await(let{entryId:y,entry:k}of a.iterRecallNewestFirst()){let b=Ko(k);if(!b)continue;let{kind:I,update:v}=b;if(I!=="tool_call"&&I!=="tool_call_update")continue;let A=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:`__noid_${y}`,C=l.get(A);if(C||(C={entryId:y,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},l.set(A,C)),y<C.entryId&&(C.entryId=y),!C.nameAuthoritative){let T=un(v);T!==void 0?(C.toolName=T,C.nameAuthoritative=!0):typeof v.name=="string"&&v.name.length>0?(C.toolName=v.name,C.nameAuthoritative=!0):I==="tool_call"&&typeof v.title=="string"&&v.title.length>0&&(C.toolName=v.title,C.nameAuthoritative=!0)}if(C.kind===void 0&&typeof v.kind=="string"&&v.kind.length>0&&(C.kind=v.kind),C.output===void 0){let T=Xn(v);T!==void 0&&(C.output=T)}let R=v.rawInput;if(R&&typeof R=="object"&&!Array.isArray(R)&&Object.keys(R).length>0)for(let[T,_]of Object.entries(R))C.rawInput[T]===void 0&&(C.rawInput[T]=_);if(Array.isArray(v.locations))for(let T of v.locations){let _=T?.path;typeof _=="string"&&_.length>0&&!C.locations.includes(_)&&C.locations.push(_)}if(typeof v.status=="string"&&C.status==="in_progress"&&(C.status=v.status),k.recordedAt!==void 0&&C.timestamp===void 0&&(C.timestamp=String(k.recordedAt)),l.size>=p)break}let m=[...l.keys()].sort((y,k)=>l.get(y).entryId-l.get(k).entryId),h=[],f=Iu,g=!1;for(let y of m){let k=l.get(y);if(k.toolName=Fr({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==n.toLowerCase())continue;if(u){let v=r.toLowerCase(),A=["file_path","filePath","path"],C=!1;for(let R of A){let T=k.rawInput[R];if(typeof T=="string"&&T.toLowerCase().includes(v)){C=!0;break}}if(!C){for(let R of k.locations)if(R.toLowerCase().includes(v)){C=!0;break}}if(!C)continue}let b={};for(let[v,A]of Object.entries(k.rawInput))typeof A=="string"?b[v]=A.length>500?A.slice(0,497)+"\u2026":A:(typeof A=="number"||typeof A=="boolean")&&(b[v]=A);k.locations.length>0&&b.locations===void 0&&(b.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:b,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let v=k.output,A=Math.min(Su,f);if(A<=0)g=!0;else{let C=v.length<=A?v:v.slice(0,A-1)+"\u2026";I.output=C,I.outputBytes=v.length,I.outputTruncated=C.length<v.length,f-=C.length}}if(h.push(I),h.length>=o)break}let w=h.length>=o;return Se({calls:h,truncated:w,...g?{outputBudgetExhausted:g}:{}})}),e}var By=1e4;function Au(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=Uy(a),u=new Dy({sessionIdGenerator:()=>Fy()});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=Xt(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 p,m=new Promise(f=>{p=setTimeout(()=>f(void 0),By)}),h=await Promise.race([c.sessionReady.catch(()=>{}),m]);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 tr=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 Qy}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Yy}from"crypto";import{Server as Wy}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as qy,ListToolsRequestSchema as zy}from"@modelcontextprotocol/sdk/types.js";function Cu(s,e,t,n){let r=typeof t=="function"?async()=>t():async()=>t,o=new Wy({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(zy,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(qy,async(a,d)=>{let c=a.params.name,u=d._meta?.progressToken??d.requestId,l=Vy(u,d.sendNotification);try{let p=await r(),m=await Gy(e.connection,s,c,a.params.arguments??{},p);return Ky(m,c)}catch(p){return Qo(p instanceof Error?p.message:String(p))}finally{l()}}),o}var Jy=15e3;function Vy(s,e,t=Jy){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 Gy(s,e,t,n,r){return await s.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:n,sessionId:r})}function Ky(s,e){if(s===null||typeof s!="object")return Qo(`extension ${e} returned non-object`);let t=s;return Array.isArray(t.content)?t:Qo(`extension ${e} omitted content array`)}function Qo(s){return{content:[{type:"text",text:s}],isError:!0}}var Xy=1e4;function Ru(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 p=l.get(u);p!==void 0&&(l.delete(u),r(p))}}async function i(u,l){for(let[p,m]of n){if(e.lookup(p)?.session?.sessionId!==u)continue;let f=m.get(l);if(f!==void 0)try{await f.server.sendToolListChanged()}catch{}}}t.onChange(u=>{o(u)});async function a(u,l){let p=n.get(u);p===void 0&&(p=new Map,n.set(u,p),e.addDisposer(u,async()=>{let b=n.get(u);if(b!==void 0){n.delete(u);for(let I of b.values())await r(I)}}));let m=p.get(l);if(m!==void 0)return m.transport;let h=t.lookup(l);if(h===void 0)return;let y=Cu(l,h,async()=>{let b=e.lookup(u);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let I,v=new Promise(C=>{I=setTimeout(()=>C(void 0),Xy)}),A=await Promise.race([b.sessionReady.catch(()=>{}),v]);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 b=>{let I=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!I||typeof I!="object")return;let v=I.tools;if(!Array.isArray(v))return;let A=[];for(let C of v){if(!C||typeof C!="object")continue;let R=C;if(typeof R.name!="string"||R.name.length===0||typeof R.description!="string"||R.inputSchema===null||typeof R.inputSchema!="object")continue;let T={name:R.name,description:R.description,inputSchema:R.inputSchema};R.outputSchema!==null&&typeof R.outputSchema=="object"&&(T.outputSchema=R.outputSchema),A.push(T)}return A}}),k=new Qy({sessionIdGenerator:()=>Yy()});return await y.connect(k),p.set(l,{server:y,transport:k}),k}async function d(u,l){let p=Xt(u);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=u.params.name,f=await a(p,h);if(f===void 0){l.code(404).send({error:`unknown mcp server: ${h}`});return}l.hijack(),await f.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 _u(s,e){ow(s),gr(s.daemon.scrubEnv);let t=s,n=s.daemon.tls?await Qe.readFile(ce(s.daemon.tls.key)):void 0,r=s.daemon.tls?await Qe.readFile(ce(s.daemon.tls.cert)):void 0;await Qe.mkdir(x.home(),{recursive:!0});let{stream:o,fileStream:i}=await sw(s.daemon.logLevel),a=Zy({logger:{level:s.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(ew,{options:{handleProtocols:yi}}),vr(F=>{a.log.info(F)}),Ir(F=>{a.log.info(F)});let d=await Ms.load(),c=await zs.load();qo(),Bo(c);let u=new Ks(c);u.start();let l=new Us(c);l.start();let p=new Ns,m=new Fs,h=new _s(e),f=new Os([h,new $s(d),m]),g=sc({validator:f});a.addHook("onRequest",async(F,ve)=>{F.routeOptions.config?.skipAuth||F.url==="/acp"||F.url?.startsWith("/acp?")||(await g(F,ve),!ve.sent&&F.authIdentity?.startsWith("script:")&&!oc(F.method,F.routeOptions.url)&&ve.code(403).send({error:"script tokens may only access read-only session data"}))});let w=setInterval(()=>{d.sweepExpired()},300*1e3);w.unref();let y=setInterval(()=>{p.sweepExpired()},300*1e3);y.unref();let k=new zn(s,{onFetched:()=>{Wd(k,A)},onStaleFallback:(F,ve)=>{let en=Math.round(ve/36e5),tn=en>=48?`${Math.round(en/24)}d`:`${en}h`;a.log.warn(`registry fetch failed (${F.message}); serving stale cache last synced ${tn} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});To(F=>a.log.info(F));let b={info:F=>a.log.info(F),warn:F=>a.log.warn(F)},I=F=>it.spawn({...F,stderrTailBytes:s.daemon.agentStderrTailBytes,logger:b});Ii(s.compressToolContent);let v=new Ts,A=new bs(k,I,void 0,{idleTimeoutMs:s.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:s.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:s.sessionDefaults,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:b,npmRegistry:s.npmRegistry,extensionCommands:v,defaultCwd:s.defaultCwd,disableWorkspaceSnapshots:s.disableWorkspaceSnapshots}),C=new Gs(c,void 0,{resolvesLocally:async F=>await A.resolveCanonicalId(F)!==void 0,cache:l}),R=new xs(fi(s),void 0,{tokenRegistry:m}),T=new Es(pi(s),void 0,{tokenRegistry:m}),_=[];jc(a,le,Jd(s),()=>_);let H=new er,J=new tr,M,W=()=>{if(M!==void 0)return M;let F=a.server.address();return M=`http://127.0.0.1:${F&&typeof F=="object"?F.port:s.daemon.port}`,M},q={agentId:s.defaultAgent,cwd:s.defaultCwd,publicHost:s.daemon.publicHost,host:s.daemon.host,port:s.daemon.port,compaction:s.compaction};Nc(a,A,q,{extensionMcp:J,mcpTokenRegistry:H,getDaemonOrigin:W},c,l),Mc(a,{store:c,localMiss:{resolvesLocally:async F=>await A.resolveCanonicalId(F)!==void 0,cache:l}}),Dc(a,k,A,{npmRegistry:s.npmRegistry}),Hc(a,R),Lc(a,T),Uc(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]})),Jc(a,{store:d,rateLimiter:p,staticTokenValidator:h}),ou(a,{store:c,health:u}),uu(a,{processRegistry:m}),bu(a,H),Au(a,H);let te=Ru(a,H,J);wu(a,{validator:f,manager:A,defaultAgent:s.defaultAgent,processRegistry:m,onExtensionVersion:(F,ve)=>R.reportVersion(F,ve),onTransformerVersion:(F,ve)=>T.reportVersion(F,ve),transformers:T,extensionCommands:v,mcpTokenRegistry:H,extensionMcp:J,extensionMcpControls:te,getDaemonOrigin:W,registry:k,foreignSessions:C});let de=!!s.daemon.tls;await a.listen({host:de?"127.0.0.1":s.daemon.host,port:de?0:s.daemon.port});let Z=a.server.address(),ke=Z&&typeof Z=="object"?Z.port:s.daemon.port,Hn,$u=s.daemon.host,Yo=ke;if(de&&n&&r){Hn=rw({listenHost:s.daemon.host,listenPort:s.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:ke,tlsOptions:{key:n,cert:r},logger:a.log});let F=Hn.address();F&&typeof F=="object"&&(Yo=F.port)}await Qe.mkdir(x.home(),{recursive:!0}),await Bd({pid:process.pid,host:$u,port:Yo,loopbackPort:ke,startedAt:new Date().toISOString()});let Xo={daemonUrl:`http://127.0.0.1:${ke}`,daemonHost:"127.0.0.1",daemonPort:ke,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${ke}/acp`,hydraHome:x.home()};R.setContext(Xo),T.setContext(Xo),await R.start(),await T.start();try{await A.reconcilePermissionFlags()}catch(F){a.log.warn(`permission flag reconcile failed: ${F.message}`)}try{await A.seedSessionIndex()}catch(F){a.log.warn(`session index seed failed: ${F.message}`)}A.resurrectPendingQueues().catch(F=>{a.log.warn(`queue replay scan failed: ${F.message}`)}),A.resumePendingCompactions().catch(F=>{a.log.warn(`compaction resume scan failed: ${F.message}`)}),A.resumePendingAgentSwaps().catch(F=>{a.log.warn(`agent-swap resume scan failed: ${F.message}`)});let Zo=s.daemon.agentSyncIntervalMinutes*60*1e3,ei=Zo>0?qd({registry:k,manager:A,intervalMs:Zo,logger:b}):void 0,ti=s.daemon.sessionGcIntervalMinutes*60*1e3,Ou=s.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ni=ti>0?zd({manager:A,intervalMs:ti,maxAgeMs:Ou,logger:b}):void 0,Fu=Qd({bootConfig:s,apply:F=>{t=F,k.setConfig(F),A.setLiveConfig({sessionDefaults:F.sessionDefaults}),q.agentId=F.defaultAgent,q.cwd=F.defaultCwd,gr(F.daemon.scrubEnv)},onDrift:F=>{_=F},logger:b});return{app:a,manager:A,registry:k,extensions:R,transformers:T,mcpTokenRegistry:H,extensionMcp:J,processRegistry:m,shutdown:async()=>{u.stop(),l.stop(),Fu(),ni&&ni(),ei&&ei(),clearInterval(w),clearInterval(y);let F=async(ve,en)=>{try{await en()}catch(tn){a.log.warn(`shutdown step ${ve} failed: ${tn instanceof Error?tn.message:String(tn)}`)}};await F("sessionTokenStore.flush",()=>d.flush()),await F("extensions.stop",()=>R.stop()),await F("transformers.stop",()=>T.stop()),await F("manager.closeAll",()=>A.closeAll()),await F("manager.flushSynopsis",()=>A.flushSynopsis(3e4)),await F("manager.shutdownSynopsis",()=>A.shutdownSynopsis()),await F("manager.flushMetaWrites",()=>A.flushMetaWrites()),await F("manager.flushHistoryWrites",()=>A.flushHistoryWrites()),vr(null),Ir(null),To(null),Hn&&await F("tlsTerminator.close",()=>new Promise(ve=>Hn.close(()=>ve()))),await F("app.close",()=>a.close());try{Tu.unlinkSync(x.pidFile())}catch{}await F("fileStream.flushSync",()=>i.flushSync())}}}var Eu=20;async function nw(s,e){let t=Zt.dirname(s),n=Zt.basename(s,".log"),r=new RegExp(`^${n}\\.(\\d+)\\.log$`),o;try{o=await Qe.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=>Qe.unlink(Zt.join(t,d.name))))}async function sw(s){await nw(x.logFile(),Eu);let e=await tw({file:x.logFile(),size:"10m",mkdir:!0,symlink:As,limit:{count:Eu,removeOtherLogFiles:!0}}),t=xu.destination(2);return{stream:xu.multistream([{stream:e,level:s},{stream:t,level:s}]),fileStream:e}}function rw(s){let e=Mu.createServer(s.tlsOptions,t=>{let n=Pu.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 ow(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 iw(){process.title="hydra-acp-daemon";let{installGlobalTlsTrust:s}=await Promise.resolve().then(()=>(Nn(),ru));s();let e=await rn(),t=await oi(),n=await _u(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
200
200
  `);let r=1e4,o=!1,i=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
201
201
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
202
202
  `);let a=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${r}ms; forcing exit.