@hydra-acp/cli 0.1.87 → 0.1.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +352 -317
- package/dist/index.d.ts +892 -575
- package/dist/index.js +105 -75
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,68 +1,78 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
`,{encoding:"utf8",mode:384})}async function
|
|
3
|
-
`),e}import*as
|
|
4
|
-
`;await
|
|
5
|
-
`)}async function
|
|
6
|
-
`)};function
|
|
7
|
-
`))}async function
|
|
8
|
-
`)};function
|
|
9
|
-
`))}async function
|
|
10
|
-
stderr: ${l}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<go)return await new Promise(r=>setTimeout(r,mo*(e+1))),As(n,e+1);throw t}}function yo(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function wo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function xs(n,e){let t=de.join(n,"node_modules",e,"package.json");try{let s=await Z.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Ss(n){let e=de.join(n.installDir,"node_modules",".bin"),t=de.join(e,n.hint);if(await ke(t))return{binName:n.hint,binPath:t};let s=await xs(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=de.join(e,i);if(await ke(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=de.join(e,i);if(await ke(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=de.join(e,n.basename);if(await ke(r))return{binName:n.basename,binPath:r}}}async function ke(n){try{return await Z.access(n),!0}catch{return!1}}var vo=C.object({package:C.string(),bin:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Fe=C.object({archive:C.string().url().optional(),cmd:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Io=C.object({"darwin-aarch64":Fe.optional(),"darwin-x86_64":Fe.optional(),"linux-aarch64":Fe.optional(),"linux-x86_64":Fe.optional(),"windows-x86_64":Fe.optional(),"windows-aarch64":Fe.optional()}),bo=C.object({package:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),So=C.object({command:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),ko=C.object({command:C.string().optional(),url:C.string().optional(),description:C.string().optional()}),Ao=C.object({npx:vo.optional(),binary:Io.optional(),uvx:bo.optional(),exec:So.optional()}),xo=C.object({id:C.string(),name:C.string(),version:C.string().optional(),description:C.string().optional(),authors:C.array(C.string()).optional(),license:C.string().optional(),icon:C.string().optional(),repository:C.string().optional(),website:C.string().optional(),distribution:Ao,onboarding:ko.optional()}),Cs=C.object({version:C.string(),agents:C.array(xo),extensions:C.array(C.unknown()).optional()}),Qe=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(o=>o.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>mn(o)===e);return i?this.applyOverride(i):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:t.command??e,args:t.args,env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:Co(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=Cs.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await oe(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Cs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ne(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Co(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function mn(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Oe(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await hn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function hn(n){let e=ae();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=un(n.distribution.binary,e);if(s?.cmd){let r=vt.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await Ms(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??mn(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=vt.join(i,"node_modules",".bin",r);if(await Ms(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Ms(n){try{return await Rs.access(n),!0}catch{return!1}}async function se(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??mn(n)??r.package,a=t.onInstallProgress;return{command:await ks({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=un(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ae()??"this platform"}.`);let i=t.onInstallProgress,o=await bs({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as To}from"child_process";import*as St from"fs";import*as Ls from"path";var I={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as O}from"zod";var Es=O.object({protocolVersion:O.number().optional(),clientCapabilities:O.record(O.unknown()).optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional()}),Mo=O.enum(["full","pending_only","none","after_message"]),Ps=O.object({cwd:O.string(),mcpServers:O.array(O.unknown()).optional(),_meta:O.record(O.unknown()).optional()}),Ts=O.object({upstreamSessionId:O.string(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),agentArgs:O.array(O.string()).optional()}),_s=O.object({sessionId:O.string(),historyPolicy:Mo.default("full"),afterMessageId:O.string().optional(),clientId:O.string().optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional(),_meta:O.record(O.unknown()).optional()});import{z as M}from"zod";var $s=M.object({sessionId:M.string()}),Fs=M.object({cwd:M.string().optional(),cursor:M.string().optional()}),yn=M.object({used:M.number().optional(),size:M.number().optional(),costAmount:M.number().optional(),costCurrency:M.string().optional()}),Hu=M.object({sessionId:M.string(),upstreamSessionId:M.string().optional(),cwd:M.string(),title:M.string().optional(),agentId:M.string().optional(),currentModel:M.string().optional(),currentUsage:yn.optional(),importedFromMachine:M.string().optional(),importedFromUpstreamSessionId:M.string().optional(),parentSessionId:M.string().optional(),forkedFromSessionId:M.string().optional(),forkedFromMessageId:M.string().optional(),originatingClient:M.object({name:M.string(),version:M.string().optional()}).optional(),interactive:M.boolean().optional(),priority:M.number().int().nonnegative().optional(),updatedAt:M.string(),attachedClients:M.number().int().nonnegative(),status:M.enum(["live","cold"]).default("live"),busy:M.boolean().default(!1),awaitingInput:M.boolean().default(!1),_meta:M.record(M.unknown()).optional()}),Ro=M.object({sessionId:M.string(),cwd:M.string(),title:M.string().optional(),updatedAt:M.string().optional(),_meta:M.record(M.unknown()).optional()}),Bu=M.object({sessions:M.array(Ro),nextCursor:M.string().optional()});function It(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue)),t}function Os(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:Ve(n._meta,It(n))};return n.title!==void 0&&(e.title=n.title),e}var Ge="hydra-acp";function Eo(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function Ye(n){if(!n)return{};let e=n[Ge];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=Ts.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=yn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="live"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Eo(t.env);r!==void 0&&(s.env=r)}return s}function Ve(n,e){return{...n??{},[Ge]:e}}import{z as S}from"zod";var Ns=S.object({sessionId:S.string(),prompt:S.array(S.unknown()),_meta:S.record(S.unknown()).optional()}),bt=S.object({sessionId:S.string()}),js=S.object({clientId:S.string(),name:S.string().optional(),version:S.string().optional()}),zu=S.object({sessionId:S.string(),messageId:S.string(),originator:js,prompt:S.array(S.unknown()),position:S.number().int().nonnegative(),queueDepth:S.number().int().positive(),enqueuedAt:S.number()}),Wu=S.object({sessionId:S.string(),messageId:S.string(),prompt:S.array(S.unknown())}),Qu=S.object({sessionId:S.string(),messageId:S.string(),reason:S.enum(["started","cancelled","abandoned"])}),Hs=S.object({sessionId:S.string(),messageId:S.string()}),Vu=S.object({cancelled:S.boolean(),reason:S.enum(["ok","not_found","already_running"])}),Bs=S.object({sessionId:S.string(),messageId:S.string(),prompt:S.array(S.unknown())}),Gu=S.object({updated:S.boolean(),reason:S.enum(["ok","not_found","already_running"])}),Us=S.object({sessionId:S.string(),targetMessageId:S.string(),prompt:S.array(S.unknown()),replaceQueue:S.boolean().optional(),onTargetCompleted:S.enum(["reject","send_anyway"]).optional()}),Yu=S.object({amended:S.boolean(),reason:S.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:S.string().optional()}),Ku=S.object({sessionId:S.string(),cancelledMessageId:S.string(),newMessageId:S.string(),prompt:S.array(S.unknown()),originator:js,amendedAt:S.number()});import{z as ve}from"zod";var el=ve.object({agentId:ve.string(),version:ve.string(),source:ve.enum(["binary","npm"]),phase:ve.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ve.number().optional(),totalBytes:ve.number().optional(),packageSpec:ve.string().optional()}),Ds="hydra-acp/agents/install_progress";function wn(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
|
|
11
|
-
`);for(;
|
|
12
|
-
`)}}),n.on("end",()=>
|
|
13
|
-
`;await new Promise((
|
|
14
|
-
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=
|
|
15
|
-
`),this.connection.fail(new Error(
|
|
16
|
-
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${
|
|
17
|
-
stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=
|
|
1
|
+
import*as gi from"fs";import*as et from"fs/promises";import*as hi from"net";import*as yi from"tls";import Nu from"fastify";import ju from"@fastify/websocket";var ks="acp.v1";function As(n,e){return n.has(ks)?ks:!1}import mi from"pino";import Bu from"pino-roll";import*as be from"fs/promises";import{homedir as mn}from"os";import{z as b}from"zod";import*as F from"path";import*as pn from"os";var bi="HYDRA_ACP_HOME";function xe(n){let e=pn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Ii(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function j(){let n=process.env[bi];if(n&&n.length>0)return F.resolve(n);let e=Ii();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return F.join(pn.homedir(),".hydra-acp")}var v={home:j,config:()=>F.join(j(),"config.json"),authToken:()=>F.join(j(),"auth-token"),remotes:()=>F.join(j(),"remotes.json"),pidFile:()=>F.join(j(),"daemon.pid"),logFile:()=>F.join(j(),"daemon.log"),currentLogFile:()=>F.join(j(),"current.log"),registryCache:()=>F.join(j(),"registry.json"),agentsDir:()=>F.join(j(),"agents"),agentLogFile:n=>F.join(j(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>F.join(j(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>F.join(j(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>F.join(j(),"sessions"),sessionDir:n=>F.join(j(),"sessions",n),sessionFile:n=>F.join(j(),"sessions",n,"meta.json"),historyFile:n=>F.join(j(),"sessions",n,"history.jsonl"),toolsDir:n=>F.join(j(),"sessions",n,"tools"),toolBlobFile:(n,e)=>F.join(j(),"sessions",n,"tools",e),queueFile:n=>F.join(j(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>F.join(j(),"sessions",".tombstones"),tombstoneAgentDir:n=>F.join(j(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>F.join(j(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>F.join(j(),"extensions"),extensionLogFile:n=>F.join(j(),"extensions",`${n}.log`),extensionPidFile:n=>F.join(j(),"extensions",`${n}.pid`),transformersDir:()=>F.join(j(),"transformers"),transformerLogFile:n=>F.join(j(),"transformers",`${n}.log`),transformerPidFile:n=>F.join(j(),"transformers",`${n}.pid`),transformerState:(n,e)=>F.join(j(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>F.join(j(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>F.join(j(),"prompt-history"),tuiLogFile:()=>F.join(j(),"tui.log"),shimWireLogFile:()=>F.join(j(),"shim-wire.log")};import*as _e from"fs/promises";function xt(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Cs(){try{let e=(await _e.readFile(v.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Si(){let n=await Cs();if(!n)throw new Error(`No service token found at ${v.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function fn(n){await _e.mkdir(v.home(),{recursive:!0}),await _e.writeFile(v.authToken(),n+`
|
|
2
|
+
`,{encoding:"utf8",mode:384})}async function ki(){let n=await Cs();if(n)return n;let e=xt();return await fn(e),process.stderr.write(`hydra-acp: initialized ${v.authToken()} with a fresh service token.
|
|
3
|
+
`),e}import*as Q from"fs/promises";import*as xs from"fs";import*as oe from"path";import{randomBytes as Ai}from"crypto";async function ie(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
4
|
+
`;await Ci(n,r,t)}async function Ci(n,e,t={}){let s=await xi(n),r=Mi(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${Ri()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Q.writeFile(o,e,i),await Q.rename(o,s)}catch(i){throw await Q.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{xs.chmodSync(s,t.mode)}catch{}}async function xi(n){let e;try{e=await Q.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Q.readlink(n),s=oe.isAbsolute(t)?t:oe.resolve(oe.dirname(n),t);try{let r=await Q.realpath(oe.dirname(s));return oe.join(r,oe.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function ue(n){let e;try{e=await Q.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Mi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Ri(){return Ai(4).toString("hex")}var Rs="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Ei=b.object({cert:b.string(),key:b.string()}),Es=55514,Pi=b.object({host:b.string().default("127.0.0.1"),port:b.number().int().positive().default(Es),logLevel:b.enum(["debug","info","warn","error"]).default("info"),tls:Ei.optional(),sessionIdleTimeoutSeconds:b.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:b.number().int().positive().default(1e4),agentStderrTailBytes:b.number().int().positive().default(4096),publicHost:b.string().optional(),agentSyncIntervalMinutes:b.number().nonnegative().default(60),sessionGcIntervalMinutes:b.number().nonnegative().default(60),sessionGcMaxAgeDays:b.number().positive().default(2)}),Ti=b.object({url:b.string().url().default(Rs),ttlHours:b.number().positive().default(24),pinned:b.boolean().default(!1)}),_i=b.object({name:b.string().optional(),description:b.string().optional(),command:b.string().optional(),args:b.array(b.string()).optional(),env:b.record(b.string()).optional()}),$i=b.object({packageSpec:b.string().optional()}),Fi=b.object({repaintThrottleMs:b.number().int().nonnegative().default(1e3),maxScrollbackLines:b.number().int().positive().default(1e4),mouse:b.boolean().default(!0),inAppSelection:b.boolean().optional(),selectionClipboard:b.enum(["primary","clipboard","both"]).default("both"),openFileCommand:b.union([b.string(),b.array(b.string())]).optional(),logMaxBytes:b.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:b.number().int().positive().default(32),progressIndicator:b.boolean().default(!0),defaultEnterAction:b.enum(["enqueue","amend"]).default("amend"),showThoughts:b.boolean().default(!0),ambiguousWidth:b.enum(["auto","narrow","wide"]).default("auto"),toolContent:b.enum(["inline","references"]).default("references"),diffContextLines:b.number().int().min(0).default(3),promptHistoryMaxEntries:b.number().int().positive().default(2e3),maxToolItems:b.number().int().nonnegative().default(5),maxPlanItems:b.number().int().nonnegative().default(5),showFileUpdates:b.enum(["none","edit","diff"]).default("edit"),sessionColumns:b.array(b.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Ms=b.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Oi=b.object({command:b.array(b.string()).default([]),args:b.array(b.string()).default([]),env:b.record(b.string()).default({}),enabled:b.boolean().default(!0)}),Hi=b.object({command:b.array(b.string()).default([]),args:b.array(b.string()).default([]),env:b.record(b.string()).default({}),enabled:b.boolean().default(!0)}),Ps=b.object({daemon:Pi.default({}),registry:Ti.default({url:Rs,ttlHours:24,pinned:!1}),agents:b.record(b.string(),_i).default({}),agentOverrides:b.record(b.string(),$i).default({}),defaultAgent:b.string().default("opencode"),defaultModels:b.record(b.string(),b.string()).default({}),synopsisAgent:b.string().optional(),synopsisModel:b.string().optional(),compaction:b.object({agent:b.string().optional(),model:b.string().optional(),tailK:b.number().int().nonnegative().default(20),maxIterations:b.number().int().positive().default(3),contextFraction:b.number().min(0).max(1).default(.5),hardCeilingFraction:b.number().min(0).max(1).default(.85),absoluteFallback:b.number().int().positive().default(12e4),idleBeforePromptMs:b.number().int().nonnegative().default(3e5),modelContextWindows:b.record(b.string(),b.number().int().positive()).default({})}).default({}),defaultCwd:b.string().default("~"),compressToolContent:b.boolean().default(!0),sessionListColdLimit:b.number().int().nonnegative().default(20),extensions:b.record(Ms,Oi).default({}),transformers:b.record(Ms,Hi).default({}),defaultTransformers:b.array(b.string()).default([]),npmRegistry:b.string().url().optional(),tui:Fi.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function Ts(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function _s(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function $s(){return await Ni(),await ue(v.config())??{}}async function Ni(){let n;try{n=await be.lstat(v.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await be.stat(v.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await be.readlink(v.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${v.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 ji(){let n=await $s(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await be.access(v.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${v.authToken()} and ${v.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await fn(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ie(v.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${v.config()} to ${v.authToken()}.
|
|
5
|
+
`)}async function Fs(){return await ji(),Ps.parse(await $s())}async function Bi(n){await ie(v.config(),n,{mode:384})}function Ui(){return Ps.parse({})}function Y(n){return n==="~"||n==="$HOME"?mn():n.startsWith("~/")?mn()+n.slice(1):n.startsWith("$HOME/")?mn()+n.slice(5):n}import*as V from"fs/promises";import{createHash as Di}from"crypto";import{gzip as Li,gunzip as qi}from"zlib";import{promisify as Os}from"util";var Hs=Os(Li),zi=Os(qi),Ns=/^[A-Za-z0-9_-]+$/,Ji=/^[a-f0-9]{64}$/,gn=!0;function js(n){gn=n}function Mt(n,e){return Ns.test(n)?e===void 0||Ji.test(e):!1}function Rt(n,e){return`${v.toolBlobFile(n,e)}.gz`}async function hn(n,e){if(!Mt(n))return null;let t=Di("sha256").update(e,"utf8").digest("hex"),s=Rt(n,t),r=v.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(v.toolsDir(n),{recursive:!0});let o=gn?s:r,i=gn?await Hs(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await V.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function Et(n,e){if(!Mt(n,e))return null;try{let t=await V.readFile(Rt(n,e));return(await zi(t)).toString("utf8")}catch{}try{return await V.readFile(v.toolBlobFile(n,e),"utf8")}catch{return null}}async function Bs(n,e){if(!Mt(n,e))return null;try{return await V.readFile(Rt(n,e))}catch{}try{let t=await V.readFile(v.toolBlobFile(n,e));return await Hs(t)}catch{return null}}async function Us(n,e,t){if(!Mt(n,e))return;let s=Rt(n,e);try{await V.access(s);return}catch{}await V.mkdir(v.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ds(n){Ns.test(n)&&await V.rm(v.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as Xs from"fs/promises";import*as Pt from"path";import{z as E}from"zod";import*as qs from"fs";import*as X from"fs/promises";import*as Ie from"path";import{spawn as zs}from"child_process";import{Readable as Wi}from"stream";function le(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function vn(n,e=le()){if(e)return n[e]}var $e=n=>{process.stderr.write(n+`
|
|
6
|
+
`)};function bn(n){$e=n??(e=>process.stderr.write(e+`
|
|
7
|
+
`))}async function Js(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${le()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=v.agentInstallDir(n.agentId,e,n.version),s=Ie.resolve(t,n.target.cmd);if(await wn(s))return s;if(await Qi({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await wn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await X.chmod(s,493).catch(()=>{}),s}async function Qi(n){await X.mkdir(Ie.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{$e(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await Vi({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});$e(`hydra-acp: extracting ${n.agentId}`),Fe(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await Gi(t,e),await X.unlink(t).catch(()=>{});try{await X.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await wn(n.installDir)){await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Fe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}$e(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Fe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Fe(n,e){if(n)try{n(e)}catch{}}async function Vi(n){let e=Ki(n.url),t=Ie.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),o=qs.createWriteStream(t),i=Wi.fromWeb(s.body);Fe(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,c=Date.now(),d=0,p=2e3,l=150;return i.on("data",u=>{a+=u.length;let f=Date.now();f-d>=l&&(d=f,Fe(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),f-c>=p&&(c=f,$e(Ls(n.agentId,a,r)))}),await new Promise((u,f)=>{i.on("error",f),o.on("error",f),o.on("finish",()=>u()),i.pipe(o)}),$e(Ls(n.agentId,a,r,!0)),Fe(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Ls(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function Ki(n){let e=new URL(n);return Ie.posix.basename(e.pathname)||"archive"}async function Gi(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await yn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await Yi("unzip")){await yn("unzip",["-q",n,"-d",e]);return}await yn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function yn(n,e){return new Promise((t,s)=>{let r=zs(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(o,i)=>{if(o===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function Yi(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=zs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function wn(n){try{return await X.access(n),!0}catch{return!1}}import*as te from"fs/promises";import*as pe from"path";import{spawn as Xi}from"child_process";var Sn=n=>{process.stderr.write(n+`
|
|
8
|
+
`)};function kn(n){Sn=n??(e=>process.stderr.write(e+`
|
|
9
|
+
`))}async function Qs(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=v.agentNpmInstallDir(n.agentId,e,n.version),s=sa(n.packageSpec),r=ra(s),o={installDir:t,packageName:s,hint:n.bin,basename:r},i=pe.join(t,"node_modules",".bin",n.bin);if(await Me(i))return i;if(await Me(t)){let l=await Ws(o);if(l)return l.binPath}await Zi({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Ws(o);if(a)return a.binPath;let c=await Ks(t,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],p=d.length>0?` (package declares bins: ${d.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${p}`)}async function Zi(n){await te.mkdir(pe.dirname(n.installDir),{recursive:!0});let e=await te.mkdtemp(`${n.installDir}.partial-`);try{Sn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),In(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await na({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await te.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Me(n.installDir)){await te.rm(e,{recursive:!0,force:!0}).catch(()=>{}),In(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Sn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),In(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await te.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function In(n,e){if(n)try{n(e)}catch{}}var ea=5,ta=25;function na(n){return Vs(n,0)}async function Vs(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=Xi("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),o.on("exit",(a,c)=>{if(a===0){t();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,p=i.trim();s(new Error(p?`npm install ${n.packageSpec} failed (${d})
|
|
10
|
+
stderr: ${p}`:`npm install ${n.packageSpec} failed (${d})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<ea)return await new Promise(r=>setTimeout(r,ta*(e+1))),Vs(n,e+1);throw t}}function sa(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function ra(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Ks(n,e){let t=pe.join(n,"node_modules",e,"package.json");try{let s=await te.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Ws(n){let e=pe.join(n.installDir,"node_modules",".bin"),t=pe.join(e,n.hint);if(await Me(t))return{binName:n.hint,binPath:t};let s=await Ks(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=pe.join(e,o);if(await Me(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[n.hint,n.basename])if(r.includes(o)){let i=pe.join(e,o);if(await Me(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let r=pe.join(e,n.basename);if(await Me(r))return{binName:n.basename,binPath:r}}}async function Me(n){try{return await te.access(n),!0}catch{return!1}}var oa=E.object({package:E.string(),bin:E.string().optional(),args:E.array(E.string()).optional(),env:E.record(E.string()).optional()}),Oe=E.object({archive:E.string().url().optional(),cmd:E.string().optional(),args:E.array(E.string()).optional(),env:E.record(E.string()).optional()}),ia=E.object({"darwin-aarch64":Oe.optional(),"darwin-x86_64":Oe.optional(),"linux-aarch64":Oe.optional(),"linux-x86_64":Oe.optional(),"windows-x86_64":Oe.optional(),"windows-aarch64":Oe.optional()}),aa=E.object({package:E.string(),args:E.array(E.string()).optional(),env:E.record(E.string()).optional()}),da=E.object({command:E.string(),args:E.array(E.string()).optional(),env:E.record(E.string()).optional()}),ca=E.object({command:E.string().optional(),url:E.string().optional(),description:E.string().optional()}),ua=E.object({npx:oa.optional(),binary:ia.optional(),uvx:aa.optional(),exec:da.optional()}),la=E.object({id:E.string(),name:E.string(),version:E.string().optional(),description:E.string().optional(),authors:E.array(E.string()).optional(),license:E.string().optional(),icon:E.string().optional(),repository:E.string().optional(),website:E.string().optional(),distribution:ua,onboarding:ca.optional(),requiredEnv:E.array(E.string().min(1)).optional()}),Gs=E.object({version:E.string(),agents:E.array(la),extensions:E.array(E.unknown()).optional()}),nt=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(i=>i.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(i=>i.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(i=>An(i)===e);return o?this.applyOverride(o):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:Y(t.command??e),args:t.args?.map(Y),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:pa(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=Gs.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(v.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Gs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ie(v.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function pa(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function An(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function He(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await Cn(i),source:s.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function Cn(n){let e=le();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=vn(n.distribution.binary,e);if(s?.cmd){let r=Pt.resolve(v.agentInstallDir(n.id,e,t),s.cmd);if(await Ys(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??An(n)??s.package,o=v.agentNpmInstallDir(n.id,e,t),i=Pt.join(o,"node_modules",".bin",r);if(await Ys(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Ys(n){try{return await Xs.access(n),!0}catch{return!1}}async function se(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??An(n)??r.package,a=t.onInstallProgress;return{command:await Qs({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:o,env:r.env??{},version:s}}if(n.distribution.binary){let r=vn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${le()??"this platform"}.`);let o=t.onInstallProgress,i=await Js({agentId:n.id,version:s,target:r,onProgress:o?c=>o({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as ya}from"child_process";import*as $t from"fs";import*as pr from"path";var S={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as D}from"zod";var Zs=D.object({protocolVersion:D.number().optional(),clientCapabilities:D.record(D.unknown()).optional(),clientInfo:D.object({name:D.string(),version:D.string().optional()}).optional()}),fa=D.enum(["full","pending_only","none","after_message"]),er=D.object({cwd:D.string(),mcpServers:D.array(D.unknown()).optional(),_meta:D.record(D.unknown()).optional()}),tr=D.object({upstreamSessionId:D.string(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),agentArgs:D.array(D.string()).optional()}),nr=D.object({sessionId:D.string(),historyPolicy:fa.default("full"),afterMessageId:D.string().optional(),clientId:D.string().optional(),clientInfo:D.object({name:D.string(),version:D.string().optional()}).optional(),_meta:D.record(D.unknown()).optional()});import{z as T}from"zod";var sr=T.object({sessionId:T.string()}),rr=T.object({cwd:T.string().optional(),cursor:T.string().optional()}),xn=T.object({used:T.number().optional(),size:T.number().optional(),costAmount:T.number().optional(),costCurrency:T.string().optional()}),Rl=T.object({sessionId:T.string(),upstreamSessionId:T.string().optional(),cwd:T.string(),title:T.string().optional(),agentId:T.string().optional(),currentModel:T.string().optional(),currentUsage:xn.optional(),importedFromMachine:T.string().optional(),importedFromUpstreamSessionId:T.string().optional(),parentSessionId:T.string().optional(),forkedFromSessionId:T.string().optional(),forkedFromMessageId:T.string().optional(),originatingClient:T.object({name:T.string(),version:T.string().optional()}).optional(),interactive:T.boolean().optional(),priority:T.number().int().nonnegative().optional(),updatedAt:T.string(),attachedClients:T.number().int().nonnegative(),status:T.enum(["live","cold"]).default("live"),busy:T.boolean().default(!1),awaitingInput:T.boolean().default(!1),compactionState:T.any().optional(),_meta:T.record(T.unknown()).optional()}),ma=T.object({sessionId:T.string(),cwd:T.string(),title:T.string().optional(),updatedAt:T.string().optional(),_meta:T.record(T.unknown()).optional()}),El=T.object({sessions:T.array(ma),nextCursor:T.string().optional()});function Tt(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function or(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:st(n._meta,Tt(n))};return n.title!==void 0&&(e.title=n.title),e}var rt="hydra-acp";function ga(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function ot(n){if(!n)return{};let e=n[rt];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=tr.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=xn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:i.messageId,originator:c,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="live"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=ga(t.env);r!==void 0&&(s.env=r)}return s}function st(n,e){return{...n??{},[rt]:e}}import{z as C}from"zod";var ir=C.object({sessionId:C.string(),prompt:C.array(C.unknown()),_meta:C.record(C.unknown()).optional()}),_t=C.object({sessionId:C.string()}),ar=C.object({clientId:C.string(),name:C.string().optional(),version:C.string().optional()}),Ol=C.object({sessionId:C.string(),messageId:C.string(),originator:ar,prompt:C.array(C.unknown()),position:C.number().int().nonnegative(),queueDepth:C.number().int().positive(),enqueuedAt:C.number()}),Hl=C.object({sessionId:C.string(),messageId:C.string(),prompt:C.array(C.unknown())}),Nl=C.object({sessionId:C.string(),messageId:C.string(),reason:C.enum(["started","cancelled","abandoned"])}),dr=C.object({sessionId:C.string(),messageId:C.string()}),jl=C.object({cancelled:C.boolean(),reason:C.enum(["ok","not_found","already_running"])}),cr=C.object({sessionId:C.string(),messageId:C.string(),prompt:C.array(C.unknown())}),Bl=C.object({updated:C.boolean(),reason:C.enum(["ok","not_found","already_running"])}),ur=C.object({sessionId:C.string(),targetMessageId:C.string(),prompt:C.array(C.unknown()),replaceQueue:C.boolean().optional(),onTargetCompleted:C.enum(["reject","send_anyway"]).optional()}),Ul=C.object({amended:C.boolean(),reason:C.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:C.string().optional()}),Dl=C.object({sessionId:C.string(),cancelledMessageId:C.string(),newMessageId:C.string(),prompt:C.array(C.unknown()),originator:ar,amendedAt:C.number()});import{z as Se}from"zod";var zl=Se.object({agentId:Se.string(),version:Se.string(),source:Se.enum(["binary","npm"]),phase:Se.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Se.number().optional(),totalBytes:Se.number().optional(),packageSpec:Se.string().optional()}),lr="hydra-acp/agents/install_progress";function Mn(n,e){let t="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
|
|
11
|
+
`);for(;c!==-1;){let d=t.slice(0,c).trim();if(t=t.slice(c+1),d.length>0)try{let p=JSON.parse(d);for(let l of s)l(p)}catch(p){for(let l of s)l({jsonrpc:"2.0",id:null,error:{code:S.ParseError,message:`Failed to parse ndjson line: ${p.message}`}})}c=t.indexOf(`
|
|
12
|
+
`)}}),n.on("end",()=>i()),n.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let c=JSON.stringify(a)+`
|
|
13
|
+
`;await new Promise((d,p)=>{e.write(c,l=>{if(l){p(l);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as ha}from"nanoid";var Rn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Re=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new Rn;let s=ha(),r={jsonrpc:"2.0",id:s,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(s,{resolve:c=>i(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:S.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??S.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}};var wa=4096,he=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??wa,this.killEscalationMs=e.killEscalationMs??va,this.logger=e.logger,this.fileLog=ba(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
|
|
14
|
+
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Mn(t.stdout,t.stdin);this.connection=new Re(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
|
|
15
|
+
`),this.connection.fail(new Error(o))}),t.on("exit",(r,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
16
|
+
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${r} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${o}`)}for(let i of this.exitHandlers)i(r,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
17
|
+
stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=ya(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
|
|
18
18
|
`),this.logger?.info(`agent ${this.agentId} pid=${this.child.pid} kill requested signal=${e}`),await this.connection.close().catch(()=>{}),this.signalProcessGroup(e),await this.waitForExit(this.killEscalationMs),!this.exited&&(this.writeLog(`--- kill escalating signal=SIGKILL time=${new Date().toISOString()} ---
|
|
19
|
-
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},$o=2e3;function Fo(n){try{let e=w.agentLogFile(n);St.mkdirSync(Ls.dirname(e),{recursive:!0});let t=St.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Me from"fs/promises";import*as $t from"os";import*as it from"path";import{customAlphabet as Wa}from"nanoid";import{customAlphabet as Ks}from"nanoid";import*as Js from"fs/promises";var Oo=64*1024*1024,No=1*1024*1024,Ne=64*1024,jo=6e4,Ho=100,Bo=1e3,Uo=64*1024,Do=256*1024,qs=20;function Lo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var kt=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??Oo,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(No,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Ne));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,jo));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Lo(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Ho,Bo)),f=Math.max(1,Math.min(e.maxBytes??Uo,Do)),p=Math.max(0,Math.min(e.contextBefore??0,qs)),g=Math.max(0,Math.min(e.contextAfter??0,qs)),m=[],h=[],y=[],A=0,k=!1,b=0,N=0,j=(R,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:R,line:P}),D.remaining--,A+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==l&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let he of D.before)A+=he.line.length}A+=P.length,m.push(D),g>0&&y.push({match:D,remaining:g})}if(p>0)for(h.push({cursor:R,line:P});h.length>p;)h.shift();let B=m.length>=u&&y.length===0,q=A>=f;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(b,R).toString("utf8"),H=r+b;if(b=R+1,N=b,j(H,P)){k=!0;break}}if(!k&&b<o.length&&this.closed){let R=o.subarray(b).toString("utf8"),P=r+b;j(P,R)&&(k=!0),N=o.length}let K=Math.min(r+N,this.writeCursor),J={matches:m,truncated:k,nextCursor:K,scannedBytes:N};return i>0&&(J.gap=i),this.closed&&K>=this.writeCursor&&(J.eof=!0),J}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Js.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var At=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],Il=new Map(At.map(n=>[n.verb,n]));function zs(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function je(n,e){return In(n,e.map(t=>t.modelId))}function In(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=zs(n),s=e.filter(i=>zs(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function Ws(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=bn(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(l);u?u.push(...c.content):t.set(l,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=bn(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Jo(r,i.outIndex,qo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&t.has(u)?zo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Wo(f)&&(f=Qo(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function bn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function qo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Jo(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function zo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Wo(n){let t=bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Qo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ce from"fs/promises";async function Ke(n,e){let t=w.queueFile(n);if(e.length===0){await ce.unlink(t).catch(()=>{});return}await ce.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
19
|
+
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},va=2e3;function ba(n){try{let e=v.agentLogFile(n);$t.mkdirSync(pr.dirname(e),{recursive:!0});let t=$t.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Pe from"fs/promises";import*as qt from"os";import*as ht from"path";import{customAlphabet as Ed}from"nanoid";async function Ne(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=n;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(c=>c.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function je(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:o}=n;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as Cr}from"nanoid";import*as mr from"fs/promises";var Ia=64*1024*1024,Sa=1*1024*1024,Be=64*1024,ka=6e4,Aa=100,Ca=1e3,xa=64*1024,Ma=256*1024,fr=20;function Ra(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ft=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??Ia,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Sa,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Be));if(s===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 c=Math.min(a,s),p={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return o>0&&(p.gap=o),this.closed&&r+c>=this.writeCursor&&(p.eof=!0),p}tail(e){let t=Math.max(0,Math.min(e,Be)),s=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,Be)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,ka));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,o=0;s!==void 0&&s<t&&(o=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Ra(e.pattern),c),p=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??Aa,Ca)),u=Math.max(1,Math.min(e.maxBytes??xa,Ma)),f=Math.max(0,Math.min(e.contextBefore??0,fr)),m=Math.max(0,Math.min(e.contextAfter??0,fr)),g=[],h=[],y=[],w=0,I=!1,A=0,k=0,M=(U,H)=>{for(let z of y)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:U,line:H}),z.remaining--,w+=H.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(d.test(H)!==p&&g.length<l){let z={cursor:U,line:H};if(f>0&&h.length>0){z.before=h.slice();for(let de of z.before)w+=de.line.length}w+=H.length,g.push(z),m>0&&y.push({match:z,remaining:m})}if(f>0)for(h.push({cursor:U,line:H});h.length>f;)h.shift();let R=g.length>=l&&y.length===0,q=w>=u;return R||q};for(let U=0;U<i.length;U++){if(i[U]!==10)continue;let H=i.subarray(A,U).toString("utf8"),$=r+A;if(A=U+1,k=A,M($,H)){I=!0;break}}if(!I&&A<i.length&&this.closed){let U=i.subarray(A).toString("utf8"),H=r+A;M(H,U)&&(I=!0),k=i.length}let P=Math.min(r+k,this.writeCursor),N={matches:g,truncated:I,nextCursor:P,scannedBytes:k};return o>0&&(N.gap=o),this.closed&&P>=this.writeCursor&&(N.eof=!0),N}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<t&&this.storage.copy(s,o,0,t-o),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>mr.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var Ot=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],lp=new Map(Ot.map(n=>[n.verb,n]));function gr(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Ue(n,e){return En(n,e.map(t=>t.modelId))}function En(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=gr(n),s=e.filter(o=>gr(o)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}function hr(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=Pn(c);if(d?.sessionUpdate!=="tool_call_update")continue;let p=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(p!==void 0&&(e.set(p,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(p,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let l=t.get(p);l?l.push(...d.content):t.set(p,[...d.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=Pn(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),o=null;continue}let p=d.sessionUpdate;if(p==="agent_message_chunk"||p==="agent_thought_chunk"||p==="user_message_chunk"){o&&o.kind===p?Pa(r,o.outIndex,Ea(d.content)):(r.push(c),o={outIndex:r.length-1,kind:p});continue}if(o=null,p==="tool_call_update"){let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&e.get(l)!==a)continue;let u=l!==void 0&&t.has(l)?Ta(c,t.get(l)??[]):c;l!==void 0&&s.has(l)&&!_a(u)&&(u=$a(u,s.get(l))),r.push(u);continue}if(p==="plan"){i!==null?r[i]=c:(r.push(c),i=r.length-1);continue}(p==="prompt_received"||p==="turn_complete")&&(i=null),r.push(c)}return r}function Pn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ea(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Pa(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...s,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function Ta(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function _a(n){let t=Pn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function $a(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var yr=`[older history truncated]
|
|
20
|
+
`,Fa=["file_path","path","command","pattern","query"];function De(n,e={}){let t=e.maxChars??4e5,s=[],r="",o=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let i of n){if(i.method!=="session/update")continue;let c=i.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){o();let p=_n(c.prompt).trim();p.length>0&&s.push(`User: ${p}`)}else if(d==="agent_message_chunk"){let p=$n(c.content);p.length>0&&(r+=p)}else d==="tool_call"?(o(),s.push(Tn(c))):d==="turn_complete"&&o()}return o(),ja(s.join(`
|
|
21
|
+
`),t)}function Tn(n){let e=Oa(n),t=Ha(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Oa(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Ha(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Fa){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Na(r,200)}`)}return t}function _n(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function $n(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Na(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function ja(n,e){if(n.length<=e)return n;let t=n.split(`
|
|
22
|
+
`);for(;t.length>0;){let s=yr+t.join(`
|
|
23
|
+
`);if(s.length<=e)return s;t.shift()}return yr}var Ba="(untitled)";function vr(n){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??Ba}`),n.synopsis.goal!==void 0&&n.synopsis.goal.trim().length>0&&e.push(`[Goal] ${n.synopsis.goal}`),n.synopsis.outcome!==void 0&&n.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${n.synopsis.outcome}`);let t=it("Open threads",n.synopsis.open_threads);t.length>0&&e.push(t);let s=it("Decisions",n.synopsis.decisions);s.length>0&&e.push(s);let r=it("File edit intentions",n.synopsis.file_edit_intentions);r.length>0&&e.push(r);let o=it("Unresolved errors",n.synopsis.unresolved_errors);o.length>0&&e.push(o);let i=it("Tool state",n.synopsis.tool_state);i.length>0&&e.push(i);let a=wr(n.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=wr(n.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=Ua(n.tail,n.tailK);return e.push("--- begin recent turns (verbatim, last "+n.tailK+") ---"),d.length>0&&e.push(d),e.push("--- end recent turns ---"),e.push(""),e.push("(Hydra has compacted earlier conversation. Detail is retrievable via the hydra-recall tools if you need to look up specifics. Acknowledge briefly and wait for the next user message.)"),e.join(`
|
|
24
|
+
`)}function it(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
|
|
25
|
+
`)}`}function wr(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Ua(n,e){if(n.length===0||e<=0)return"";let t=Da(n);if(t.length===0)return"";let s=t.slice(-e),r=[];for(let o of s)if(o.user.length>0&&r.push("User: "+o.user),o.agent.length>0&&r.push("Assistant: "+o.agent),o.tools.length>0)for(let i of o.tools)r.push(i);return r.join(`
|
|
26
|
+
`)}function Da(n){let e=[],t=null;for(let s of n){if(s.method!=="session/update")continue;let o=s.params?.update;if(!o||typeof o.sessionUpdate!="string")continue;let i=o.sessionUpdate;if(i==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:_n(o.prompt).trim(),agent:"",tools:[]};else if(i==="agent_message_chunk"&&t!==null){let a=$n(o.content);a.length>0&&(t.agent+=a)}else i==="tool_call"&&t!==null?t.tools.push(Tn(o)):i==="turn_complete"&&t!==null&&(e.push(t),t=null)}return t!==null&&t.user.length>0&&e.push(t),e}import*as fe from"fs/promises";async function at(n,e){let t=v.queueFile(n);if(e.length===0){await fe.unlink(t).catch(()=>{});return}await fe.mkdir(v.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
20
27
|
`)+`
|
|
21
|
-
`;await
|
|
22
|
-
`))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Vs(n){let e=w.queueFile(n);await ce.unlink(e).catch(()=>{})}import*as tr from"fs/promises";var Xs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Zs=Ks(Xs,16),Gs=Ks(Xs,16),ge="hydra_session_";function He(){return`m_${Zs()}`}function er(n){return n.startsWith(ge)?n.slice(ge.length):n}var Vo=1e3,Sn=300*1e3,Go=64,xe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;currentModel;currentMode;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${ge}${Zs()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Vo,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){na(this.internalPromptCapture,t);return}this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>this.handlePermissionRequest(t)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0){let r=e,i=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(t.has(c.name)||!c.intercepts.has("response:session/update"))continue;let l=`t_${Gs()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return;if(f==="processing"){let p=d,g=i,m=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...m,c.name]),p+1).then(()=>h()).catch(()=>h()))},Sn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(l,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:m,side:"response"})});return}t.add(c.name)}let o=sa(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=ta(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.inFlightPermissions.size>0}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}attach(e,t,s={}){if(this.closed)throw X(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw X(new Error(`client ${e.clientId} is already attached`),I.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=o=>t.raw?o:Ws(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?An(r,t.afterMessageId):-1;return o<0?{entries:[...i,...s(r)],appliedPolicy:"full"}:{entries:[...i,...s(r.slice(o+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let t of this.inFlightPermissions)t.addClient(e)}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw X(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw X(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=He();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ye((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Be(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:He()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Go;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw X(new Error("client not attached"),I.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=He(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=He(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw X(new Error("client not attached"),I.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${Gs()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??kn(e);if(f==="processing"){let p=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:kn(e))))},Sn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(l,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Sn,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:kn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Be((e??{}).prompt),r=xn(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=Ue(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ue(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(o.id==="mode"){let a=Xe(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=Ue(o.options);if(d.length>0){let c=Xe(o.options),l=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=l,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:g,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let t={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=t;for(let s of this.usageHandlers)try{s(t)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Xo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Zo(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),ea(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(!t)return;if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let t=e.trim();if(!t)return;if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:t,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${t} ${s.verb}`:`hydra ${t}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),t.startsWith("hydra-acp-")){let a=t.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(At.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=I.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=At.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(c.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=I.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let u,f=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
28
|
+
`;await fe.writeFile(t,s,"utf8")}async function br(n){let e=v.queueFile(n),t;try{t=await fe.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
|
|
29
|
+
`))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Ir(n){let e=v.queueFile(n);await fe.unlink(e).catch(()=>{})}import*as Er from"fs/promises";var xr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Mr=Cr(xr,16),Sr=Cr(xr,16),La=20,ye="hydra_session_";function Le(){return`m_${Mr()}`}function Rr(n){return n.startsWith(ye)?n.slice(ye.length):n}var qa=1e3,Fn=300*1e3,za=64,Ee=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${ye}${Mr()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.getCompactionStateHook=e.getCompactionState,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??qa,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){Ga(this.internalPromptCapture,t);return}this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>this.handlePermissionRequest(t)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0){let r=e,o=this.injectCumulativeCost(e);for(let c=s;c<this.transformChain.length;c++){let d=this.transformChain[c];if(t.has(d.name)||!d.intercepts.has("response:session/update"))continue;let p=`t_${Sr()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(f){this.logger?.warn(`transformer ${d.name} error on response:session/update: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return;if(u==="processing"){let f=c,m=o,g=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:d.name}),this.runResponseChain(m,new Set([...g,d.name]),f+1).then(()=>h()).catch(()=>h()))},Fn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(p,{resolve:()=>h(),timer:y,transformerName:d.name,method:"session/update",envelope:m,chainIdx:f,originatedBy:g,side:"response"})});return}t.add(d.name)}let i=Ya(o);if(i!==null){this.setAgentAdvertisedCommands(i);return}let a=Ka(o);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.inFlightPermissions.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");let s=this.agentId,r=this.cwd,o=this.agentArgs,i=this.forwardedEnv,a=this.currentModel,c=this.currentMode,d=this.spawnReplacementAgent;if(!d)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],l=await d({agentId:s,cwd:r,agentArgs:o,...i?{forwardedEnv:i}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),await je({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:a,agentReportedModel:l.initialModel,logger:this.logger}),await Ne({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=[];if(this.historyStore)try{u=await this.historyStore.load(this.sessionId)}catch(w){this.logger?.warn(`swapUpstream: historyStore.load failed: ${w.message}`)}let f=vr({synopsis:e.artifact,title:e.title,tail:u,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[]};try{await l.agent.connection.request("session/prompt",{sessionId:l.upstreamSessionId,prompt:[{type:"text",text:f}]})}finally{this.internalPromptCapture=void 0}let m=this.upstreamSessionId,g=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let h=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let w of this.agentChangeHandlers)try{w({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(I){this.logger?.warn(`swapUpstream: agentChange handler failed: ${I.message}`)}if(this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:m,...g!==void 0?{previousSummarizedThroughEntry:g}:{}})}catch(w){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${w.message}`)}await h.kill().catch(()=>{}),this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0});let y=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
30
|
+
Compaction completed.
|
|
31
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}});for(let w of this.clients.values())w.connection.notify("session/update",y).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,p=await s(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(p.agent),await je({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger}),await Ne({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:d,agentReportedMode:p.initialMode,logger:this.logger}),p.agent.connection.drainBuffered("session/update");let l=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await l.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(f){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${f.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=La){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of s){let c=i.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,p=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(p){if(d==="tool_call")r.add(p);else if(d==="tool_call_update"){let l=c.status;(l==="completed"||l==="failed")&&o.add(p)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{})}attach(e,t,s={}){if(this.closed)throw ee(new Error("session is closed"),S.SessionNotFound);if(this.clients.has(e.clientId))throw ee(new Error(`client ${e.clientId} is already attached`),S.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:hr(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!kr(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Hn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...s(o)],appliedPolicy:"full"}:{entries:[...i,...s(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.inFlightPermissions)t.addClient(e)}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw ee(new Error("client not attached"),S.SessionNotFound);if(this.closing)throw ee(new Error("session is closing; new prompts cannot be accepted"),S.SessionClosing);let r=Le();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(ot((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let i of this.interactiveHandlers)try{i(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=qe(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Le()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>za;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw ee(new Error("client not attached"),S.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let c=this.promptQueue.find(p=>p.messageId===r&&p.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let o=Le(),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 d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let s=Le(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw ee(new Error("client not attached"),S.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let p=`t_${Sr()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:p,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${c.name} error on ${d}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return o==="notification"?void 0:l?.payload??On(e);if(u==="processing"){let f=a,m=i,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:c.name}),this.forwardRequest(e,m,new Set([...g,c.name]),f+1,o).then(h).catch(()=>h(o==="notification"?void 0:On(e))))},Fn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(p,{resolve:h,timer:y,transformerName:c.name,method:e,envelope:m,chainIdx:f,originatedBy:g,side:"request",tailKind:o})})}s.add(c.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Fn,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let i=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,i).then(s.resolve).catch(()=>s.resolve(i==="notification"?void 0:On(s.method)))}},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(t,s,i,o)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=qe((e??{}).prompt),r=Nn(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=ze(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=ze(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=i.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(i.id==="mode"){let a=dt(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=i.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),c=ze(i.options);if(c.length>0){let d=dt(i.options),p=d.length>0?d.map(h=>({value:h.id,name:h.name??h.id})):c.map(h=>({value:h.modelId,name:h.name??h.modelId})),l=i.name,u=typeof l=="string"&&l.trim()?l.trim():a,f=i.currentValue,m=typeof f=="string"&&f.trim()?f.trim():p[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=p,typeof f=="string"&&f.trim()&&(h.currentValue=f.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:m,options:p})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let o={};typeof s.costAmount=="number"&&(o.amount=s.costAmount),typeof s.costCurrency=="string"&&(o.currency=s.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Wa(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Qa(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(",")}]`),Va(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:t,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${t} ${s.verb}`:`hydra ${t}`,i={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(i.description=s.description),e.push(i),t.startsWith("hydra-acp-")){let a=t.slice(10);if(a.length>0){let c=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,p={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(p.description=s.description),e.push(p)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let 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(Ot.some(l=>l.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return a?this.runAgentCommandInline(i):this.runAgentCommand(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let l=new Error(`no dispatcher for /hydra verb ${o}`);throw l.code=S.InternalError,l}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let c=`hydra-acp-${o}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,i,t):this.runExtensionCommand(c,i);let d=Ot.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:u}of this.extensionCommands.list())l.has(u)||(d.push(u),l.add(u))}let p=new Error(`unknown /hydra verb: ${o} (known: ${d.join(", ")})`);throw p.code=S.InvalidParams,p}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(m=>m.verb===i)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},p=new Promise(m=>{d=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>d({stopReason:"cancelled",reason:m})});let l,u=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),g=await Promise.race([m,p]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return u=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let f=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return f.length>0?this.emitExtensionReply(f):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
23
32
|
${e}
|
|
24
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let
|
|
33
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",c=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${c}`});e=`Sessions (${t.length}):
|
|
25
34
|
${s.join(`
|
|
26
35
|
`)}`}}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
27
36
|
${e}
|
|
28
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}handleHelpCommand(){let t=this.mergedAvailableCommands().map(r=>{let
|
|
37
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}handleHelpCommand(){let t=this.mergedAvailableCommands().map(r=>{let o=r.description?` ${r.description}`:"";return`\`/${r.name}\`${o}`}),s=t.length>0?`Available commands:
|
|
29
38
|
${t.join(`
|
|
30
39
|
`)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
31
40
|
${s}
|
|
32
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let
|
|
41
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let c=i?o.some(p=>p.modelId===i):!0,d=o.map(p=>{let l=p.modelId===i?"\u25B6 ":" ",u=p.name&&p.name!==p.modelId?` ${p.name}`:"";return`${l}${p.modelId}${u}`});!c&&i&&d.unshift(`\u25B6 ${i}`),a=d.join(`
|
|
33
42
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
34
43
|
${a}
|
|
35
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
44
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Ue(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let o=this.agentAdvertisedModels.map(l=>l.modelId),i=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:o.filter(l=>l.toLowerCase().includes(i)),c=a.length>0?a:o,d=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,p=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
45
|
+
${d}.
|
|
46
|
+
${p}:
|
|
47
|
+
${c.join(`
|
|
39
48
|
`)}
|
|
40
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,
|
|
49
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(d=>d.id===o):!0,c=r.map(d=>{let p=d.id===o?"\u25B6 ":" ",l=d.name&&d.name!==d.id?` ${d.name}`:"";return`${p}${d.id}${l}`});!a&&o&&c.unshift(`\u25B6 ${o}`),i=c.join(`
|
|
41
50
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
42
|
-
${
|
|
43
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(
|
|
51
|
+
${i}
|
|
52
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(o=>o.id).join(", ");throw ee(new Error(`unknown mode: ${t} (known: ${r})`),S.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[2]??"";if(!s){let p=this.buildConfigOptions();if(p.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
44
53
|
_(no config options advertised yet)_
|
|
45
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let
|
|
46
|
-
${
|
|
54
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let l=p.map(u=>Ar(u));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
55
|
+
${l.join(`
|
|
47
56
|
|
|
48
57
|
`)}
|
|
49
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let
|
|
58
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let o=this.buildConfigOptions(),i=o.find(p=>p.id===s);if(!i){let p=o.map(l=>l.id).join(`
|
|
50
59
|
`);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
51
60
|
"${s}" is not a known config option.
|
|
52
61
|
Available options:
|
|
53
|
-
${
|
|
62
|
+
${p}
|
|
54
63
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
55
|
-
${
|
|
56
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=
|
|
57
|
-
${
|
|
58
|
-
${
|
|
59
|
-
${
|
|
64
|
+
${Ar(i)}
|
|
65
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(p=>p.value),c=En(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let p=r.toLowerCase(),l=c.kind==="ambiguous"?c.candidates:a.filter(g=>g.toLowerCase().includes(p)),u=l.length>0?l:a,f=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:l.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=c.kind==="ambiguous"||l.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
66
|
+
${f}.
|
|
67
|
+
${m}:
|
|
68
|
+
${u.join(`
|
|
60
69
|
`)}
|
|
61
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(
|
|
62
|
-
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new kt(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Ne,Ne)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Vs(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>tr.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!Ko(e,r),o=i?ra(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw X(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=ia(s);return new Promise((i,o)=>{let a=!1,d=[],c=0,l,u={addClient:m};this.inFlightPermissions.add(u);let f=this.sessionId,p=h=>{a||(a=!0,this.inFlightPermissions.delete(u),h())},g=h=>h?.code===I.MethodNotFound;function m(h){if(a)return;let y=h.connection.request("session/request_permission",s);d.push({client:h}),c++,y.then(A=>{c--,p(()=>{let k=oa({toolCallId:r,result:A,resolver:h});for(let b of d)b.client.clientId!==h.clientId&&b.client.connection.notify("session/update",{sessionId:f,update:k}).catch(()=>{});i(A)})}).catch(A=>{if(c--,g(A)||(l=A),c===0&&!a){let k=l??X(new Error("no client handled permission request"),I.PermissionDenied);p(()=>o(k))}})}for(let h of t)m(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:He(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ke(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Be(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
63
|
-
`)&&t.startsWith("/")?t.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(t):s==="/model"?i=await this.handleModelCommand(t):i=await this.handleSlashCommand(t,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function X(n,e){return n.code=e,n}var Yo=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function Ko(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Yo.has(s)}function Xo(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Zo(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function ea(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Ue(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Xe(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function ta(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function na(n,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&n.chunks.push(r.text)}function sa(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function ra(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:He()}}}function An(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function ia(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function oa(n){let e=aa(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=da(n.resolver),t}function aa(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function da(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Be(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function kn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Ys(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
|
|
70
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[]};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(!e)throw ee(new Error("/hydra agent requires an agent id"),S.InvalidParams);if(e===this.agentId)throw ee(new Error(`already on agent ${e}`),S.InvalidParams);if(!this.spawnReplacementAgent)throw ee(new Error("agent switching not configured for this session"),S.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),o=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(o.agent);let i=this.agent;this.agent=o.agent,this.agentId=e,this.upstreamSessionId=o.upstreamSessionId,this.agentMeta=o.agentMeta,this.agentCapabilities=o.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=o.initialModel,this.currentMode=o.initialMode,this.setAgentAdvertisedModels(o.initialModels??[]),this.setAgentAdvertisedModes(o.initialModes??[]),await i.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let c of this.agentChangeHandlers)try{c(a)}catch{}return{stopReason:"end_turn"}}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw ee(new Error("agent restart not configured for this session"),S.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),t=this._summarizedThroughEntry;if(e==null&&t==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
|
|
71
|
+
`)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ee(new Error("session is closing"),S.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let i={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let l=(d.params??{}).update;if(!l||l._meta?.["hydra-acp"]?.synthetic)continue;let f=l.sessionUpdate;if(f==="prompt_received"){let m=qe(l.prompt);m&&s.push({speaker:"user",text:m})}else if(f==="agent_message_chunk"){let g=l.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(f==="tool_call"||f==="tool_call_update"){let m=l.status,g=l.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let o=[],i;for(let d of s)i&&i.speaker===d.speaker?i.text+=d.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:d.speaker,text:d.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.`,c=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,c,"","--- begin transcript ---",...o,"--- end transcript ---"].join(`
|
|
72
|
+
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Ft(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??Be,Be)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(i.nextCursor,s);(c==="data"||c==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=S.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ir(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),o!==void 0&&r.drainFileWrites().then(()=>Er.unlink(o).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),o=!kr(e,r),i=o?Xa(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ee(new Error("no clients attached to handle permission request"),S.PermissionDenied);let s=this.rewriteForClient(e),r=Za(s);return new Promise((o,i)=>{let a=!1,c=[],d=0,p,l={addClient:g};this.inFlightPermissions.add(l);let u=this.sessionId,f=h=>{a||(a=!0,this.inFlightPermissions.delete(l),h())},m=h=>h?.code===S.MethodNotFound;function g(h){if(a)return;let y=h.connection.request("session/request_permission",s);c.push({client:h}),d++,y.then(w=>{d--,f(()=>{let I=ed({toolCallId:r,result:w,resolver:h});for(let A of c)A.client.clientId!==h.clientId&&A.client.connection.notify("session/update",{sessionId:u,update:I}).catch(()=>{});o(w)})}).catch(w=>{if(d--,m(w)||(p=w),d===0&&!a){let I=p??ee(new Error("no client handled permission request"),S.PermissionDenied);f(()=>i(I))}})}for(let h of t)g(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Le(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],o={clientId:e.clientId};e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version);let i=this.parseQueuePosition(t);return new Promise((a,c)=>{let d={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},p=this.insertEntryAt(d,i);this.persistRewrite(),this.broadcastQueueAdded(d,{position:p}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),s+o+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>at(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=qe(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
73
|
+
`)&&t.startsWith("/")?t.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let o;return s==="/sessions"?o=await this.handleSessionsCommand():s==="/help"?o=await this.handleHelpCommand():s==="/mode"?o=await this.handleModeCommand(t):s==="/model"?o=await this.handleModelCommand(t):o=await this.handleSlashCommand(t,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(o){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function ee(n,e){return n.code=e,n}var Ja=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]);function kr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Ja.has(s)}function Wa(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Qa(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Va(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function ze(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function dt(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function Ka(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function Ga(n,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&n.chunks.push(r.text)}function Ya(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function Xa(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:Le()}}}function Hn(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function Za(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function ed(n){let e=td(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=nd(n.resolver),t}function td(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function nd(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function qe(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function On(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Ar(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let o=r.value===n.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
|
|
64
74
|
${s.join(`
|
|
65
|
-
`)}`}function
|
|
75
|
+
`)}`}function Nn(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as We from"fs/promises";import*as _p from"path";import{customAlphabet as rd}from"nanoid";import{z as x}from"zod";import{z as L}from"zod";var Pr=L.object({status:L.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:L.number(),iter:L.number().int().nonnegative().optional(),attempts:L.number().int().nonnegative().optional(),lastError:L.string().optional(),worker:L.object({upstreamSessionId:L.string(),pid:L.number().int().nonnegative()}).optional()}),ct=L.object({goal:L.string().optional(),outcome:L.string().optional(),files_touched:L.array(L.string()).optional(),tools_used:L.array(L.string()).optional(),rejected_approaches:L.array(L.string()).optional(),open_threads:L.array(L.string()).optional(),decisions:L.array(L.string()).optional(),file_edit_intentions:L.array(L.string()).optional(),unresolved_errors:L.array(L.string()).optional(),tool_state:L.array(L.string()).optional()}),Tr=200,jn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
66
76
|
{
|
|
67
77
|
"title": "short summary, max 80 chars",
|
|
68
78
|
"synopsis": {
|
|
@@ -72,41 +82,61 @@ ${s.join(`
|
|
|
72
82
|
"open_threads": ["work started but not finished"]
|
|
73
83
|
}
|
|
74
84
|
}
|
|
75
|
-
Use empty arrays/strings where a field doesn't apply.`;function
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
85
|
+
Use empty arrays/strings where a field doesn't apply.`;function _r(n){let e=n.trim();if(e.length===0)return;let t=Je(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Je(e.slice(o,i+1)))}if(t===void 0){let o=Fr(e);o!==void 0&&(t=Je(o))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let o=s.title.trim();o.length>0&&(r.title=o.slice(0,Tr))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=ct.safeParse(s.synopsis);o.success&&sd(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var Bn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
86
|
+
{
|
|
87
|
+
"title": "short summary, max 80 chars",
|
|
88
|
+
"goal": "the user's original ask",
|
|
89
|
+
"outcome": "what was concluded or shipped",
|
|
90
|
+
"rejected_approaches": ["things tried and abandoned"],
|
|
91
|
+
"open_threads": ["work started but not finished"],
|
|
92
|
+
"decisions": ["key architectural or implementation decisions"],
|
|
93
|
+
"file_edit_intentions": ["files planned to be edited"],
|
|
94
|
+
"unresolved_errors": ["errors left open at session end"],
|
|
95
|
+
"tool_state": ["runtime state relevant for recall"]
|
|
96
|
+
}
|
|
97
|
+
Use empty arrays/strings where a field doesn't apply.`;function $r(n){let e=n.trim();if(e.length===0)return;let t=Je(e);if(t===void 0){let d=e.indexOf("{"),p=e.lastIndexOf("}");d>=0&&p>d&&(t=Je(e.slice(d,p+1)))}if(t===void 0){let d=Fr(e);d!==void 0&&(t=Je(d))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Tr))}let o={},i=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let p=s[d].trim();p.length>0&&(o[d]=p,i=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let p=s[d],l=L.array(L.string()).safeParse(p);l.success&&p.length>0&&(o[d]=l.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Je(n){try{return JSON.parse(n)}catch{return}}function Fr(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let o=e;o<n.length;o++){let i=n[o];if(s){r?r=!1:i==="\\"?r=!0:i==='"'&&(s=!1);continue}if(i==='"'){s=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function sd(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var od="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",id=rd(od,16),ad="hydra_lineage_";function ut(){return`${ad}${id()}`}var Dn=x.object({name:x.string(),description:x.string().optional()}),Ln=x.object({id:x.string(),name:x.string().optional(),description:x.string().optional()}),dd=x.object({modelId:x.string(),name:x.string().optional(),description:x.string().optional()}),qn=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional(),cumulativeCost:x.number().optional()}),zn=x.object({name:x.string(),version:x.string().optional()}),cd=x.object({previousUpstreamSessionId:x.string(),previousSummarizedThroughEntry:x.number().int().nonnegative().optional()}),ud=x.object({version:x.literal(1),sessionId:x.string(),lineageId:x.string().optional(),upstreamSessionId:x.string(),importedFromSessionId:x.string().optional(),importedFromUpstreamSessionId:x.string().optional(),importedFromMachine:x.string().optional(),agentId:x.string(),cwd:x.string(),title:x.string().optional(),synopsis:ct.optional(),compactionState:Pr.optional(),rollbackBreadcrumb:cd.optional(),summarizedThroughEntry:x.number().int().nonnegative().optional(),agentArgs:x.array(x.string()).optional(),currentModel:x.string().optional(),currentMode:x.string().optional(),currentUsage:qn.optional(),agentCommands:x.array(Dn).optional(),agentModes:x.array(Ln).optional(),agentModels:x.array(dd).optional(),pendingHistorySync:x.boolean().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:zn.optional(),interactive:x.boolean().optional(),priority:x.number().int().nonnegative().optional(),forwardedEnv:x.record(x.string(),x.string()).optional(),createdAt:x.string(),updatedAt:x.string()}),Un=/^[A-Za-z0-9_-]+$/;function ld(n){if(!Un.test(n))throw new Error(`unsafe session id: ${n}`)}var Ht=class{async write(e){ld(e.sessionId);let t={version:1,...e};await ie(v.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Un.test(e))return;let t=await ue(v.sessionFile(e));if(t!==void 0)try{return ud.parse(t)}catch{return}}async delete(e){if(Un.test(e)){try{await We.unlink(v.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await We.rmdir(v.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await We.readdir(v.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}};function Jn(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var pd=me.object({version:me.literal(1),agentId:me.string(),upstreamSessionId:me.string(),deletedAt:me.string(),upstreamUpdatedAt:me.string().optional(),cwd:me.string().optional(),title:me.string().optional(),reason:me.enum(["user","expired"]).optional(),interactive:me.boolean().optional()}),Nt=class{async add(e){let t={version:1,...e};await ie(v.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(v.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=v.tombstoneFile(e,t),r=await ue(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return pd.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(v.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(v.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await we.readdir(v.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let t;try{t=await we.readdir(v.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function Or(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as Vr from"fs/promises";import{fileURLToPath as fd}from"url";import*as lt from"path";import*as jt from"fs";function md(){try{let n=lt.dirname(fd(import.meta.url));for(let e=0;e<8;e+=1){let t=lt.join(n,"package.json");if(jt.existsSync(t)){let r=JSON.parse(jt.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=lt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var K=md(),Bt="hydra-acp-cat";var gd=12e4;async function Nr(n,e,t){let s=n.timeoutMs??gd,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),d=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),p=d.sessionId;if(typeof p!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(p,r.pid),n.modelId){let m=yd(d);if(m.size===0||m.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:p,modelId:n.modelId})}catch(g){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${g.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let l=[];r.connection.onNotification("session/update",m=>{let g=hd(m);g.length>0&&l.push(g)}),await r.connection.request("session/prompt",{sessionId:p,prompt:[{type:"text",text:e}]});let u=l.join(""),f=t(u);if(!f){let m=JSON.stringify(u.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${u.length} preview=${m})`);let g=u.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${u.length} chars): ${g}${u.length>120?"\u2026":""}`)}return f})();return await new Promise((c,d)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),c(void 0)},s),o.unref?.(),a.then(p=>{o&&clearTimeout(o),i||c(p)},p=>{o&&clearTimeout(o),i||d(p)})})}catch(a){let c=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function jr(n){let e=De(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
|
|
98
|
+
|
|
99
|
+
${e}
|
|
100
|
+
|
|
101
|
+
${jn}`:`${t}
|
|
102
|
+
|
|
103
|
+
${jn}`;return Nr(n,s,_r)}async function Br(n){let e=De(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
|
|
104
|
+
|
|
105
|
+
${e}
|
|
106
|
+
|
|
107
|
+
${Bn}`:`${t}
|
|
80
108
|
|
|
81
|
-
${Cn}`:Cn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let f=c.join(""),p=sr(f);return p||n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse as snapshot JSON (replyLen=${f.length} preview=${JSON.stringify(f.slice(0,200))})`),p})();return await new Promise((o,a)=>{s=setTimeout(()=>{r=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${e}ms`),o(void 0)},e),s.unref?.(),i.then(d=>{s&&clearTimeout(s),r||o(d)},d=>{s&&clearTimeout(s),r||a(d)})})}catch(i){n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${i.message}`);return}finally{s&&clearTimeout(s),t&&await t.kill().catch(()=>{})}}function Pa(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function Ta(n){let e=new Set;ar(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&ar(e,t.availableModels),e}function ar(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function _a(n){let e=new Map;for(let t of pr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function lr(n){return _a(n).map(e=>e.name)}function $a(n){let e=new Map;for(let t of pr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function fr(n){return $a(n).map(e=>e.path)}function pr(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:cr(i),paths:new Set},e.set(d,c)):c.toolName=cr(i);for(let l of ur(i.rawInput,i.locations))c.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of ur(i.rawInput,i.locations))a.paths.add(d)}return e}function cr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function ur(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Fa=2,Et=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Fa}opts;queued=new Set;inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.queued.has(e)||this.inflight.has(e)||(this.queued.add(e),this.drain())}size(){return{queued:this.queued.size,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued.clear(),await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&this.queued.size>0;){let e=this.queued.values().next().value;if(!e)return;this.queued.delete(e);let t=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,t)}}async runOne(e){try{let t=await this.opts.store.read(e);if(!t){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=t.summarizedThroughEntry;if(r!==void 0&&s.length<=r){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${s.length})`);return}let i=this.opts.synopsisAgent??t.agentId,o=await this.opts.registry.getAgent(i);if(!o){this.opts.logger?.warn(`synopsis: agent ${i} not in registry for session ${e}; skipping`);return}let a=await se(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await gr.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let l=await dr({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!l){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}l.title&&await this.opts.persistTitle(e,l.title);let u=Oa(l.synopsis,s);u&&Na(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!l.title)} fields=${ja(u)}`)):l.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(t){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${t.message}`)}}};function Oa(n,e){let t=fr(e),s=lr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Na(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function ja(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Y from"fs/promises";function mr(n){return n==="summary"?"summary":"inline"}var $n=256;function hr(n,e){return e!=="summary"?n:n.map(Ha)}function Ha(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(yr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=Fn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function Ba(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function yr(n){if(Ba(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Fn(e.text)),typeof e.content=="string"?t.content=Fn(e.content):e.content&&typeof e.content=="object"&&(t.content=yr(e.content)),t}function Fn(n){if(typeof n=="string"&&n.length>$n){let e=n.length-$n;return`${n.slice(0,$n)}\u2026[+${e} chars omitted from summary export]`}return n}var Ua=2048;function wr(n){let e=new Set,t=s=>{if(vr(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function vr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Da(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function jn(n,e){if(!Da(n))return n;let t=n.params,s=t.update,r=await On(s,e);return{...n,params:{...t,update:r}}}async function On(n,e){if(typeof n=="string"){if(n.length<=Ua)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await On(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await On(r,e);return t}return n}async function Ir(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Nn(t,e);return s===t?n:{...n,params:s}}async function Nn(n,e){if(vr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Nn(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await Nn(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var nt=/^[A-Za-z0-9_-]+$/,La=1e3,Pt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??La}async append(e,t){if(nt.test(e))return this.enqueue(e,async()=>{await Y.mkdir(w.sessionDir(e),{recursive:!0});let s=await jn(t,i=>an(e,i)),r=JSON.stringify(s)+`
|
|
82
|
-
`;await
|
|
109
|
+
${Bn}`;return Nr(n,s,$r)}function hd(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function yd(n){let e=new Set;Hr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Hr(e,t.availableModels),e}function Hr(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function wd(n){let e=new Map;for(let t of zr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Lr(n){return wd(n).map(e=>e.name)}function vd(n){let e=new Map;for(let t of zr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function qr(n){return vd(n).map(e=>e.path)}function zr(n){let e=new Map,t=0;for(let s of n){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,d=e.get(c);d===void 0?(d={toolName:Ur(o),paths:new Set},e.set(c,d)):d.toolName=Ur(o);for(let p of Dr(o.rawInput,o.locations))d.paths.add(p);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let c of Dr(o.rawInput,o.locations))a.paths.add(c)}return e}function Ur(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Dr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var bd=2,Ut=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??bd}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]="title",this.drain())}scheduleCompaction(e){if(this.stopped||this.inflight.has(e))return;if(this.queued[e]==="title"){this.queued[e]="compaction";return}this.queued[e]="compaction",this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){try{let s=await this.opts.store.read(e);if(!s){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let r=await this.opts.histories.load(e,{maxEntries:1/0}),o=s.summarizedThroughEntry;if(o!==void 0&&r.length<=o){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${r.length})`);return}let i=t==="compaction"?this.opts.compactionAgent??s.agentId:this.opts.synopsisAgent??s.agentId,a=await this.opts.registry.getAgent(i);if(!a){this.opts.logger?.warn(`synopsis: agent ${i} not in registry for session ${e}; skipping`);return}let c=await se(a,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.compactionAgent===void 0,p=t==="compaction"?this.opts.compactionModel??(d?s.currentModel:void 0):this.opts.synopsisModel,l=v.sessionDir(e);if(await Vr.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${r.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),t==="compaction"){let u=this.opts.compactionMaxIterations??3,f=0,m=o??0,g,h=0,y,w=Date.now();await this.opts.onCompactionStateChange?.(e,{status:"requested",requestedAt:w}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"started",requestedAt:w});try{do{f++,this.opts.logger?.info(`synopsis: compaction iteration ${f} sessionId=${e} historyLen=${r.length} watermark=${m}`);let I=await this.opts.histories.load(e,{maxEntries:1/0});if(I.length<=m)break;let A=await Br({agentId:i,cwd:l,plan:c,history:I,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(M,P)=>{this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:w,iter:f,worker:{upstreamSessionId:M,pid:P??0}})},onFailure:M=>{y=M}});if(A){let M=Jr(A.synopsis,I);M&&Wr(M)&&(await this.opts.persistSynopsis(e,M,I.length),g=M,h=I.length,y=void 0,await this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:w,iter:f}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"iteration",iter:f,historyLen:I.length}),await this.opts.onCompactionArtifact?.(e,M,h),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${f} fields=${Qr(M)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${f} returned no result`);if(m=I.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(f<u);if(g)f>=u&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${h} iterations=${f}`);else{f>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${u} without producing artifact sessionId=${e}: ${y??"no reason captured"}`);let I=y??(f===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${f} iteration(s)`);await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:w,iter:f,lastError:I}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:I})}}catch(I){let A=I instanceof Error?I.message:String(I);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${A}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:w,iter:f,lastError:A}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:A})}}else{let u=await jr({agentId:i,cwd:l,plan:c,history:r,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!u){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let f=Jr(u.synopsis,r);f&&Wr(f)?(await this.opts.persistSynopsis(e,f,r.length),u.title&&await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!u.title)} fields=${Qr(f)}`)):u.title&&(await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function Jr(n,e){let t=qr(e),s=Lr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Wr(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Qr(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Z from"fs/promises";function Kr(n){return n==="summary"?"summary":"inline"}var Wn=256;function Gr(n,e){return e!=="summary"?n:n.map(Id)}function Id(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(Yr));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,c={};a.error!==void 0&&(c.error=Qn(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),o.rawOutput=c}return{...n,params:{...t,update:o}}}function Sd(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function Yr(n){if(Sd(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Qn(e.text)),typeof e.content=="string"?t.content=Qn(e.content):e.content&&typeof e.content=="object"&&(t.content=Yr(e.content)),t}function Qn(n){if(typeof n=="string"&&n.length>Wn){let e=n.length-Wn;return`${n.slice(0,Wn)}\u2026[+${e} chars omitted from summary export]`}return n}var kd=2048;function Xr(n){let e=new Set,t=s=>{if(Zr(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function Zr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Ad(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Gn(n,e){if(!Ad(n))return n;let t=n.params,s=t.update,r=await Vn(s,e);return{...n,params:{...t,update:r}}}async function Vn(n,e){if(typeof n=="string"){if(n.length<=kd)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await Vn(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Vn(r,e);return t}return n}async function eo(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Kn(t,e);return s===t?n:{...n,params:s}}async function Kn(n,e){if(Zr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let o=await Kn(r,e);o!==r&&(t=!0),s.push(o)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,o]of Object.entries(n)){let i=await Kn(o,e);i!==o&&(t=!0),s[r]=i}return t?s:n}return n}var pt=/^[A-Za-z0-9_-]+$/,Cd=1e3,Dt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Cd}async append(e,t){if(pt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(v.sessionDir(e),{recursive:!0});let s=await Gn(t,o=>hn(e,o)),r=JSON.stringify(s)+`
|
|
110
|
+
`;await Z.appendFile(v.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(pt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(v.sessionDir(e),{recursive:!0});let s=[];for(let o of t)s.push(await Gn(o,i=>hn(e,i)));let r=s.length===0?"":s.map(o=>JSON.stringify(o)).join(`
|
|
83
111
|
`)+`
|
|
84
|
-
`;await
|
|
85
|
-
`).filter(
|
|
112
|
+
`;await Z.writeFile(v.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(pt.test(e))return this.enqueue(e,async()=>{let s;try{s=await Z.readFile(v.historyFile(e),"utf8")}catch(i){if(i.code==="ENOENT")return;throw i}let r=s.split(`
|
|
113
|
+
`).filter(i=>i.length>0);if(r.length<=t)return;let o=r.slice(-t);await Z.writeFile(v.historyFile(e),o.join(`
|
|
86
114
|
`)+`
|
|
87
|
-
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!
|
|
88
|
-
`)){if(u.length===0)continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let
|
|
115
|
+
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!pt.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await Z.readFile(v.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let i=[];for(let u of o.split(`
|
|
116
|
+
`)){if(u.length===0)continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let m=f;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=t.maxEntries??this.maxEntries,c=i.length>a?i.slice(-a):i;if(!s)return c;let d=new Map,p=async u=>{let f=d.get(u);if(f!==void 0)return f;let m=await Et(e,u);return d.set(u,m),m},l=[];for(let u of c)l.push(await eo(u,p));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(pt.test(e))return this.enqueue(e,async()=>{try{await Z.unlink(v.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Ds(e);try{await Z.rmdir(v.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};import{promises as to}from"fs";import*as no from"path";async function so(n,e){await to.mkdir(no.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await to.writeFile(n,t.length>0?t.join(`
|
|
89
117
|
`)+`
|
|
90
|
-
`:"")}import{z as F}from"zod";var qa=F.object({method:F.string(),params:F.unknown(),recordedAt:F.number()}),Ja=F.object({sessionId:F.string(),lineageId:F.string(),upstreamSessionId:F.string().optional(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),synopsis:Ze.optional(),summarizedThroughEntry:F.number().int().nonnegative().optional(),currentModel:F.string().optional(),currentMode:F.string().optional(),currentUsage:Pn.optional(),agentCommands:F.array(Rn).optional(),agentModes:F.array(En).optional(),interactive:F.boolean().optional(),originatingClient:Tn.optional(),priority:F.number().int().nonnegative().optional(),createdAt:F.string(),updatedAt:F.string()}),za=F.object({version:F.literal(1),exportedAt:F.string(),exportedFrom:F.object({hydraVersion:F.string(),machine:F.string(),hydraHost:F.string().optional()}),session:Ja,history:F.array(qa),promptHistory:F.array(F.string()).optional(),toolBlobs:F.record(F.string()).optional()});function st(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function Ar(n){return za.parse(n)}var xr=900*1e3,Qa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tt=Wa(Qa,16),ot=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>pe.spawn(i)),this.store=s??new xt,this.tombstones=r.tombstones??new Ct,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Pt({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.synopsisOnClose=r.synopsisOnClose??!1,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~",this.synopsisCoordinator=new Et({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,persistTitle:async(i,o)=>{let a=this.get(i);if(a){await a.retitle(o);return}await this.persistTitle(i,o)},persistSynopsis:(i,o,a)=>this.persistSynopsis(i,o,a),logger:this.logger,npmRegistry:this.npmRegistry}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;synopsisOnClose;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;agentCatalog=[];async refreshAgentCatalog(){try{let{agents:e}=await Oe(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let r={...t.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Tt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}t.agentCapabilities=r}let s=new xe({cwd:e.cwd,agentId:e.agentId,agent:t.agent,upstreamSessionId:t.upstreamSessionId,agentMeta:t.agentMeta,agentCapabilities:t.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:t.initialModel,currentMode:t.initialMode,agentModes:t.initialModes,agentModels:t.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=I.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=I.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await se(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});o=m.agentCapabilities,i.authMethods=_t(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ce(m,i)}let a;try{let m=Ka(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===I.AuthRequired)throw await i.kill().catch(()=>{}),Ce(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
91
|
-
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Pr(a??{}),c=e.agentModes??Mr(Er(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let l=await Tr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=Cr(a??{}),f=Mr(Rr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await _r({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new xe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:f,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Tr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await _r({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new xe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Me.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Te(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=I.AgentNotInstalled,p}let s=await se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:$t.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=_t(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=w.sessionsDir(),u=[],f=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){f+=1;continue}if(Va(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!rr(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ge}${Tt()}`,y=new Date().toISOString(),A=p.updatedAt??y,k={sessionId:h,lineageId:et(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:A,updatedAt:A};p.title!==void 0&&(k.title=p.title);let b=_n(k);await this.store.write(b),u.push({version:1,...b})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}}),o=i.agentCapabilities;r.authMethods=_t(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=Cr(a),l=Rr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=je(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,u,m)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=l.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let f=Er(a),p=Pr(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ce(i,r)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let d=new Error(`agent ${e} not found in registry`);throw d.code=I.AgentNotInstalled,d}let i=await se(r,[],{npmRegistry:this.npmRegistry}),o=t??Te(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});a.authMethods=_t(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ce(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Le({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}e.firstPromptSeeded&&this.synopsisOnClose&&this.synopsisCoordinator.schedule(e.sessionId)}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:Fr(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Ga(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return wt(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Ya(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forwardedEnv:t.forwardedEnv}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Be(r.update.prompt),o=xn(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ge))return;let t=ge+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=I.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await rt(t.sessionId),d=Le({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await rt(s.sessionId),i=Le(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>rt(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Le({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let g=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),c=await Promise.all(d.map(l=>rt(l.sessionId)));for(let l=0;l<d.length;l+=1){let u=d[l],f=c[l],p=Le(u,f.hasContent);if(!r(p))continue;let g=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=et(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await $r(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of wr(o)){let l=await ms(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=I.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ge}${Tt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=I.SessionNotFound,g}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let m=new Error(`agent ${r} not found in registry`);throw m.code=I.AgentNotInstalled,m}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=An(o,t.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw g.code=I.InvalidParams,g}d=t.forkAt}else{let g=Za(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),l=await $r(e),u={...s,lineageId:et(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},f=st({record:u,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:G,machine:$t.hostname()}),p=`${ge}${Tt()}`;return await this.writeImportedRecord({sessionId:p,bundle:f,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d}),{sessionId:p,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await hs(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Me.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await kr(w.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await rt(e),r=Le(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Qs(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<xr),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${xr/1e3}s)`),await Ke(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Ke(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Va(n,e){if(typeof n!="string"||n.length===0)return!1;let t=it.resolve(n),s=it.resolve(e);return t===s||t.startsWith(s+it.sep)}function Ga(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return _n({sessionId:n.sessionId,lineageId:e?.lineageId??et(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:Fr(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Fr(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ya(n){return n?{...n}:void 0}function Ka(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ft(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Xa(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Cr(n){return Ft(n,{nestedKey:"models",configId:"model",fromObject:e=>le(e.currentModelId)??le(e.currentModel)??le(e.modelId)??le(e.model),fromConfig:e=>le(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=I.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function _t(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function le(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Xa(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Mr(n){return n.length>0?n:void 0}function Rr(n){return Ft(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ue(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ue(e.options);return t.length>0?t:void 0}})??[]}function Er(n){return Ft(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Xe(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Xe(e.options);return t.length>0?t:void 0}})??[]}function Pr(n){return Ft(n,{nestedKey:"modes",configId:"mode",fromObject:e=>le(e.currentModeId)??le(e.currentMode)??le(e.modeId)??le(e.mode),fromConfig:e=>le(e.currentValue)})}async function Tr(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function _r(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}function Za(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function $r(n){try{let e=await Me.readFile(w.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
|
|
92
|
-
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function
|
|
93
|
-
`);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let
|
|
94
|
-
`),
|
|
95
|
-
`),
|
|
96
|
-
`,{encoding:"utf8",mode:384})}catch(
|
|
97
|
-
`)}e.child=f,e.logStream=
|
|
98
|
-
`)}),f.on("exit",(
|
|
99
|
-
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof
|
|
100
|
-
`);try{
|
|
101
|
-
|
|
102
|
-
`))}async function Nr(n,e){let t=ae();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Bt.join(w.agentsDir(),t),a;try{a=await ct.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;dt(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=Bt.join(o,c),p;try{p=await ct.readdir(f,{withFileTypes:!0})}catch(g){dt(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let h=Bt.join(f,m);try{await ct.rm(h,{recursive:!0,force:!0}),dt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){dt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function jr(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await hn(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Dn(n){let e=n.maxDeletions??200,t=(p,g)=>{n.logger&&n.logger[p](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,t("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${id(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Hr(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Dn({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function id(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as od}from"crypto";function Ln(n){if(Array.isArray(n))return n.map(Ln);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Ln(n[t]);return e}return n}function Br(n){let{tui:e,...t}=n,s=JSON.stringify(Ln(t));return od("sha256").update(s).digest("hex").slice(0,16)}import*as Lr from"path";import{createHash as ad,randomBytes as dd,timingSafeEqual as cd}from"crypto";var qr="hydra_session_",ud=3600*24*30,Ur=12,ld=32,fd=50;function pd(){return Lr.join(w.home(),"session-tokens.json")}function Dr(n){return ad("sha256").update(n).digest("hex")}function Jr(n){return dd(n).toString("hex")}function gd(){return Jr(Ur).slice(0,Ur*2)}function md(){return`${qr}${Jr(ld)}`}var Ut=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=pd(),s=await oe(t);s&&Array.isArray(s.records)&&(e=s.records.filter(hd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=md(),s=Dr(t),r=gd(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ud,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(qr))return;let t=Dr(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!cd(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},fd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ne(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function hd(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var zr="Bearer ",Dt=class{constructor(e){this.token=e}token;async validate(e){return yd(e,this.token)?"service":void 0}},Lt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},qt=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Wr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(zr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Qr(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Jt=class{tokens=new Map;mint(e,t){let s=mt();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function yd(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var zt=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as pt from"os";import*as fi from"path";import{posix as wd}from"path";import vd from"strip-ansi";function ut(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Id=/[\x00-\x08\x0b-\x1f\x7f]/g;function ee(n){return vd(n).replace(Id,"")}function L(n){return ee(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Yr(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Md(t);case"agent_thought_chunk":case"agent_thought":return Rd(t);case"user_message_chunk":return Ed(t);case"prompt_received":return Pd(t);case"tool_call":return Td(t,e);case"tool_call_update":return Nd(t,e);case"plan":return Bd(t);case"current_mode_update":return Ud(t);case"current_model_update":return Dd(t);case"turn_complete":return Ld(t);case"usage_update":return Cd(t);case"available_commands_update":return Ad(t);case"available_modes_update":return xd(t);case"session_info_update":return Sd(t);case"config_option_update":return bd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function bd(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Sd(n){let e=U(n,"title"),t=e!==void 0?L(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),i}function kd(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:L(r)};typeof s.description=="string"&&(i.description=L(s.description)),e.push(i)}return e}function Ad(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:kd(e)}:null}function xd(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:L(r.id)};typeof r.name=="string"&&(i.name=L(r.name)),typeof r.description=="string"&&(i.description=L(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Cd(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function Md(n){let e=lt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ut(n)}}function Rd(n){let e=typeof n.text=="string"?ee(n.text):lt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ut(n)}}function Ed(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=lt(n.content);return t===null?null:{kind:"user-text",text:t}}function Pd(n){let e=qd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Kr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Vr(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Wt(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Vr(r.oldText),o=Vr(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Xr(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:ee(t)}function Td(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title")??U(n,"name")??U(n,"label")??"tool call",r=U(n,"name")??U(n,"title");if(Kr(r)){let g=Xr(n);if(g!==null){let m=U(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=ti(L(s),n,e),o=U(n,"status"),a=U(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Wt(n);c!==null&&(d.editDiff=c);let l=ei(n);l!==void 0&&(d.detail=l);let u=qn(n);u!==void 0&&(d.detailFull=u);let f=Zr(n);f!==void 0&&(d.locations=f);let p=ut(n);return p!==void 0&&(d.workerTaskId=p),d}function Zr(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Gr=64;function ei(n){let e=qn(n);if(e===void 0)return;let t=L(e),s=n.rawInput;return s&&typeof s.command=="string"?Fd(t,Gr):Od(t,Gr)}function qn(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ee(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Ee(L(s))}var _d=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function $d(n){for(let e of _d)if(n.startsWith(e))return!0;return!1}function ti(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ee(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Ee(o)}return $d(n)?Ee(`/${n}`):t.cwd&&t.cwd.length>0?Ee(wd.resolve(t.cwd,n)):n}function Fd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Od(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Nd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?ti(L(s),n,e):void 0,i=U(n,"status"),o=Wt(n),a=ei(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=U(n,"name")??s;if(Kr(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Xr(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=qn(n);u!==void 0&&(l.detailFull=u);let f=Zr(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let g=jd(n);g!==null&&(l.errorText=g),Hd(n,g)&&(l.upstreamInterrupted=!0)}let p=ut(n);return p!==void 0&&(l.workerTaskId=p),l}function jd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=lt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ee(s)}return null}function Hd(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Bd(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?L(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function Ud(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Dd(n){let e=U(n,"currentModel")??U(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:L(e),...s&&s.length>0?{availableModels:s}:{}}}function Ld(n){let e=U(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function lt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ee(e.text):null}function qd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=lt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function U(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ni(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=zd(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)Jd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function si(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Jd(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function zd(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Wt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function ri(n){let e=Wd(n),t=Qd(e),s=[];Vd(s,n),Gd(s,e,t);let r=s.join(`
|
|
118
|
+
`:"")}import{z as B}from"zod";var xd=B.object({method:B.string(),params:B.unknown(),recordedAt:B.number()}),Md=B.object({sessionId:B.string(),lineageId:B.string(),upstreamSessionId:B.string().optional(),agentId:B.string(),cwd:B.string(),title:B.string().optional(),synopsis:ct.optional(),summarizedThroughEntry:B.number().int().nonnegative().optional(),currentModel:B.string().optional(),currentMode:B.string().optional(),currentUsage:qn.optional(),agentCommands:B.array(Dn).optional(),agentModes:B.array(Ln).optional(),interactive:B.boolean().optional(),originatingClient:zn.optional(),priority:B.number().int().nonnegative().optional(),createdAt:B.string(),updatedAt:B.string()}),Rd=B.object({version:B.literal(1),exportedAt:B.string(),exportedFrom:B.object({hydraVersion:B.string(),machine:B.string(),hydraHost:B.string().optional()}),session:Md,history:B.array(xd),promptHistory:B.array(B.string()).optional(),toolBlobs:B.record(B.string()).optional()});function ft(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function ro(n){return Rd.parse(n)}var oo=900*1e3,io=5e3,ao=3,Pd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Lt=Ed(Pd,16),yt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>he.spawn(a)),this.store=s??new Ht,this.tombstones=r.tombstones??new Nt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Dt({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new Ut({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c)=>{let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c)=>{this.broadcastHydraCompaction(a,c)},onCompactionArtifact:async(a,c,d)=>{let p=this.get(a);if(!p){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${a}`),await this.mutateRecord(a,{synopsis:c,summarizedThroughEntry:d});return}try{if(!await p.isQuiescedForSwap()){let u=this.compactionDeferrals.get(a)??0;if(u++,u>ao){this.logger?.warn(`compaction: deferral cap reached for sessionId=${a}, skipping swap until next trigger`),this.compactionDeferrals.delete(a),p.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"]),p.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached"});return}this.compactionDeferrals.set(a,u),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${u}`),p.broadcastCompactionPhase({phase:"deferred",attempts:u}),setTimeout(()=>{this.retrySwap(a)},io).unref();return}this.compactionDeferrals.delete(a),await p.swapUpstream({artifact:c,tailK:i,summarizedThroughEntry:d}),p.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"])}catch(l){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${l instanceof Error?l.message:String(l)}, leaving session as-is`)}}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;compactionDeferrals=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async retrySwap(e){let t=this.get(e);if(!t){this.compactionDeferrals.delete(e);return}let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let i=this.compactionDeferrals.get(e)??0;if(i++,i>ao){this.logger?.warn(`compaction: deferral cap reached on retry for sessionId=${e}, giving up`),this.compactionDeferrals.delete(e),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]),t.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached on retry"});return}this.compactionDeferrals.set(e,i),this.logger?.info(`compaction: still not quiesced on retry, re-deferring sessionId=${e} attempt=${i}`),setTimeout(()=>{this.retrySwap(e)},io).unref();return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing on retry for sessionId=${e}, skipping swap`),this.compactionDeferrals.delete(e),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}this.compactionDeferrals.delete(e),await t.swapUpstream({artifact:o.synopsis,tailK:s,summarizedThroughEntry:o.summarizedThroughEntry}),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"])}catch(r){this.logger?.warn(`compaction: retrySwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async refreshAgentCatalog(){try{let{agents:e}=await He(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let r={...t.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let i=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Lt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});i.action==="stop"&&i.payload&&(r=i.payload)}catch{}t.agentCapabilities=r}let s=new Ee({cwd:e.cwd,agentId:e.agentId,agent:t.agent,upstreamSessionId:t.upstreamSessionId,agentMeta:t.agentMeta,agentCapabilities:t.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:r.mcpServers??[]}),loadExistingAgentSession:(r,o)=>this.bootstrapAgentLoad(r,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:t.initialModel,currentMode:t.initialMode,agentModes:t.initialModes,agentModels:t.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(s.sessionId),getCompactionState:()=>this.getCompactionState(s.sessionId),uncompactHook:()=>this.performUncompact(s.sessionId),onCompactionSwapHook:r=>{this.mutateRecord(s.sessionId,{rollbackBreadcrumb:r}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(s.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(s),s}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=S.AlreadyAttached,o}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let g=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw g.code=S.AgentNotInstalled,g}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await se(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),i;try{let g=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:K}});i=g.agentCapabilities,o.authMethods=mt(g.authMethods)}catch(g){throw await o.kill().catch(()=>{}),ke(g,o)}let a;try{let g=co(e.agentId,e.currentModel);a=await o.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...g&&{_meta:g}})}catch(g){if(g&&typeof g=="object"&&g.code===S.AuthRequired)throw await o.kill().catch(()=>{}),ke(g,o);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
|
|
119
|
+
`),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=ts(a??{}),d=e.agentModes??Xn(es(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(g=>g.id))}`);let p=await Ne({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(p)} for sessionId=${e.hydraSessionId}`);let l=Yn(a??{}),u=Xn(Zn(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(l)} advertisedModels=${JSON.stringify(u?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let f=await je({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:l,logger:this.logger});if(e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new Ee({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:g.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(g,h)=>this.bootstrapAgentLoad(g,{...h,mcpServers:h.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:f,currentMode:p,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:u,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(m.sessionId),getCompactionState:()=>this.getCompactionState(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:g=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:g}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await Ne({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await je({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Ee({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,p)=>this.bootstrapAgentLoad(d,{...p,mcpServers:p.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(c.sessionId),getCompactionState:()=>this.getCompactionState(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Pe.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Y(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let f=new Error(`agent ${e} not found in registry`);throw f.code=S.AgentNotInstalled,f}let s=await se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:qt.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:K}})}catch(f){throw await r.kill().catch(()=>{}),ke(f,r)}if(r.authMethods=mt(o.authMethods),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(f){throw await r.kill().catch(()=>{}),f}await r.kill().catch(()=>{});let c=new Set;for(let f of this.sessions.values())c.add(`${f.agentId}::${f.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let f of d)c.add(`${f.agentId}::${f.upstreamSessionId}`);let p=v.sessionsDir(),l=[],u=0;for(let f of a){let m=`${e}::${f.sessionId}`;if(c.has(m)){u+=1;continue}if(Td(f.cwd,p)){u+=1;continue}let g=await this.tombstones.read(e,f.sessionId).catch(()=>{});if(g){if(!Or(g,f.updatedAt)){u+=1;continue}await this.tombstones.remove(e,f.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${f.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let h=`${ye}${Lt()}`,y=new Date().toISOString(),w=f.updatedAt??y,I={sessionId:h,lineageId:ut(),upstreamSessionId:f.sessionId,agentId:e,cwd:f.cwd,pendingHistorySync:!0,interactive:!0,createdAt:w,updatedAt:w};f.title!==void 0&&(I.title=f.title);let A=Jn(I);await this.store.write(A),l.push({version:1,...A})}return{synced:l,skipped:u}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let o=0;o<100;o+=1){let i={};s!==void 0&&(i.cursor=s);let a=await e.connection.request("session/list",i),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let p={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(p.title=d.title),typeof d.updatedAt=="string"&&(p.updatedAt=d.updatedAt),t.push(p)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=S.AgentNotInstalled,o}let s=await se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:K}}),i=o.agentCapabilities;r.authMethods=mt(o.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=Yn(a),p=Zn(a),l=e.model??this.defaultModels[e.agentId];if(l&&l!==d){let m=Ue(l,p),g=e.model!==void 0?`model=${JSON.stringify(l)}`:`defaultModels[${e.agentId}]=${JSON.stringify(l)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,l,g)&&(d=l);else if(m.kind==="resolved")(m.modelId===d||await this.applySeedModel(r,c,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(d=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${g} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let h=p.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=es(a),f=ts(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:i,initialModel:d,initialModels:p.length>0?p:void 0,initialModes:u.length>0?u:void 0,initialMode:f}}catch(o){throw await r.kill().catch(()=>{}),ke(o,r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let i=new Error(`agent ${t.agentId} not found in registry`);throw i.code=S.AgentNotInstalled,i}let r=await se(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=mt(i.authMethods);let c=co(t.agentId,void 0),d=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),p=Yn(d),l=Xn(Zn(d)),u=es(d),f=ts(d);return{agent:o,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:p,initialModels:l,initialModes:u.length>0?u:void 0,initialMode:f}}catch(i){throw await o.kill().catch(()=>{}),ke(i,o)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=s.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=S.AgentNotInstalled,c}let o=await se(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:K}});a.authMethods=mt(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),ke(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=S.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Qe({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:lo(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=_d(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return Et(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:$d(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=qe(r.update.prompt),i=Nn(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ye))return;let t=ye+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=S.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await gt(t.sessionId),c=Qe({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:d,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await gt(s.sessionId),o=Qe(s,r.hasContent),i=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:o,priority:s.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=p=>e.includeNonInteractive?!0:p===!0,o=[...this.sessions.values()].filter(p=>!e.cwd||p.cwd===e.cwd),i=await Promise.all(o.map(p=>gt(p.sessionId)));for(let p=0;p<o.length;p+=1){let l=o[p],u=i[p];s.add(l.sessionId);let f=Qe({interactive:l.interactive,...l.originatingClient?{originatingClient:l.originatingClient}:{}},u.hasContent);if(!r(f))continue;let m=u.mtime??new Date(l.updatedAt).toISOString();t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:m,attachedClients:l.attachedCount,status:"live",busy:l.turnStartedAt!==void 0,awaitingInput:l.awaitingInput,compactionState:l.compactionState})}let c=(await this.store.list().catch(p=>{throw this.logger?.warn(`session list: store.list() failed: ${p?.message??String(p)}`),p})).filter(p=>!s.has(p.sessionId)&&(!e.cwd||p.cwd===e.cwd)),d=await Promise.all(c.map(p=>gt(p.sessionId)));for(let p=0;p<c.length;p+=1){let l=c[p],u=d[p],f=Qe(l,u.hasContent);if(!r(f))continue;let m=u.mtime??l.updatedAt;t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage?{...l.currentUsage,costAmount:(l.currentUsage.cumulativeCost??0)+(l.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:l.importedFromMachine,importedFromUpstreamSessionId:l.importedFromUpstreamSessionId,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:l.compactionState})}return t.sort((p,l)=>p.updatedAt<l.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=ut(),p={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let l=await this.store.read(e);l&&(l.lineageId||await this.store.write({...l,lineageId:d}))}).catch(()=>{}),r=p}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await uo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let c={};for(let d of Xr(i)){let p=await Bs(e,d);p&&(c[d]=p.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=S.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ye}${Lt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let m=new Error(`source session not found: ${e}`);throw m.code=S.SessionNotFound,m}let r=t.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let g=new Error(`agent ${r} not found in registry`);throw g.code=S.AgentNotInstalled,g}let i=await this.histories.load(e).catch(()=>[]),a,c;if(t.forkAt!==void 0){if(a=Hn(i,t.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw m.code=S.InvalidParams,m}c=t.forkAt}else{let m=Od(i);m?(a=m.index,c=m.messageId):(a=-1,c="")}let d=i.slice(0,a+1),p=await uo(e),l={...s,lineageId:ut(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},u=ft({record:l,history:d,promptHistory:p.length>0?p:void 0,hydraVersion:K,machine:qt.hostname()}),f=`${ye}${Lt()}`;return await this.writeImportedRecord({sessionId:f,bundle:u,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c}),{sessionId:f,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await Us(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Pe.utimes(v.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await so(v.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await gt(e),r=Qe(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,...t,updatedAt:new Date().toISOString()};for(let i of s)delete o[i];await this.store.write(o)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e){this.synopsisCoordinator.scheduleCompaction(e)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}broadcastHydraCompaction(e,t){let s=this.get(e);s&&s.broadcastCompactionPhase(t)}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await br(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(c=>r-c.enqueuedAt<oo),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${oo/1e3}s)`),await at(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await at(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),c.replayPersistedQueue(o)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function Td(n,e){if(typeof n!="string"||n.length===0)return!1;let t=ht.resolve(n),s=ht.resolve(e);return t===s||t.startsWith(s+ht.sep)}function _d(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(p=>p.description!==void 0?{name:p.name,description:p.description}:{name:p.name}):void 0)??e?.agentCommands,r=n.availableModes(),i=(r.length>0?r.map(p=>{let l={id:p.id};return p.name!==void 0&&(l.name=p.name),p.description!==void 0&&(l.description=p.description),l}):void 0)??e?.agentModes,a=n.availableModels(),d=(a.length>0?a.map(p=>{let l={modelId:p.modelId};return p.name!==void 0&&(l.name=p.name),p.description!==void 0&&(l.description=p.description),l}):void 0)??e?.agentModels;return Jn({sessionId:n.sessionId,lineageId:e?.lineageId??ut(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:lo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:d,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function lo(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function $d(n){return n?{...n}:void 0}function co(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function zt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let i=e.fromObject(s);if(i!==void 0)return i}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let o=Fd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Yn(n){return zt(n,{nestedKey:"models",configId:"model",fromObject:e=>ge(e.currentModelId)??ge(e.currentModel)??ge(e.modelId)??ge(e.model),fromConfig:e=>ge(e.currentValue)})}function ke(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==S.AuthRequired)return n;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(t.data)?t.data:{},o=s(r._meta)?r._meta:{},i=s(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=S.AuthRequired,c.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function mt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",o=s.type==="agent"||s.type==="terminal"?s.type:void 0,i=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...c&&{_meta:c}})}return e.length>0?e:void 0}function ge(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Fd(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Xn(n){return n.length>0?n:void 0}function Zn(n){return zt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=ze(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=ze(e.options);return t.length>0?t:void 0}})??[]}function es(n){return zt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=dt(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=dt(e.options);return t.length>0?t:void 0}})??[]}function ts(n){return zt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ge(e.currentModeId)??ge(e.currentMode)??ge(e.modeId)??ge(e.mode),fromConfig:e=>ge(e.currentValue)})}function Od(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function uo(n){try{let e=await Pe.readFile(v.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
|
|
120
|
+
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function gt(n){try{let e=await Pe.stat(v.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Qe(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Bt?!1:e?!0:void 0}import{spawn as Hd}from"child_process";import*as Ke from"fs";import*as Ae from"fs/promises";import*as po from"path";var Jt=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Nd=1e3,jd=6e4,ns=3e3,Ve=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Nd,this.restartCapMs=r.restartCapMs??jd;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Ae.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},ns);s.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw wt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw wt(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw wt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw wt(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw wt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},ns);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Jt(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ae.readdir(this.adapter.paths.dir())}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.endsWith(".pid"))continue;let s=po.join(this.adapter.paths.dir(),t),r;try{let o=await Ae.readFile(s,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&ss(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+ns;for(;Date.now()<o&&ss(r);)await new Promise(i=>setTimeout(i,50));if(ss(r))try{process.kill(r,"SIGKILL")}catch{}}await Ae.unlink(s).catch(()=>{})}}spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Ke.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});i.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
|
|
121
|
+
`);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let c={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:a,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...p]=o;if(d===void 0){i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
|
|
122
|
+
`),i.end();return}let l=Y(d),u=[...p,...r.args].map(Y),f;try{f=Hd(l,u,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){i.write(`[hydra-acp] failed to spawn ${r.name}: ${m.message}
|
|
123
|
+
`),i.end(),this.scheduleRestart(e,t);return}if(f.stdout&&f.stdout.pipe(i,{end:!1}),f.stderr&&f.stderr.pipe(i,{end:!1}),typeof f.pid=="number")try{Ke.writeFileSync(this.adapter.paths.pidFile(r.name),`${f.pid}
|
|
124
|
+
`,{encoding:"utf8",mode:384})}catch(m){i.write(`[hydra-acp] failed to write pid file for ${r.name}: ${m.message}
|
|
125
|
+
`)}e.child=f,e.logStream=i,e.pid=typeof f.pid=="number"?f.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,f.on("error",m=>{i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${m.message}
|
|
126
|
+
`)}),f.on("exit",(m,g)=>{try{Ke.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${g??"null"}
|
|
127
|
+
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof m=="number"?m:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let h=e.exitWaiters.splice(0);for(let w of h)w();if(this.stopping||e.manuallyStopped){try{i.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let y=e.breaker.recordExit(m,r.name,this.adapter.kind);if(typeof y=="object"){e.failureReason=y.tripped,i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${y.tripped}
|
|
128
|
+
`);try{i.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ss(n){try{return process.kill(n,0),!0}catch{return!1}}function wt(n,e){return n.code=e,n}var Bd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:v.extensionsDir,logFile:v.extensionLogFile,pidFile:v.extensionPidFile}},Wt=class extends Ve{constructor(e,t,s={}){super(e,Bd,t,s)}};var Ud={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:v.transformersDir,logFile:v.transformerLogFile,pidFile:v.transformerPidFile}},Qt=class extends Ve{connected=new Map;constructor(e,t,s={}){super(e,Ud,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var Vt=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};import*as rs from"fs/promises";async function fo(n){await rs.writeFile(v.pidFile(),JSON.stringify(n)+`
|
|
129
|
+
`,{encoding:"utf8",mode:384})}import*as bt from"fs/promises";import*as Kt from"path";var vt=n=>{process.stderr.write(n+`
|
|
130
|
+
`)};function os(n){vt=n??(e=>process.stderr.write(e+`
|
|
131
|
+
`))}async function mo(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let o=e.activeAgentVersions(),i=Kt.join(v.agentsDir(),t),a;try{a=await bt.readdir(i,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;vt(`hydra-acp: prune: failed to read ${i}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,p=r.get(d);if(p===void 0)continue;let l=o.get(d)??new Set,u=Kt.join(i,d),f;try{f=await bt.readdir(u,{withFileTypes:!0})}catch(m){vt(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of f){if(!m.isDirectory())continue;let g=m.name;if(g===p||l.has(g)||g.includes(".partial-"))continue;let h=Kt.join(u,g);try{await bt.rm(h,{recursive:!0,force:!0}),vt(`hydra-acp: pruned stale ${d} ${g} (${h})`)}catch(y){vt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function go(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},o=async()=>{let a=[];try{let p=await n.registry.load();for(let l of p.agents)await Cn(l)==="yes"&&a.push(l.id)}catch(p){return r("warn",`registry load failed: ${p.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:p,skipped:l}=await n.manager.syncFromAgent(d);r("info",`${d}: synced ${p.length}, skipped ${l}`)}catch(p){r("warn",`${d}: ${p.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(c=>{i(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function is(n){let e=n.maxDeletions??200,t=(f,m)=>{n.logger&&n.logger[f](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(f=>(t("warn",`manager.list failed: ${f.message}`),[])),i=[];for(let f of o){if(f.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(f.interactive!==!1)continue}else if(f.interactive===!0)continue;let g=Date.parse(f.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:f.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((f,m)=>f.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),c=a[0]?.lastUsedMs,d=0,p=0;for(let{sessionId:f}of a)try{await n.manager.deleteRecord(f)&&(d+=1)}catch(m){p+=1,t("warn",`delete ${f} failed: ${m.message}`)}let l=i.length-a.length;if(n.verbose||d>0||p>0){let f=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${d} ${f} session(s) older than ${Dd(n.maxAgeMs)}`+(p>0?`; ${p} failed`:"")+(l>0?`; ${l} deferred to next sweep`:""))}let u={considered:i.length,deleted:d,failed:p,deferred:l};return c!==void 0&&(u.oldestLastUsedMs=c),u}function ho(n){let e,t=!1,s=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await is({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},o),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Dd(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as Ld}from"crypto";function as(n){if(Array.isArray(n))return n.map(as);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=as(n[t]);return e}return n}function yo(n){let{tui:e,...t}=n,s=JSON.stringify(as(t));return Ld("sha256").update(s).digest("hex").slice(0,16)}import*as bo from"path";import{createHash as qd,randomBytes as zd,timingSafeEqual as Jd}from"crypto";var Io="hydra_session_",Wd=3600*24*30,wo=12,Qd=32,Vd=50;function Kd(){return bo.join(v.home(),"session-tokens.json")}function vo(n){return qd("sha256").update(n).digest("hex")}function So(n){return zd(n).toString("hex")}function Gd(){return So(wo).slice(0,wo*2)}function Yd(){return`${Io}${So(Qd)}`}var Gt=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=Kd(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(Xd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=Yd(),s=vo(t),r=Gd(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:Wd,a=new Date(o.getTime()+i*1e3),c={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Io))return;let t=vo(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!Jd(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},Vd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ie(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function Xd(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var ko="Bearer ",Yt=class{constructor(e){this.token=e}token;async validate(e){return Zd(e,this.token)?"service":void 0}},Xt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Zt=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Ao(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(ko)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(ko.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function Co(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var en=class{tokens=new Map;mint(e,t){let s=xt();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function Zd(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var tn=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as ps from"fs";import*as kt from"os";import*as Qo from"path";import*as fs from"readline";function ds(n){return Math.floor(n/4)}function xo(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=ds(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}import{posix as ec}from"path";import tc from"strip-ansi";function It(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var nc=/[\x00-\x08\x0b-\x1f\x7f]/g;function re(n){return tc(n).replace(nc,"")}function W(n){return re(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Eo(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return cc(t);case"agent_thought_chunk":case"agent_thought":return uc(t);case"user_message_chunk":return lc(t);case"prompt_received":return pc(t);case"tool_call":return fc(t,e);case"tool_call_update":return wc(t,e);case"plan":return Ic(t);case"current_mode_update":return Sc(t);case"current_model_update":return kc(t);case"turn_complete":return Ac(t);case"usage_update":return dc(t);case"available_commands_update":return ic(t);case"available_modes_update":return ac(t);case"session_info_update":return rc(t);case"config_option_update":return sc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function sc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function rc(n){let e=J(n,"title"),t=e!==void 0?W(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s["hydra-acp"];if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),o}function oc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:W(r)};typeof s.description=="string"&&(o.description=W(s.description)),e.push(o)}return e}function ic(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:oc(e)}:null}function ac(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:W(r.id)};typeof r.name=="string"&&(o.name=W(r.name)),typeof r.description=="string"&&(o.description=W(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function dc(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function cc(n){let e=St(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:It(n)}}function uc(n){let e=typeof n.text=="string"?re(n.text):St(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:It(n)}}function lc(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=St(n.content);return t===null?null:{kind:"user-text",text:t}}function pc(n){let e=Cc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Po(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Mo(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function nn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=Mo(r.oldText),i=Mo(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function To(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:re(t)}function fc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title")??J(n,"name")??J(n,"label")??"tool call",r=J(n,"name")??J(n,"title");if(Po(r)){let m=To(n);if(m!==null){let g=J(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:m};return g!==void 0&&(h.status=g),h}}let o=Fo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),c={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(c.status=i),a!==void 0&&(c.rawKind=a);let d=nn(n);d!==null&&(c.editDiff=d);let p=$o(n);p!==void 0&&(c.detail=p);let l=cs(n);l!==void 0&&(c.detailFull=l);let u=_o(n);u!==void 0&&(c.locations=u);let f=It(n);return f!==void 0&&(c.workerTaskId=f),c}function _o(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Ro=64;function $o(n){let e=cs(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?hc(t,Ro):yc(t,Ro)}function cs(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return re(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return xe(W(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return xe(W(s))}}}var mc=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function gc(n){for(let e of mc)if(n.startsWith(e))return!0;return!1}function Fo(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return xe(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return xe(i)}return gc(n)?xe(`/${n}`):t.cwd&&t.cwd.length>0?xe(ec.resolve(t.cwd,n)):n}function hc(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function yc(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function wc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Fo(W(s),n,e):void 0,o=J(n,"status"),i=nn(n),a=$o(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let d=J(n,"name")??s;if(Po(d)){let m={kind:"exit-plan-mode",toolCallId:t},g=To(n);return g!==null&&(m.plan=g),o!==void 0&&(m.status=o),m}let p={kind:"tool-call-update",toolCallId:t};r!==void 0&&(p.title=r),a!==void 0&&(p.detail=a);let l=cs(n);l!==void 0&&(p.detailFull=l);let u=_o(n);if(u!==void 0&&(p.locations=u),o!==void 0&&(p.status=o),i!==null&&(p.editDiff=i),o==="failed"){let m=vc(n);m!==null&&(p.errorText=m),bc(n,m)&&(p.upstreamInterrupted=!0)}let f=It(n);return f!==void 0&&(p.workerTaskId=f),p}function vc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=St(s.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return re(s)}return null}function bc(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Ic(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?W(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function Sc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function kc(n){let e=J(n,"currentModel")??J(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:W(e),...s&&s.length>0?{availableModels:s}:{}}}function Ac(n){let e=J(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function St(n){if(typeof n=="string")return re(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?re(e.text):null}function Cc(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=St(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function J(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Oo(n){let e=new Map,t=new Map;for(let r of n){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,d=Mc(i);if(d.length===0)continue;let p=d;if(c!==void 0){let l=e.get(c)??[],u=[];for(let f of d)l.some(m=>m.path===f.path&&m.oldText===f.oldText&&m.newText===f.newText)||u.push(f);if(u.length===0)continue;e.set(c,[...l,...u]),p=u}for(let l of p)xc(t,l)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function Ho(n){let e=[];for(let t of n){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){s=o;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function xc(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Mc(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,p=typeof d.old_string=="string"?d.old_string:void 0,l=typeof d.new_string=="string"?d.new_string:void 0;p===void 0||l===void 0||e.push({path:i,oldText:p,newText:l})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let c=typeof i.oldText=="string"?i.oldText:"",d=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=nn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function No(n){let e=Rc(n),t=Ec(e),s=[];Pc(s,n),Tc(s,e,t);let r=s.join(`
|
|
103
132
|
`);return r.endsWith(`
|
|
104
133
|
`)||(r+=`
|
|
105
|
-
`),r}function
|
|
106
|
-
`)),n.push("")}function
|
|
107
|
-
`))n.push(`> ${
|
|
108
|
-
`);for(let u of l)n.push(`> _${Re(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let l=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Xd(l.status)} ${Kd(l)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let l of c.entries){let u=l.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Re(l.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Re(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Re(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Yd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Kd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Re(n.title)}${t}`}function Xd(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function Re(n){return n.replace(/</g,"<").replace(/>/g,">")}function Jn(n){return n.toLocaleString("en-US")}function ii(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Zd(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>ec(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function ec(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:oi(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:oi(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function oi(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function tc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var nc=5,sc=200,ai=30;async function ui(n,e,t={}){let s=Zd(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??nc,i=t.maxSessions??sc,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],l=!1;for(let u of d){if(c.length>=i){l=!0;break}let f=await n.loadHistory(u.sessionId).catch(()=>[]),p=rc(f,s,r);if(p.snippets.length===0)continue;let g={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(g.title=u.title),c.push(g)}return{query:e,truncated:l,results:c}}function rc(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=ic(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function ic(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=oc(a).filter(c=>tc(t,c.kind));for(let c of d){let l=c.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),g={kind:c.kind,text:lc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function oc(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Qt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ee(s.text):Qt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(cc(s))return[];let i=Qt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=uc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return ac(s);default:return[]}}function ac(n){let e=di(n,"name"),t=di(n,"title"),s=[];if(t!==void 0){let a=L(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=L(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=ci(r);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=ci(i);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=dc(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function dc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=L(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=L(s);if(r.length>0)return r}}return null}function cc(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function Qt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ee(e.text):""}function uc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Qt(t);s.length>0&&e.push(s)}return e.join("")}function di(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ci(n){try{return JSON.stringify(n)}catch{return""}}function lc(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-ai),d=Math.min(s.length,o+i.length+ai),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}import{randomBytes as fc}from"crypto";function ft(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=fc(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}function li(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ii(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function pi(n,e,t,s={}){n.get("/v1/sessions",async r=>{let i=r.query,o=i?.includeNonInteractive==="1"||i?.includeNonInteractive==="true";return{sessions:await e.list({cwd:i?.cwd,includeNonInteractive:o})}}),n.get("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.getOne(a);return d||(i.code(404).send({error:"session not found"}),i)}),n.post("/v1/sessions/search",async(r,i)=>{let o=r.body??{},a=typeof o.q=="string"?o.q:"";if(a.trim().length===0)return i.code(400).send({error:"q is required"}),i;let d=Array.isArray(o.sessionIds)?o.sessionIds.filter(l=>typeof l=="string"&&l.length>0):void 0;return await ui(e,a,{sessionIds:d})}),n.post("/v1/sessions",async(r,i)=>{let o=r.body??{},a=Te(o.cwd??t.cwd),d=o.agentId??t.agentId,c=ft(s),l=c!==void 0?[...o.mcpServers??[],...c.descriptors]:o.mcpServers;try{let u=await e.create({cwd:a,agentId:d,mcpServers:l});c!==void 0&&c.bindToSession(u),i.code(201).send({sessionId:u.sessionId,agentId:u.agentId,cwd:u.cwd})}catch(u){c!==void 0&&c.abandon(u instanceof Error?u:void 0),i.code(500).send({error:u.message})}}),n.post("/v1/sessions/collect",async(r,i)=>{let o=r.body??{},a=typeof o.maxAgeDays=="number"&&o.maxAgeDays>0?o.maxAgeDays*24*60*60*1e3:0,d=typeof o.limit=="number"&&o.limit>0?o.limit:1e3,c=o.selection==="explicit"||o.selection==="unpromoted"?o.selection:"unpromoted";try{let l=await Dn({manager:e,maxAgeMs:a,maxDeletions:d,selection:c,verbose:!1});i.code(200).send(l)}catch(l){i.code(500).send({error:l.message})}}),n.post("/v1/sessions/:id/kill",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(d){d.close({deleteRecord:!1}).catch(()=>{}),i.code(202).send();return}if(!await e.hasRecord(a)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(!d)return i.code(404).send({error:"session not found"}),i;let c=r.body??{},l={};(c.mode==="memory"||c.mode==="file")&&(l.mode=c.mode),typeof c.capacityBytes=="number"&&(l.capacityBytes=c.capacityBytes),typeof c.fileCapBytes=="number"&&(l.fileCapBytes=c.fileCapBytes),(l.mode??"memory")==="file"&&(l.filePathFor=u=>fi.join(pt.tmpdir(),`hydra-acp-stdin-${u}.log`));try{return d.openStream(l)}catch(u){return i.code(409).send({error:u.message}),i}}),n.post("/v1/sessions/:id/stdin",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(!d)return i.code(404).send({error:"session not found"}),i;let c=r.body??{},l=typeof c.chunk=="string"?c.chunk:"",u=c.eof===!0;try{return d.streamWrite(l,u)}catch(f){return i.code(409).send({error:f.message}),i}}),n.patch("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.body??{};if(d.priority!==void 0){let l=d.priority,u;if(l===null||l===0)u=void 0;else if(typeof l=="number"&&Number.isInteger(l)&&l>0)u=l;else{i.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(a,u)){i.code(404).send({error:"session not found"});return}i.code(204).send();return}if(d.regen===!0){if(!(e.get(a)!==void 0||await e.hasRecord(a))){i.code(404).send({error:"session not found"});return}e.scheduleSynopsis(a),i.code(202).send();return}if(typeof d.title!="string"||d.title.trim().length===0){i.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(a,d.title)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.delete("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(d){await d.close({deleteRecord:!0}),i.code(204).send();return}if(!await e.deleteRecord(a)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.get("/v1/sessions/:id/export",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.query?.tools,c=d==="references"?"references":mr(d),l=await e.exportBundle(a,c==="references"?{tools:"references"}:{});if(!l){i.code(404).send({error:"session not found"});return}let u=st({record:l.record,history:c==="summary"?hr(l.history,"summary"):l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,...l.toolBlobs!==void 0?{toolBlobs:l.toolBlobs}:{},hydraVersion:G,machine:pt.hostname(),hydraHost:li(t)}),f=new Date().toISOString().replace(/[:.]/g,"-");i.header("Content-Disposition",`attachment; filename="${a}-${f}.hydra"`),i.code(200).send(u)}),n.get("/v1/sessions/:id/diff",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.exportBundle(a);if(!d){i.code(404).send({error:"session not found"});return}let c=r.query??{},l=c.fold==="true"||c.fold==="1",u=typeof c.paths=="string"&&c.paths.length>0?new Set(c.paths.split(",").map(p=>p.trim()).filter(p=>p.length>0)):void 0,f=ni(d.history);u&&(f=f.filter(p=>u.has(p.path))),l&&(f=f.map(p=>({...p,hunks:si(p.hunks)}))),i.code(200).send(f)}),n.get("/v1/sessions/:id/tools/:hash",async(r,i)=>{let o=r.params,a=await e.resolveCanonicalId(o.id)??o.id,d=await e.loadToolBlob(a,o.hash);if(d===null){i.code(404).send({error:"tool blob not found"});return}i.header("Content-Type","text/plain; charset=utf-8"),i.code(200).send(d)}),n.get("/v1/sessions/:id/transcript",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.exportBundle(a);if(!d){i.code(404).send({error:"session not found"});return}let c=st({record:d.record,history:d.history,promptHistory:d.promptHistory.length>0?d.promptHistory:void 0,hydraVersion:G,machine:pt.hostname(),hydraHost:li(t)});i.header("Content-Type","text/markdown; charset=utf-8"),i.code(200).send(ri(c))}),n.post("/v1/sessions/:id/fork",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.body??{},c={};if(d.forkAt!==void 0){if(typeof d.forkAt!="string"||d.forkAt.length===0){i.code(400).send({error:"forkAt must be a non-empty string"});return}c.forkAt=d.forkAt}if(d.cwd!==void 0){if(typeof d.cwd!="string"||d.cwd.length===0){i.code(400).send({error:"cwd must be a non-empty string"});return}c.cwd=Te(d.cwd)}if(d.agentId!==void 0){if(typeof d.agentId!="string"||d.agentId.length===0){i.code(400).send({error:"agentId must be a non-empty string"});return}c.agentId=d.agentId}if(d.title!==void 0){if(typeof d.title!="string"){i.code(400).send({error:"title must be a string"});return}c.title=d.title}try{let l=await e.forkSession(a,c);i.code(201).send(l)}catch(l){let u=l;if(u.code===I.SessionNotFound){i.code(404).send({error:u.message});return}if(u.code===I.InvalidParams||u.code===I.AgentNotInstalled){i.code(400).send({error:u.message});return}i.code(500).send({error:u.message})}}),n.post("/v1/sessions/import",async(r,i)=>{let o=r.body??{};if(o.bundle===void 0){i.code(400).send({error:"missing bundle"});return}let a;if(o.cwd!==void 0){if(typeof o.cwd!="string"||o.cwd.length===0){i.code(400).send({error:"cwd must be a non-empty string"});return}a=o.cwd}let d;try{d=Ar(o.bundle)}catch(c){i.code(400).send({error:"invalid bundle",details:c.message});return}try{let c=await e.importBundle(d,{replace:o.replace===!0,...a!==void 0?{cwd:a}:{}});i.code(201).send(c)}catch(c){let l=c;if(l.code===I.BundleAlreadyImported){i.code(409).send({error:"bundle already imported",existingSessionId:l.existingSessionId});return}i.code(500).send({error:l.message})}}),n.get("/v1/sessions/:id/history",async(r,i)=>{let o=r.params.id,a=r.query,d=a?.follow==="1"||a?.follow==="true",c=await e.resolveCanonicalId(o)??o,l=e.get(c),u,f,p=!1,g=1e4,m=[];if(l){d&&(f=l.onBroadcast(y=>{i.raw.writableEnded||(p?i.raw.write(JSON.stringify(y)+`
|
|
109
|
-
`):(
|
|
110
|
-
`);let
|
|
111
|
-
`)}}return p=!0,f||i.raw.end(),i})}function gi(n,e,t,s={}){n.get("/v1/agents",async()=>Oe(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await se(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===I.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function mi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pc=/^[A-Za-z0-9._-]+$/;function Vt(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=gc(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){gt(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){gt(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){gt(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){gt(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){gt(o,d)}})}function gt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function gc(n){let e=n.name;if(typeof e!="string"||!pc.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function hi(n,e){Vt(n,"extension",e)}function yi(n,e){Vt(n,"transformer",e)}function wi(n,e){n.get("/v1/config",async()=>e)}import{z as We}from"zod";import*as ze from"fs/promises";import*as vi from"path";import{randomBytes as Zp,scrypt as mc,timingSafeEqual as hc}from"crypto";import{promisify as yc}from"util";var wc=yc(mc);function Ii(){return vi.join(w.home(),"password-hash")}var vc=128*1024*1024;async function bi(){try{return(await ze.readFile(Ii(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Si(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ze.readFile(Ii(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await wc(n,o,a.length,{N:s,r,p:i,maxmem:vc});return d.length!==a.length?!1:hc(d,a)}var Ic=We.object({password:We.string().min(1),label:We.string().min(1).max(256).optional(),ttlSec:We.number().int().positive().optional()}),bc=We.object({id:We.string().optional()}).optional();function ki(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Sc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ic.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await bi())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Si(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=bc.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Sc(n){return n.ip||"unknown"}import{nanoid as Yn}from"nanoid";function zn(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as Mc}from"crypto";import*as xi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Rc(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ie(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function Wn(n,e){let t=ft(n),s;try{s=await n.manager.resurrect({...e,mcpServers:t?.descriptors})}catch(r){throw t!==void 0&&t.abandon(r instanceof Error?r:void 0),r}return t!==void 0&&t.bindToSession(s),Fc(s,n),s}function Ci(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Qr({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=zn(t),a=new Ae(o),d={clientId:`hydra_client_${Yn(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,f)=>{if(d.attached.get(u)?.readonly)throw _(I.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Es.parse(u??{});f.clientInfo?.name&&(d.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),$c()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},g=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let A={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(A.outputSchema=y.outputSchema),A}).filter(h=>h!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,g=typeof f.method=="string"?f.method:void 0,m=f.envelope,h=f.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=ie(e.manager,p),A=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(A)return y.dischargeClaim(A,m),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,g,m)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,g,m)};throw _(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw _(-32602,"hydra-acp/session/request_permission requires sessionId");return ie(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Tc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,h=f._meta&&typeof f._meta=="object"?f._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,A=y&&typeof y.title=="string"?y.title:void 0,k=y&&typeof y.model=="string"?y.model:void 0;if(!g&&m){let j=e.manager.get(m);j&&(g=j.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let b=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:b,transformChain:[],title:A,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw _(I.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw _(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=e.manager.get(p);if(g)return await g.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw _(I.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,g=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=ie(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let b=[],N=[],j=0,K=!1,J,R,P=!1,H=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(K?{entries:b,truncated:!0}:{entries:b}))};J=h.onBroadcast(q=>{let D=Rc(q);for(b.push(q),N.push(D),j+=D;b.length>0&&(b.length>1e3||j>1048576);)b.shift(),j-=N.shift()??0,K=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&H()});let B=setTimeout(H,m);typeof B.unref=="function"&&B.unref(),R=h.onClose(()=>H())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw _(-32602,"close_child_session requires childSessionId");let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,g=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw _(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=await e.manager.loadToolBlob(p,f.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>Ec(u,e)),a.onRequest("session/new",async u=>{let f=Ps.parse(u),p=Ye(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(R=>typeof R=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,A=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Mc(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let P={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};A=[...f.mcpServers??[],P]}let k=ft(e);k!==void 0&&(A=[...A??[],...k.descriptors]);let b;try{b=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:A,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Ai(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),k!==void 0&&k.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,P=e.mcpTokenRegistry;y.complete(b),b.onClose(()=>{P.unbind(R)})}k!==void 0&&k.bindToSession(b);let N,j;try{N=Gt(a,b,d),{entries:j}=await b.attach(N,"full")}catch(R){throw await b.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of j){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let K=Qn(b),J=Vn(b);return{sessionId:b.sessionId,...K?{modes:K}:{},...J?{models:J}:{},configOptions:b.buildConfigOptions(),_meta:Gn(e.manager,b,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=_s.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ye(f._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${h}`);let A=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,k=e.manager.get(A);if(!k&&h){let P=await e.manager.loadFromDisk(A);if(!P)throw _(I.SessionNotFound,`session ${f.sessionId} not found`);let H=await e.manager.loadHistory(A),B=f.clientId??`cli_${Yn(8)}`;d.attached.set(P.hydraSessionId,{sessionId:P.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${P.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${H.length}`);for(let q of H)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:H.length,_meta:_c(P)}}if(!k){let P=await e.manager.loadFromDisk(A),H=P;if(m&&(H={...P,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!H)throw _(I.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);let B=H.originatingClient?H:{...H,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;k=await Wn(e,{...q,onInstallProgress:Ai(a)})}let b=Gt(a,k,d,f.clientInfo,f.clientId),N=g.replayMode==="drip",{entries:j,appliedPolicy:K}=await k.attach(b,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:N,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:b.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(k.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${k.sessionId} clientId=${b.clientId} attachedCount=${d.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${K} replayed=${j.length} readonly=${h}${N?" replayMode=drip":""}`),N){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,H=750;(async()=>{let B=null;for(let q of j){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let he=Math.min(H,Math.max(0,(D-B)/P));he>0&&await new Promise(en=>setTimeout(en,he))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<j.length&&!a.isClosed();P++){let H=j[P],B=a.notify(H.method,H.params).catch(()=>{});(P+1)%200===0&&await B}k.replayPendingPermissions(b);let J=Qn(k),R=Vn(k);return{sessionId:k.sessionId,clientId:b.clientId,connectedClients:k.connectedClients(b.clientId),historyPolicy:K,replayed:j.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:k.buildConfigOptions(),_meta:Gn(e.manager,k)}}),a.onRequest("session/detach",async u=>{let f=$s.parse(u),p=d.attached.get(f.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(f.sessionId);return g?.detach(p.clientId),d.attached.delete(f.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Ge]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Fs.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(h=>h.originatingClient?.name!==Rt).map(Os)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return Oe(e.registry)}),a.onRequest("session/prompt",async u=>{let f=Ns.parse(u);c(f.sessionId,"session/prompt");let p=d.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),_(I.SessionNotFound,"not attached to session");let g=e.manager.get(f.sessionId);if(!g){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw _(I.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),g=await Wn(e,m);let h=Gt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,f)});let l=u=>{let f;try{f=bt.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let g=e.manager.get(f.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=bt.parse(u);return c(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Hs.parse(u);return c(f.sessionId,"hydra-acp/prompt/cancel"),ie(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=bt.parse(u);return c(f.sessionId,"hydra-acp/session/force_cancel"),ie(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Bs.parse(u);return c(f.sessionId,"hydra-acp/prompt/update"),ie(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Us.parse(u);c(f.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(f.sessionId);if(!p)throw _(I.SessionNotFound,"not attached to session");return ie(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw _(I.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let b=await e.manager.loadFromDisk(g);if(!b)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Wn(e,b)}let h=Gt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}m.replayPendingPermissions(h);let A=Qn(m),k=Vn(m);return{sessionId:m.sessionId,...A?{modes:A}:{},...k?{models:k}:{},configOptions:m.buildConfigOptions(),_meta:Gn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=Pc(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),_(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:g}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw _(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw _(I.InvalidParams,"session/set_mode requires string modeId");let g=ie(e.manager,f.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=y=>_(I.InvalidParams,y),g=f?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=ie(e.manager,f.sessionId),h=m.buildConfigOptions().find(y=>y.id===f.configId);if(!h)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!h.options.some(y=>y.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{if(!f.startsWith("session/")||u===null||typeof u!="object")throw _(I.MethodNotFound,`Method not found: ${f}`);let p=u.sessionId;if(typeof p!="string")throw _(I.MethodNotFound,`Method not found: ${f}`);return c(p,f),ie(e.manager,p).forwardRequest(f,u)})})}async function Ec(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw _(I.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let f=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(f)}let d=a.authMethods??[],c=d.find(f=>f.id===s);if(!c){let f=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${f.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=c._meta?.type;if((c.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let f=c._meta?.args,p=[];if(f!==void 0){if(!Array.isArray(f))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${f===null?"null":typeof f}`);for(let y of f)if(typeof y!="string")throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);p=f}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,A]of Object.entries(process.env))typeof A=="string"&&(m[y]=A);Object.assign(m,g.env);let h=xi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g.command,args:[...g.args,...p],env:m,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(f){throw Ce(f,a)}}function Ai(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Ds,t).catch(()=>{})}}function Qn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Vn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function Pc(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=je(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function Tc(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw _(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw _(I.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw _(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ie(t.manager,r).addTransformer(i),{ok:!0}}function _c(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[Ge]:It(e,t)}}function Gn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return Ve(e.agentMeta,It(s,r))}function $c(){return{protocolVersion:1,agentInfo:{name:"hydra",version:G},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Ve(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Fc(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Gt(n,e,t,s,r){return{clientId:r??`cli_${Yn(8)}`,connection:n,clientInfo:s}}var Yt=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Oc}from"crypto";import{McpServer as Nc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as jc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Q}from"zod";var Mi="Bearer ";function Kt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Mi))return;let t=e.slice(Mi.length).trim();return t.length>0?t:void 0}function Hc(n){let e=new Nc({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:Q.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:Q.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:Q.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:Q.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Q.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:Q.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Q.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo(),o={outcome:r,writeCursor:i.writeCursor,closed:i.closed};return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent:o}}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:Q.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Q.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Q.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Q.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Q.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Q.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Q.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Q.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Q.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s),i=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:i}}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}),e}var Bc=1e4;function Ri(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=Hc(a),l=new jc({sessionIdGenerator:()=>Oc()});await c.connect(l);let u={server:c,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=Kt(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Bc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let u=await s(d,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Xt=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Wc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Qc}from"crypto";import{Server as Uc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Dc,ListToolsRequestSchema as Lc}from"@modelcontextprotocol/sdk/types.js";var qc=6e4;function Ei(n,e,t,s={}){let r=s.invokeTimeoutMs??qc,i=typeof t=="function"?async()=>t():async()=>t,o=new Uc({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),a=new Map(e.tools.map(d=>[d.name,d]));return o.setRequestHandler(Lc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Dc,async d=>{let c=d.params.name;if(!a.has(c))return Zt(`unknown tool: ${c}`);try{let l=await i(),u=await Jc(e.connection,n,c,d.params.arguments??{},l,r);return zc(u,c)}catch(l){return Zt(l instanceof Error?l.message:String(l))}}),o}async function Jc(n,e,t,s,r,i){let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Error(`extension timeout after ${i}ms`)),i)});try{return await Promise.race([n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function zc(n,e){if(n===null||typeof n!="object")return Zt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Zt(`extension ${e} omitted content array`)}function Zt(n){return{content:[{type:"text",text:n}],isError:!0}}var Vc=1e4;function Pi(n,e,t,s={}){let r=new Map;async function i(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),i(f))}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let A=r.get(l);if(A!==void 0){r.delete(l);for(let k of A.values())await i(k)}}));let p=f.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Ei(u,g,async()=>{let A=e.lookup(l);if(A===void 0)throw new Error("mcp token no longer bound");if(A.session!==void 0)return A.session.sessionId;let k,b=new Promise(j=>{k=setTimeout(()=>j(void 0),Vc)}),N=await Promise.race([A.sessionReady.catch(()=>{}),b]);if(k!==void 0&&clearTimeout(k),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new Wc({sessionIdGenerator:()=>Qc()});return await h.connect(y),f.set(u,{server:h,transport:y}),y}async function d(l,u){let f=Kt(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=l.params.name,m=await a(f,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)})}async function Xc(n,e){eu(n);let t=n.daemon.tls?{key:await Se.readFile(n.daemon.tls.key),cert:await Se.readFile(n.daemon.tls.cert)}:void 0;await Se.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Zc(n.daemon.logLevel),i=Gc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Yc,{options:{handleProtocols:es}}),ln(E=>{i.log.info(E)}),gn(E=>{i.log.info(E)});let o=await Ut.load(),a=new zt,d=new Jt,c=new qt([new Dt(e),new Lt(o),d]),l=Wr({validator:c});i.addHook("onRequest",async(E,fe)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await l(E,fe)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=new Qe(n,{onFetched:()=>{Nr(p,y)}});Un(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>pe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});gs(n.compressToolContent);let h=new Ht,y=new ot(p,m,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,synopsisOnClose:n.synopsisOnClose,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),A=new Nt(as(n),void 0,{tokenRegistry:d}),k=new jt(ds(n),void 0,{tokenRegistry:d});mi(i,G,Br(n));let b=new Yt,N=new Xt,j,K=()=>{if(j!==void 0)return j;let E=i.server.address(),fe=E&&typeof E=="object"?E.port:n.daemon.port;return j=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${fe}`,j};pi(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port},{extensionMcp:N,mcpTokenRegistry:b,getDaemonOrigin:K}),gi(i,p,y,{npmRegistry:n.npmRegistry}),hi(i,A),yi(i,k),wi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},synopsisOnClose:n.synopsisOnClose,defaultTransformers:[...n.defaultTransformers]}),ki(i,{store:o,rateLimiter:a}),Ri(i,b),Pi(i,b,N),Ci(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,fe)=>A.reportVersion(E,fe),onTransformerVersion:(E,fe)=>k.reportVersion(E,fe),transformers:k,extensionCommands:h,mcpTokenRegistry:b,extensionMcp:N,getDaemonOrigin:K,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let J=i.server.address(),R=J&&typeof J=="object"?J.port:n.daemon.port;await Se.mkdir(w.home(),{recursive:!0}),await Se.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
|
|
112
|
-
|
|
134
|
+
`),r}function Rc(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=Eo(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Ec(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Pc(n,e){let t=e.session,s=Rr(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Te(r)}`),n.push("");let o=[];o.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${us(a.size)}`:void 0;c.push(d?`${us(a.used)} / ${d} tokens`:`${us(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}o.push(`- **Usage:** ${c.join(" \xB7 ")}`)}n.push(o.join(`
|
|
135
|
+
`)),n.push("")}function Tc(n,e,t){if(!e.some(d=>_c(d.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,o="",i=!1,a=()=>{o.length!==0&&(n.push(o.trimEnd()),n.push(""),o="")},c=()=>{i||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),i=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),n.push("**User:**"),n.push("");for(let p of d.text.split(`
|
|
136
|
+
`))n.push(`> ${Te(p)}`);n.push(""),n.push("**Assistant:**"),n.push(""),i=!0;break}case"agent-text":c(),o+=d.text;break;case"agent-thought":{c(),a();let p=d.text.split(`
|
|
137
|
+
`);for(let l of p)n.push(`> _${Te(l)}_`);n.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let p=t.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};n.push(`- ${Fc(p.status)} ${$c(p)}`),n.push("");break}case"tool-call-update":break;case"plan":{c(),a(),n.push("**Plan:**"),n.push("");for(let p of d.entries){let l=p.status==="completed"?"[x]":"[ ]";n.push(`- ${l} ${Te(p.content)}`)}n.push("");break}case"mode-changed":c(),a(),n.push(`_mode: ${Te(d.mode)}_`),n.push("");break;case"model-changed":c(),a(),n.push(`_model: ${Te(d.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function _c(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function $c(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Te(n.title)}${t}`}function Fc(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function Te(n){return n.replace(/</g,"<").replace(/>/g,">")}function us(n){return n.toLocaleString("en-US")}function jo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Oc(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,c=[];for(let p of s){let l=p.toUpperCase();l==="AND"?i=!0:l==="OR"?a=!0:c.push(p)}i?o="AND":a&&(o="OR");let d=c.map(p=>Hc(p)).filter(p=>p.term.length>0);return{operator:o,terms:d}}function Hc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Bo(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Bo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Bo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Nc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var jc=5,Bc=200,Uo=30;async function qo(n,e,t={}){let s=Oc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??jc,o=t.maxSessions??Bc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),c=i?a.filter(l=>i.has(l.sessionId)):a,d=[],p=!1;for(let l of c){if(d.length>=o){p=!0;break}let u=await n.loadHistory(l.sessionId).catch(()=>[]),f=Uc(u,s,r);if(f.snippets.length===0)continue;let m={sessionId:l.sessionId,cwd:l.cwd,status:l.status,updatedAt:l.updatedAt,totalMatches:f.totalMatches,snippets:f.snippets};l.title!==void 0&&(m.title=l.title),d.push(m)}return{query:e,truncated:p,results:d}}function Uc(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=Dc(n,i,o,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Dc(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let c=Lc(a).filter(d=>Nc(t,d.kind));for(let d of c){let p=d.text.toLowerCase(),l=p.indexOf(r);if(l===-1)continue;let u=0;for(;l!==-1;)u++,l=p.indexOf(r,l+r.length);if(o+=u,i.length<s){let f=p.indexOf(r),m={kind:d.kind,text:Qc(d.text,f,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(m.toolName=d.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function Lc(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=sn(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?re(s.text):sn(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(Jc(s))return[];let o=sn(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=Wc(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return qc(s);default:return[]}}function qc(n){let e=Do(n,"name"),t=Do(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Lo(r);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Lo(o);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=zc(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function zc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=W(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=W(s);if(r.length>0)return r}}return null}function Jc(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function sn(n){if(typeof n=="string")return re(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?re(e.text):""}function Wc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=sn(t);s.length>0&&e.push(s)}return e.join("")}function Do(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Lo(n){try{return JSON.stringify(n)}catch{return""}}function Qc(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-Uo),c=Math.min(s.length,i+o.length+Uo),d=a>0?"\u2026":"",p=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${p}`}import{randomBytes as Jo}from"crypto";function zo(n){let e=Jo(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function ls(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(zo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(zo({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let o=Ge(n.deps);return o!==void 0&&(o.bindToSession(s),r=[...r,...o.descriptors]),r}}function Ge(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Jo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{s.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>s.abandon(a)}}var rn=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Wo(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!jo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Vo(n,e,t,s={}){n.get("/v1/sessions",async c=>{let d=c.query,p=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:p})}}),n.get("/v1/sessions/:id",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=await e.getOne(l);return u||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(c,d)=>{let p=c.body??{},l=typeof p.q=="string"?p.q:"";if(l.trim().length===0)return d.code(400).send({error:"q is required"}),d;let u=Array.isArray(p.sessionIds)?p.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await qo(e,l,{sessionIds:u})}),n.post("/v1/sessions",async(c,d)=>{let p=c.body??{},l=Y(p.cwd??t.cwd),u=p.agentId??t.agentId,f=Ge(s),m=f!==void 0?[...p.mcpServers??[],...f.descriptors]:p.mcpServers;try{let g=await e.create({cwd:l,agentId:u,mcpServers:m});f!==void 0&&f.bindToSession(g),d.code(201).send({sessionId:g.sessionId,agentId:g.agentId,cwd:g.cwd})}catch(g){f!==void 0&&f.abandon(g instanceof Error?g:void 0),d.code(500).send({error:g.message})}}),n.post("/v1/sessions/collect",async(c,d)=>{let p=c.body??{},l=typeof p.maxAgeDays=="number"&&p.maxAgeDays>0?p.maxAgeDays*24*60*60*1e3:0,u=typeof p.limit=="number"&&p.limit>0?p.limit:1e3,f=p.selection==="explicit"||p.selection==="unpromoted"?p.selection:"unpromoted";try{let m=await is({manager:e,maxAgeMs:l,maxDeletions:u,selection:f,verbose:!1});d.code(200).send(m)}catch(m){d.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=e.get(l);if(u){u.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(l)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=e.get(l);if(!u)return d.code(404).send({error:"session not found"}),d;let f=c.body??{},m={};(f.mode==="memory"||f.mode==="file")&&(m.mode=f.mode),typeof f.capacityBytes=="number"&&(m.capacityBytes=f.capacityBytes),typeof f.fileCapBytes=="number"&&(m.fileCapBytes=f.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=g=>Qo.join(kt.tmpdir(),`hydra-acp-stdin-${g}.log`));try{return u.openStream(m)}catch(g){return d.code(409).send({error:g.message}),d}}),n.post("/v1/sessions/:id/stdin",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=e.get(l);if(!u)return d.code(404).send({error:"session not found"}),d;let f=c.body??{},m=typeof f.chunk=="string"?f.chunk:"",g=f.eof===!0;try{return u.streamWrite(m,g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.patch("/v1/sessions/:id",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=c.body??{};if(u.priority!==void 0){let m=u.priority,g;if(m===null||m===0)g=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)g=m;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(l,g)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(u.regen===!0){if(!(e.get(l)!==void 0||await e.hasRecord(l))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(l),d.code(202).send();return}if(typeof u.title!="string"||u.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(l,u.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=e.get(l);if(u){await u.close({deleteRecord:!0}),d.code(204).send();return}if(!await e.deleteRecord(l)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.get("/v1/sessions/:id/export",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=c.query?.tools,f=u==="references"?"references":Kr(u),m=await e.exportBundle(l,f==="references"?{tools:"references"}:{});if(!m){d.code(404).send({error:"session not found"});return}let g=ft({record:m.record,history:f==="summary"?Gr(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:K,machine:kt.hostname(),hydraHost:Wo(t)}),h=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${l}-${h}.hydra"`),d.code(200).send(g)}),n.get("/v1/sessions/:id/diff",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=await e.exportBundle(l);if(!u){d.code(404).send({error:"session not found"});return}let f=c.query??{},m=f.fold==="true"||f.fold==="1",g=typeof f.paths=="string"&&f.paths.length>0?new Set(f.paths.split(",").map(y=>y.trim()).filter(y=>y.length>0)):void 0,h=Oo(u.history);g&&(h=h.filter(y=>g.has(y.path))),m&&(h=h.map(y=>({...y,hunks:Ho(y.hunks)}))),d.code(200).send(h)}),n.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let p=c.params,l=await e.resolveCanonicalId(p.id)??p.id,u=await e.loadToolBlob(l,p.hash);if(u===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(u)}),n.get("/v1/sessions/:id/transcript",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=await e.exportBundle(l);if(!u){d.code(404).send({error:"session not found"});return}let f=ft({record:u.record,history:u.history,promptHistory:u.promptHistory.length>0?u.promptHistory:void 0,hydraVersion:K,machine:kt.hostname(),hydraHost:Wo(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(No(f))}),n.post("/v1/sessions/:id/fork",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=c.body??{},f={};if(u.forkAt!==void 0){if(typeof u.forkAt!="string"||u.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}f.forkAt=u.forkAt}if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}f.cwd=Y(u.cwd)}if(u.agentId!==void 0){if(typeof u.agentId!="string"||u.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}f.agentId=u.agentId}if(u.title!==void 0){if(typeof u.title!="string"){d.code(400).send({error:"title must be a string"});return}f.title=u.title}try{let m=await e.forkSession(l,f);d.code(201).send(m)}catch(m){let g=m;if(g.code===S.SessionNotFound){d.code(404).send({error:g.message});return}if(g.code===S.InvalidParams||g.code===S.AgentNotInstalled){d.code(400).send({error:g.message});return}d.code(500).send({error:g.message})}}),n.post("/v1/sessions/import",async(c,d)=>{let p=c.body??{};if(p.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let l;if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}l=p.cwd}let u;try{u=ro(p.bundle)}catch(f){d.code(400).send({error:"invalid bundle",details:f.message});return}try{let f=await e.importBundle(u,{replace:p.replace===!0,...l!==void 0?{cwd:l}:{}});d.code(201).send(f)}catch(f){let m=f;if(m.code===S.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}d.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p,u=e.get(l),f;if(u?f=u.summarizedThroughEntry:f=await e.getSummarizedThroughEntry(l),f===void 0&&!await e.hasRecord(l))return d.code(404).send({error:"session not found"}),d;let m=await e.getCompactionState(l),g=await e.getRollbackBreadcrumb(l),h=!1,y,I=await e.getHistory(l).catch(()=>[])??[];if(I.length>0&&t.compaction){let A=f??0,k=I.length,P=I.slice(A).reduce(($,R)=>$+JSON.stringify(R.params).length,0);y=ds(P);let N=u?.currentModel,U=I.at(-1).recordedAt,H=u?.currentUsage;h=xo({summarizedThroughEntry:A,totalEntries:k,unsummarizedChars:P,compactionInFlight:e.getCompactionInFlight(),currentModel:N,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof H?.used=="number"?{agentReportedUsed:H.used}:{},...typeof H?.size=="number"?{agentReportedSize:H.size}:{}})}return{summarizedThroughEntry:f??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:h,...y!=null?{approxTokens:y}:{},...m!=null?{compactionState:m}:{},...g!=null?{rollbackBreadcrumb:g}:{}}}),n.post("/v1/sessions/:id/compact",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p;if(e.get(l)){e.scheduleCompaction(l),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(l)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(l),d.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(c,d)=>{let p=c.params.id,l=await e.resolveCanonicalId(p)??p;if(!await e.hasRecord(l)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(l),d.code(202).send({rolledBack:!0})}catch(u){let f=u instanceof Error?u.message:String(u);d.code(409).send({error:f})}}),n.get("/v1/sessions/:id/history",async(c,d)=>{let p=c.params.id,l=c.query,u=l?.follow==="1"||l?.follow==="true",f=await e.resolveCanonicalId(p)??p,m=e.get(f),g,h,y=!1,w=1e4,I=[];if(m){u&&(h=m.onBroadcast(k=>{d.raw.writableEnded||(y?d.raw.write(JSON.stringify(k)+`
|
|
138
|
+
`):(I.push(k),I.length>w&&I.shift()))})),c.raw.on("close",()=>{h?.(),d.raw.writableEnded||d.raw.end()});try{g=await m.getHistorySnapshot()}catch(k){throw h?.(),k}}else{let k=await e.getHistory(f);if(k===void 0)return d.code(404).send({error:"session not found"}),d;g=k}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let A=new Set;for(let k of g??[]){d.raw.write(JSON.stringify(k)+`
|
|
139
|
+
`);let M=k;typeof M.recordedAt=="number"&&A.add(String(M.recordedAt))}for(;I.length>0;){let k=I.splice(0,I.length);for(let M of k){let P=M,N=typeof P.recordedAt=="number"?String(P.recordedAt):"";N&&A.has(N)||d.raw.write(JSON.stringify(M)+`
|
|
140
|
+
`)}}return y=!0,h||d.raw.end(),d});function r(c,d,p){let l=typeof c=="string"?c.trim():"";if(l.length===0)return null;let u;try{u=JSON.parse(l)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!u||typeof u!="object"||Array.isArray(u))return console.debug("events endpoint: skipping non-object JSONL line"),null;let f=u;if(typeof f.recordedAt!="number"||p!==void 0&&f.recordedAt<p||typeof f.params!="object"||f.params===null||Array.isArray(f.params))return null;let m=f.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let h=m.update.sessionUpdate;return typeof h!="string"||!d.has(h)?null:{recordedAt:f.recordedAt,entry:u}}function o(c,d,p){let u=d.params.update,f={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:p,update:u};return u.messageId!==void 0&&u.messageId!==null&&(f.messageId=u.messageId),f}async function i(c,d,p,l){let u=fs.createInterface({input:ps.createReadStream(d),crlfDelay:1/0}),f=null;for await(let m of u){let g=r(m,p,l);if(g){let h=g.entry.params.update.sessionUpdate;f={ts:g.recordedAt,row:o(c,g.entry,h)};break}}return{sessionId:c,rl:u,current:f,exhausted:f===null}}async function a(c,d,p){for await(let l of c.rl){let u=r(l,d,p);if(u){let f=u.entry.params.update.sessionUpdate;c.current={ts:u.recordedAt,row:o(c.sessionId,u.entry,f)};return}}c.exhausted=!0}n.get("/v1/sessions/events",async(c,d)=>{let p=c.query,l=p.kinds;if(!l||l.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let u=l.split(",").map(w=>w.trim());if(u.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of u)if(!rn.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...rn].join(", ")}`}),d;let f=new Set(u),m;if(p.since!==void 0&&p.since.trim().length>0){let w=new Date(p.since);if(isNaN(w.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;m=w.getTime()}let g=await e.list({includeNonInteractive:!0}),h=m!==void 0?g.filter(w=>new Date(w.updatedAt).getTime()>=m):g;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let y=[];for(let w of h)try{let I=v.historyFile(w.sessionId),A=await i(w.sessionId,I,f,m);A.exhausted||y.push(A)}catch(I){if(I.code==="ENOENT")continue;throw I}c.raw.on("close",()=>{for(let w of y)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;y.length>0;){let w=-1,I=1/0;for(let k=0;k<y.length;k++){let M=y[k];M.current!==null&&M.current.ts<I&&(I=M.current.ts,w=k)}if(w===-1)break;let A=y[w];if(d.raw.write(JSON.stringify(A.current.row)+`
|
|
141
|
+
`),await a(A,f,m),A.exhausted){try{A.rl.close()}catch{}y.splice(w,1)}}}catch(w){for(let I of y)try{I.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(c,d)=>{let p=c.params.id,l=c.query,u=await e.resolveCanonicalId(p)??p;if(!e.get(u)&&!await e.hasRecord(u))return d.code(404).send({error:"session not found"}),d;let m=l.kinds;if(!m||m.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let g=m.split(",").map(k=>k.trim());if(g.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let k of g)if(!rn.has(k))return d.code(400).send({error:`kind "${k}" is not queryable; allowed kinds: ${[...rn].join(", ")}`}),d;let h=new Set(g),y;if(l.since!==void 0&&l.since.trim().length>0){let k=new Date(l.since);if(isNaN(k.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;y=k.getTime()}let w=v.historyFile(u),I=ps.createReadStream(w),A=fs.createInterface({input:I,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let k of A){let M=typeof k=="string"?k.trim():"";if(M.length===0)continue;let P;try{P=JSON.parse(M)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!P||typeof P!="object"||Array.isArray(P)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let N=P;if(typeof N.recordedAt!="number"||typeof N.params!="object"||N.params===null||Array.isArray(N.params))continue;let U=N.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let H=U.update,$=H.sessionUpdate;if(typeof $!="string"||!h.has($)||y!==void 0&&N.recordedAt<y)continue;let R={ts:new Date(N.recordedAt).toISOString(),kind:$,update:H};H.messageId!==void 0&&H.messageId!==null&&(R.messageId=H.messageId),d.raw.write(JSON.stringify(R)+`
|
|
142
|
+
`)}}catch(k){if(k.code==="ENOENT")return d.raw.end(),d;throw k}return d.raw.end(),d})}function Ko(n,e,t,s={}){n.get("/v1/agents",async()=>He(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await se(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){o.code(500).send({error:c.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:c}=await t.syncFromAgent(i);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===S.AgentNotInstalled){o.code(404).send({error:c.message});return}o.code(409).send({error:c.message})}})}function Go(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Vc=/^[A-Za-z0-9._-]+$/;function on(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,c=t.get(a);if(!c){i.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(o,i)=>{let a=o.body??{},c=Kc(a);if("error"in c){i.code(400).send({error:c.error});return}try{let d=t.register(c.config);i.code(201).send(d)}catch(d){At(i,d)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(c){At(i,c)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let c=await t.startByName(a);i.code(200).send(c)}catch(c){At(i,c)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let c=await t.stopByName(a);i.code(200).send(c)}catch(c){At(i,c)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let c=await t.restartByName(a);i.code(200).send(c)}catch(c){At(i,c)}})}function At(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function Kc(n){let e=n.name;if(typeof e!="string"||!Vc.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function Yo(n,e){on(n,"extension",e)}function Xo(n,e){on(n,"transformer",e)}function Zo(n,e){n.get("/v1/config",async()=>e)}import{z as Xe}from"zod";import*as Ye from"fs/promises";import*as ei from"path";import{randomBytes as tg,scrypt as Gc,timingSafeEqual as Yc}from"crypto";import{promisify as Xc}from"util";var Zc=Xc(Gc);function ti(){return ei.join(v.home(),"password-hash")}var eu=128*1024*1024;async function ni(){try{return(await Ye.readFile(ti(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function si(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Ye.readFile(ti(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let c=await Zc(n,i,a.length,{N:s,r,p:o,maxmem:eu});return c.length!==a.length?!1:Yc(c,a)}var tu=Xe.object({password:Xe.string().min(1),label:Xe.string().min(1).max(256).optional(),ttlSec:Xe.number().int().positive().optional()}),nu=Xe.object({id:Xe.string().optional()}).optional();function ri(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=su(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=tu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await ni())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await si(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=nu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function su(n){return n.ip||"unknown"}import{nanoid as vs}from"nanoid";function ms(n){let e=[],t=[],s=!1,r=o=>{if(!s){s=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:S.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,c)=>{n.send(i,d=>{if(d){c(d);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){s||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(c),o())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as ii}from"crypto";import*as ai from"os";function O(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function du(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,o=s.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=s.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function ae(n,e,t){let s=n.get(e);if(!s)throw O(S.SessionNotFound,t??`session ${e} not found`);return s}async function gs(n,e){let t=Ge(n),s,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=ii(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],c=ls({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),d;try{d=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(p){throw t!==void 0&&t.abandon(p instanceof Error?p:void 0),r!==void 0&&r.abandon(p instanceof Error?p:void 0),p}if(t!==void 0&&t.bindToSession(d),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let p=s,l=n.mcpTokenRegistry;r.complete(d),d.onClose(()=>{l.unbind(p)})}return mu(d,n),d}function di(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Co({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=ms(t),a=new Re(i),c={clientId:`hydra_client_${vs(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let l of c.attached.values())e.manager.get(l.sessionId)?.detach(l.clientId);c.attached.clear()});let d=(l,u)=>{if(c.attached.get(l)?.readonly)throw O(S.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async l=>{let u=Zs.parse(l??{});u.clientInfo?.name&&(c.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let f=u.clientInfo?.version;return f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f)),fu()}),o&&e.extensionCommands){let l=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let f=u??{},m=Array.isArray(f.commands)?f.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(g=>g!==void 0):[];return l.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{l.clear(o.name)})}if(o&&e.extensionMcp){let l=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let f=u??{},m=typeof f.instructions=="string"?f.instructions:void 0,g=Array.isArray(f.tools)?f.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let w={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(w.outputSchema=y.outputSchema),w}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return l.register(o.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{l.clear(o.name)})}o?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async l=>{let u=l??{},f=Array.isArray(u.intercepts)?u.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,f),e.manager?.defaultTransformers.includes(o.name))){let m=e.transformers.resolveChain([o.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async l=>{let u=l??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,m=typeof u.method=="string"?u.method:void 0,g=u.envelope,h=u.route;if(!f||!m)throw O(-32602,"emit_message requires sessionId and method");let y=ae(e.manager,f),w=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(w)return y.dischargeClaim(w,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(o.name,m,g)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(o.name,m,g)};throw O(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async l=>{let u=l??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(!f)throw O(-32602,"hydra-acp/session/request_permission requires sessionId");return ae(e.manager,f).requestPermissionFromClients(u)}),a.onRequest("hydra-acp/transformer/attach",async l=>lu(l,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async l=>{let u=l??{},f=typeof u.agentId=="string"?u.agentId:e.defaultAgent,m=typeof u.cwd=="string"?u.cwd:void 0,g=typeof u.parentSessionId=="string"?u.parentSessionId:void 0,h=u._meta&&typeof u._meta=="object"?u._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,w=y&&typeof y.title=="string"?y.title:void 0,I=y&&typeof y.model=="string"?y.model:void 0;if(!m&&g){let M=e.manager.get(g);M&&(m=M.cwd)}if(!m)throw O(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:f,cwd:m,parentSessionId:g,interactive:A,transformChain:[],title:w,model:I})).sessionId}}),a.onRequest("hydra-acp/session/fork",async l=>{let u=l??{};if(typeof u.sessionId!="string")throw O(S.InvalidParams,"fork_session requires sessionId");let f=typeof u.forkAt=="string"?u.forkAt:void 0,m=typeof u.cwd=="string"?u.cwd:void 0,g=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...f!==void 0?{forkAt:f}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{}})}),a.onRequest("hydra-acp/session/delete",async l=>{let u=l??{};if(typeof u.sessionId!="string")throw O(S.InvalidParams,"hydra-acp/session/delete requires sessionId");let f=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=e.manager.get(f);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:f};if(!await e.manager.deleteRecord(f))throw O(S.SessionNotFound,`session ${f} not found`);return{deleted:!0,sessionId:f}}),a.onRequest("hydra-acp/child_session/await",async l=>{let u=l??{},f=typeof u.childSessionId=="string"?u.childSessionId:void 0,m=u.until==="idle"?"idle":"turn_complete",g=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,18e5):3e5;if(!f)throw O(-32602,"await_child requires childSessionId");let h=ae(e.manager,f,`child session ${f} not found`);return new Promise(y=>{let A=[],k=[],M=0,P=!1,N,U,H=!1,$=()=>{H||(H=!0,clearTimeout(R),N?.(),U?.(),y(P?{entries:A,truncated:!0}:{entries:A}))};N=h.onBroadcast(q=>{let z=du(q);for(A.push(q),k.push(z),M+=z;A.length>0&&(A.length>1e3||M>1048576);)A.shift(),M-=k.shift()??0,P=!0;m==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&$()});let R=setTimeout($,g);typeof R.unref=="function"&&R.unref(),U=h.onClose(()=>$())})}),a.onRequest("hydra-acp/child_session/close",async l=>{let u=l??{},f=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!f)throw O(-32602,"close_child_session requires childSessionId");let m=e.manager.get(f);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async l=>{let u=l??{},f=typeof u.token=="string"?u.token:void 0,m=typeof u.sessionId=="string"?u.sessionId:void 0,g=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return f&&m&&e.manager.get(m)?.keepAliveClaim(f,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async l=>{let u=l??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw O(S.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let f=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(f,u.hash);if(m===null)throw O(S.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async l=>cu(l,e)),a.onRequest("session/new",async l=>{let u=er.parse(l),f=ot(l?._meta),m=Array.isArray(f.transformers)&&f.transformers.every(R=>typeof R=="string")?f.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,w=u.mcpServers;if(f.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=ii(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let q={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};w=[...u.mcpServers??[],q]}let I,A,k=Ge(e);k!==void 0&&(w=[...w??[],...k.descriptors]);let M=ls({baselineMcpServers:u.mcpServers,stdinEnabled:f.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:u.cwd,agentId:f.agentId??e.defaultAgent,mcpServers:w,title:f.title,agentArgs:f.agentArgs,model:f.model,onInstallProgress:oi(a),transformChain:g,originatingClient:c.clientInfo,...f.interactive!==void 0?{interactive:f.interactive}:{},...f.env!==void 0?{forwardedEnv:f.env}:{},...M?{mintMcpServersForSwap:M}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),A!==void 0&&A.abandon(R instanceof Error?R:void 0),k!==void 0&&k.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,q=e.mcpTokenRegistry;y.complete(P),P.onClose(()=>{q.unbind(R)})}if(I!==void 0&&A!==void 0&&e.mcpTokenRegistry!==void 0){let R=I,q=e.mcpTokenRegistry;A.complete(P),P.onClose(()=>{q.unbind(R)})}k!==void 0&&k.bindToSession(P);let N,U;try{N=an(a,P,c),{entries:U}=await P.attach(N,"full")}catch(R){throw await P.close({deleteRecord:!1}).catch(()=>{}),R}c.attached.set(P.sessionId,{sessionId:P.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of U){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let H=hs(P),$=ys(P);return{sessionId:P.sessionId,...H?{modes:H}:{},...$?{models:$}:{},configOptions:P.buildConfigOptions(),_meta:ws(e.manager,P,{clientId:N.clientId})}}),a.onRequest("session/attach",async l=>{let u=nr.parse(l),f=u.clientInfo?.version;f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f));let m=ot(u._meta),g=m.resume,h=m.readonly===!0,y=m.env;n.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!g} readonly=${h}`);let w=g?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,I=e.manager.get(w);if(!I&&h){let $=await e.manager.loadFromDisk(w);if(!$)throw O(S.SessionNotFound,`session ${u.sessionId} not found`);let R=await e.manager.loadHistory(w),q=u.clientId??`cli_${vs(8)}`;c.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:q,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${q} attachedCount=${c.attached.size} replayed=${R.length}`);for(let z of R)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:q,connectedClients:[q],historyPolicy:"full",replayed:R.length,_meta:pu($)}}let A=!I;if(!I){let $=await e.manager.loadFromDisk(w),R=$;if(g&&(R={...$,hydraSessionId:u.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!R)throw O(S.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);let q=R.originatingClient?R:{...R,originatingClient:c.clientInfo},z=y!==void 0?{...q,forwardedEnv:y}:q;I=await gs(e,{...z,onInstallProgress:oi(a)})}let k=an(a,I,c,u.clientInfo,u.clientId),M=m.replayMode==="drip",{entries:P,appliedPolicy:N}=await I.attach(k,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:M,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(I.sessionId,{sessionId:I.sessionId,clientId:k.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(I.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${I.sessionId} clientId=${k.clientId} attachedCount=${c.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${N} replayed=${P.length} readonly=${h}${M?" replayMode=drip":""}`),M){let $=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,R=750;(async()=>{let q=null;for(let z of P){let de=typeof z.recordedAt=="number"?z.recordedAt:null;if(q!==null&&de!==null){let tt=Math.min(R,Math.max(0,(de-q)/$));tt>0&&await new Promise(Ct=>setTimeout(Ct,tt))}de!==null&&(q=de);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let $=0;$<P.length&&!a.isClosed();$++){let R=P[$],q=a.notify(R.method,R.params).catch(()=>{});($+1)%200===0&&await q}I.replayPendingPermissions(k);let U=hs(I),H=ys(I);return{sessionId:I.sessionId,clientId:k.clientId,connectedClients:I.connectedClients(k.clientId),historyPolicy:N,replayed:P.length,...U?{modes:U}:{},...H?{models:H}:{},configOptions:I.buildConfigOptions(),_meta:ws(e.manager,I,{resurrected:A})}}),a.onRequest("session/detach",async l=>{let u=sr.parse(l),f=c.attached.get(u.sessionId);if(!f)throw O(S.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(f.clientId),c.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[rt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async l=>{let u=rr.parse(l??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(h=>h.originatingClient?.name!==Bt).map(or)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw O(S.InternalError,"agent registry unavailable");return He(e.registry)}),a.onRequest("session/prompt",async l=>{let u=ir.parse(l);d(u.sessionId,"session/prompt");let f=c.attached.get(u.sessionId);if(!f)throw n.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),O(S.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let g=await e.manager.loadFromDisk(u.sessionId);if(!g)throw O(S.SessionNotFound,`session ${u.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),m=await gs(e,g);let h=an(a,m,c,void 0,f.clientId);await m.attach(h,"none")}return m.prompt(f.clientId,u)});let p=l=>{let u;try{u=_t.parse(l)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let f=c.attached.get(u.sessionId);if(!f)return;if(f.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(f.clientId).catch(g=>{n.log.warn(`session/cancel for ${u.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",p),a.onRequest("session/cancel",async l=>{let u=_t.parse(l);return d(u.sessionId,"session/cancel"),p(l),null}),a.onRequest("hydra-acp/prompt/cancel",async l=>{let u=dr.parse(l);return d(u.sessionId,"hydra-acp/prompt/cancel"),ae(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async l=>{let u=_t.parse(l);return d(u.sessionId,"hydra-acp/session/force_cancel"),ae(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async l=>{let u=cr.parse(l);return d(u.sessionId,"hydra-acp/prompt/update"),ae(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async l=>{let u=ur.parse(l);d(u.sessionId,"hydra-acp/prompt/amend");let f=c.attached.get(u.sessionId);if(!f)throw O(S.SessionNotFound,"not attached to session");return ae(e.manager,u.sessionId).amendPrompt(f.clientId,u)}),a.onRequest("session/load",async l=>{let u=l??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(!f)throw O(S.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(f)??f,g=e.manager.get(m);if(!g){let A=await e.manager.loadFromDisk(m);if(!A)throw O(S.SessionNotFound,`session ${f} not found in memory or on disk`);g=await gs(e,A)}let h=an(a,g,c),{entries:y}=await g.attach(h,"pending_only");c.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let A of y){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}g.replayPendingPermissions(h);let w=hs(g),I=ys(g);return{sessionId:g.sessionId,...w?{modes:w}:{},...I?{models:I}:{},configOptions:g.buildConfigOptions(),_meta:ws(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async l=>{let u=l?.sessionId;typeof u=="string"&&d(u,"session/set_model");let f=uu(l,e.manager);if(f.kind==="error")throw n.log.warn(f.logMessage),O(f.code,f.message);if(f.kind==="no_op")return n.log.warn(f.logMessage),await a.notify("session/update",{sessionId:f.sessionId,update:{sessionUpdate:"current_model_update",currentModel:f.currentModel}}).catch(()=>{}),null;n.log.info(f.logMessage);let{modelId:m}=f,g=await f.session.forwardRequest("session/set_model",{...l,modelId:m});return f.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async l=>{let u=l,f=u?.sessionId;if(typeof f=="string"&&d(f,"session/set_mode"),!u||typeof u.sessionId!="string")throw O(S.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw O(S.InvalidParams,"session/set_mode requires string modeId");let m=ae(e.manager,u.sessionId),g=await m.forwardRequest("session/set_mode",l);return m.applyModeChange(u.modeId),g}),a.onRequest("session/set_config_option",async l=>{let u=l,f=y=>O(S.InvalidParams,y),m=u?.sessionId;if(typeof m=="string"&&d(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw f("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw f("session/set_config_option requires string configId");if(typeof u.value!="string")throw f("session/set_config_option requires string value");let g=ae(e.manager,u.sessionId),h=g.buildConfigOptions().find(y=>y.id===u.configId);if(!h)throw f(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!h.options.some(y=>y.value===u.value))throw f(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),g.applyModelChange(u.value);break}case"mode":{u.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),g.applyModeChange(u.value);break}case"agent":{u.value!==g.agentId&&await g.setAgent(u.value);break}default:throw f(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(l,u)=>{if(!u.startsWith("session/")||l===null||typeof l!="object")throw O(S.MethodNotFound,`Method not found: ${u}`);let f=l.sessionId;if(typeof f!="string")throw O(S.MethodNotFound,`Method not found: ${u}`);return d(f,u),ae(e.manager,f).forwardRequest(u,l)})})}async function cu(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw O(S.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let u=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(u)}let c=a.authMethods??[],d=c.find(u=>u.id===s);if(!d){let u=c.map(f=>f.id);throw O(S.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${u.map(f=>JSON.stringify(f)).join(", ")}]`)}let p=d._meta?.type;if((d.type??(p==="agent"||p==="terminal"?p:"agent"))==="terminal"){let u=d._meta?.args,f=[];if(u!==void 0){if(!Array.isArray(u))throw O(S.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${u===null?"null":typeof u}`);for(let y of u)if(typeof y!="string")throw O(S.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);f=u}let m=await e.manager.planSpawnForAgent(a.agentId),g={};for(let[y,w]of Object.entries(process.env))typeof w=="string"&&(g[y]=w);Object.assign(g,m.env);let h=ai.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m.command,args:[...m.args,...f],env:g,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(u){throw ke(u,a)}}function oi(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(lr,t).catch(()=>{})}}function hs(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function ys(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function uu(n,e){if(!n||typeof n!="object")return{kind:"error",code:S.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:S.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:S.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:S.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=Ue(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(c=>c.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:S.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function lu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw O(S.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw O(S.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw O(S.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ae(t.manager,r).addTransformer(o),{ok:!0}}function pu(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[rt]:Tt(e,t)}}function ws(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return st(e.agentMeta,Tt(s,r))}function fu(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:st(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function mu(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function an(n,e,t,s,r){return{clientId:r??`cli_${vs(8)}`,connection:n,clientInfo:s}}var dn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((i,a)=>{t=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as gu}from"crypto";import{McpServer as hu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as yu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as G}from"zod";function*bs(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;if(s.method!=="session/update")continue;let o=s.params?.update;!o||typeof o.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:o.sessionUpdate,update:o})}}function ne(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var ci="Bearer ";function Ze(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(ci))return;let t=e.slice(ci.length).trim();return t.length>0?t:void 0}function wu(n){let e=new hu({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:G.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return ne(s)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:G.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return ne(s)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:G.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:G.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:G.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let o=await n.streamRead(t,s,r);return ne(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:G.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:G.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),o=n.streamInfo();return ne({outcome:r,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:G.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:G.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:G.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:G.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:G.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:G.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:G.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:G.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:G.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return ne(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return ne(t)}),e}var vu=1e4;function ui(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let d=wu(a),p=new yu({sessionIdGenerator:()=>gu()});await d.connect(p);let l={server:d,transport:p};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await p.close()}catch{}try{await d.close()}catch{}}),p}async function r(i,a){let c=Ze(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let p;if(d.session!==void 0)p=d.session;else{let u,f=new Promise(g=>{u=setTimeout(()=>g(void 0),vu)}),m=await Promise.race([d.sessionReady.catch(()=>{}),f]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}p=m}let l=await s(c,p);a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as bu}from"crypto";import{McpServer as Iu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Su}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ce}from"zod";function ku(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Au(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function Cu(n){let e=new Iu({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 `recall_search` to find entries by keyword, `recall_range` to pull a contiguous slice verbatim, and `recall_tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("recall_search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via recall_range. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:Ce.string().min(1).describe("Case-insensitive substring to search for."),limit:Ce.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ce.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return ne({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. recall_search retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=await o.getHistorySnapshot(),a=[];for(let{entryId:d,entry:p,kind:l}of bs(i)){if(l==="tool_call"&&!r)continue;let u=De([p]),f=u.toLowerCase().indexOf(t.toLowerCase());if(f<0)continue;let m=ku(l),g=Au(u,f),h=typeof p.recordedAt=="number"?String(p.recordedAt):void 0;if(a.push({entryId:d,speaker:m,snippet:g,timestamp:h}),a.length>=s)break}let c=a.length>=s&&a.length<i.length;return ne({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("recall_range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after recall_search narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Ce.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ce.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return ne({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. recall_range retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`recall_range: to_entry (${s}) must be >= from_entry (${t})`);let o=s-t+1;if(o>50)throw new Error(`recall_range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getHistorySnapshot(),a=Math.min(t,i.length-1),c=Math.min(s,i.length-1),d=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let p=i.slice(a,c+1),l=De(p);return{content:[{type:"text",text:l}],structuredContent:{text:l,entry_count:p.length,truncated:d}}}),e.registerTool("recall_tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:Ce.string().optional(),file_path:Ce.string().optional(),limit:Ce.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return ne({calls:[],truncated:!1,note:"This session has no compacted history. recall_tool_calls retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let i=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!i&&!a)throw new Error("recall_tool_calls: at least one of tool_name or file_path must be provided");let c=await o.getHistorySnapshot(),d=[];for(let{entryId:l,entry:u,kind:f,update:m}of bs(c)){if(f!=="tool_call")continue;let g;if(typeof m.name=="string"&&m.name.length>0?g=m.name:typeof m.title=="string"&&m.title.length>0?g=m.title:g="(unnamed)",t!==void 0&&g.toLowerCase()!==t.toLowerCase())continue;let h=m.rawInput,y={};if(h&&typeof h=="object"&&!Array.isArray(h))for(let[A,k]of Object.entries(h))typeof k=="string"?y[A]=k.length>500?k.slice(0,497)+"\u2026":k:(typeof k=="number"||typeof k=="boolean")&&(y[A]=k);if(a&&h&&typeof h=="object"&&!Array.isArray(h)){let A=s.toLowerCase(),k=["file_path","path"],M=!1;for(let P of k){let N=h[P];if(typeof N=="string"&&N.toLowerCase()===A){M=!0;break}}if(!M)continue}let w="in_progress";typeof m.status=="string"&&(w=m.status);let I=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(d.push({entryId:l,tool:g,args:y,status:w,timestamp:I}),d.length>=r)break}let p=d.length>=r;return ne({calls:d,truncated:p})}),e}var xu=1e4;function li(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let d=Cu(a),p=new Su({sessionIdGenerator:()=>bu()});await d.connect(p);let l={server:d,transport:p};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await p.close()}catch{}try{await d.close()}catch{}}),p}async function r(i,a){let c=Ze(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let l=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,f=new Promise(g=>{u=setTimeout(()=>g(void 0),xu)}),m=await Promise.race([d.sessionReady.catch(()=>{}),f]);if(u!==void 0&&clearTimeout(u),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var cn=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Fu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Ou}from"crypto";import{Server as Mu}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Ru,ListToolsRequestSchema as Eu}from"@modelcontextprotocol/sdk/types.js";function pi(n,e,t){let s=typeof t=="function"?async()=>t():async()=>t,r=new Mu({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=new Map(e.tools.map(i=>[i.name,i]));return r.setRequestHandler(Eu,async()=>({tools:e.tools.map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema!==void 0?{outputSchema:i.outputSchema}:{}}))})),r.setRequestHandler(Ru,async(i,a)=>{let c=i.params.name;if(!o.has(c))return un(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,p=Tu(d,a.sendNotification);try{let l=await s(),u=await _u(e.connection,n,c,i.params.arguments??{},l);return $u(u,c)}catch(l){return un(l instanceof Error?l.message:String(l))}finally{p()}}),r}var Pu=15e3;function Tu(n,e,t=Pu){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function _u(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function $u(n,e){if(n===null||typeof n!="object")return un(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:un(`extension ${e} omitted content array`)}function un(n){return{content:[{type:"text",text:n}],isError:!0}}var Hu=1e4;function fi(n,e,t){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function o(d){for(let p of s.values()){let l=p.get(d);l!==void 0&&(p.delete(d),r(l))}}t.onChange(d=>{o(d)});async function i(d,p){let l=s.get(d);l===void 0&&(l=new Map,s.set(d,l),e.addDisposer(d,async()=>{let y=s.get(d);if(y!==void 0){s.delete(d);for(let w of y.values())await r(w)}}));let u=l.get(p);if(u!==void 0)return u.transport;let f=t.lookup(p);if(f===void 0)return;let g=pi(p,f,async()=>{let y=e.lookup(d);if(y===void 0)throw new Error("mcp token no longer bound");if(y.session!==void 0)return y.session.sessionId;let w,I=new Promise(k=>{w=setTimeout(()=>k(void 0),Hu)}),A=await Promise.race([y.sessionReady.catch(()=>{}),I]);if(w!==void 0&&clearTimeout(w),A===void 0)throw new Error("session not ready");return A.sessionId}),h=new Fu({sessionIdGenerator:()=>Ou()});return await g.connect(h),l.set(p,{server:g,transport:h}),h}async function a(d,p){let l=Ze(d);if(l===void 0){p.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){p.code(404).send({error:"unknown mcp token"});return}let f=d.params.name,m=await i(l,f);if(m===void 0){p.code(404).send({error:`unknown mcp server: ${f}`});return}p.hijack(),await m.handleRequest(d.raw,p.raw,d.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(d,p)=>{await a(d,p)}),n.get("/mcp/:name",c,async(d,p)=>{await a(d,p)}),n.delete("/mcp/:name",c,async(d,p)=>{await a(d,p)})}async function Uu(n,e){qu(n);let t=n.daemon.tls?await et.readFile(Y(n.daemon.tls.key)):void 0,s=n.daemon.tls?await et.readFile(Y(n.daemon.tls.cert)):void 0;await et.mkdir(v.home(),{recursive:!0});let{stream:r,fileStream:o}=await Du(n.daemon.logLevel),i=Nu({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(ju,{options:{handleProtocols:As}}),bn(_=>{i.log.info(_)}),kn(_=>{i.log.info(_)});let a=await Gt.load(),c=new tn,d=new en,p=new Zt([new Yt(e),new Xt(a),d]),l=Ao({validator:p});i.addHook("onRequest",async(_,ce)=>{_.routeOptions.config?.skipAuth||_.url==="/acp"||_.url?.startsWith("/acp?")||await l(_,ce)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let f=setInterval(()=>{c.sweepExpired()},300*1e3);f.unref();let m=new nt(n,{onFetched:()=>{mo(m,w)}});os(_=>i.log.info(_));let g={info:_=>i.log.info(_),warn:_=>i.log.warn(_)},h=_=>he.spawn({..._,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});js(n.compressToolContent);let y=new Vt,w=new yt(m,h,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:y,defaultCwd:n.defaultCwd}),I=new Wt(Ts(n),void 0,{tokenRegistry:d}),A=new Qt(_s(n),void 0,{tokenRegistry:d});Go(i,K,yo(n));let k=new dn,M=new cn,P,N=()=>{if(P!==void 0)return P;let _=i.server.address();return P=`http://127.0.0.1:${_&&typeof _=="object"?_.port:n.daemon.port}`,P};Vo(i,w,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:M,mcpTokenRegistry:k,getDaemonOrigin:N}),Ko(i,m,w,{npmRegistry:n.npmRegistry}),Yo(i,I),Xo(i,A),Zo(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),ri(i,{store:a,rateLimiter:c}),ui(i,k),li(i,k),fi(i,k,M),di(i,{validator:p,manager:w,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(_,ce)=>I.reportVersion(_,ce),onTransformerVersion:(_,ce)=>A.reportVersion(_,ce),transformers:A,extensionCommands:y,mcpTokenRegistry:k,extensionMcp:M,getDaemonOrigin:N,registry:m});let U=!!n.daemon.tls;await i.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let H=i.server.address(),$=H&&typeof H=="object"?H.port:n.daemon.port,R,q=n.daemon.host,z=$;if(U&&t&&s){R=Lu({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:$,tlsOptions:{key:t,cert:s},logger:i.log});let _=R.address();_&&typeof _=="object"&&(z=_.port)}await et.mkdir(v.home(),{recursive:!0}),await fo({pid:process.pid,host:q,port:z,loopbackPort:$,startedAt:new Date().toISOString()});let de={daemonUrl:`http://127.0.0.1:${$}`,daemonHost:"127.0.0.1",daemonPort:$,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${$}/acp`,hydraHome:v.home()};I.setContext(de),A.setContext(de),await I.start(),await A.start(),w.resurrectPendingQueues().catch(_=>{i.log.warn(`queue replay scan failed: ${_.message}`)}),w.resumePendingCompactions().catch(_=>{i.log.warn(`compaction resume scan failed: ${_.message}`)});let tt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ct=tt>0?go({registry:m,manager:w,intervalMs:tt,logger:g}):void 0,Is=n.daemon.sessionGcIntervalMinutes*60*1e3,wi=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ss=Is>0?ho({manager:w,intervalMs:Is,maxAgeMs:wi,logger:g}):void 0;return{app:i,manager:w,registry:m,extensions:I,transformers:A,mcpTokenRegistry:k,extensionMcp:M,processRegistry:d,shutdown:async()=>{Ss&&Ss(),Ct&&Ct(),clearInterval(u),clearInterval(f);let _=async(ce,vi)=>{try{await vi()}catch(ln){i.log.warn(`shutdown step ${ce} failed: ${ln instanceof Error?ln.message:String(ln)}`)}};await _("sessionTokenStore.flush",()=>a.flush()),await _("extensions.stop",()=>I.stop()),await _("transformers.stop",()=>A.stop()),await _("manager.closeAll",()=>w.closeAll()),await _("manager.flushSynopsis",()=>w.flushSynopsis(3e4)),await _("manager.shutdownSynopsis",()=>w.shutdownSynopsis()),await _("manager.flushMetaWrites",()=>w.flushMetaWrites()),await _("manager.flushHistoryWrites",()=>w.flushHistoryWrites()),bn(null),kn(null),os(null),R&&await _("tlsTerminator.close",()=>new Promise(ce=>R.close(()=>ce()))),await _("app.close",()=>i.close());try{gi.unlinkSync(v.pidFile())}catch{}await _("fileStream.flushSync",()=>o.flushSync())}}}async function Du(n){let e=await Bu({file:v.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=mi.destination(2);return{stream:mi.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Lu(n){let e=yi.createServer(n.tlsOptions,t=>{let s=hi.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",o),s.on("error",o),t.on("close",()=>o()),s.on("close",()=>o()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function qu(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{he as AgentInstance,Re as JsonRpcConnection,nt as Registry,Ee as Session,yt as SessionManager,Ui as defaultConfig,ki as ensureServiceToken,xt as generateServiceToken,Fs as loadConfig,Si as loadServiceToken,Mn as ndjsonStreamFromStdio,v as paths,se as planSpawn,Uu as startDaemon,Bi as writeConfig,ms as wsToMessageStream};
|