@hydra-acp/cli 0.1.74 → 0.1.75
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 +235 -230
- package/dist/index.d.ts +12 -0
- package/dist/index.js +48 -48
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
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: ${f}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<oo)return await new Promise(r=>setTimeout(r,ao*(e+1))),vs(n,e+1);throw t}}function uo(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 lo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Is(n,e){let t=oe.join(n,"node_modules",e,"package.json");try{let s=await K.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 ys(n){let e=oe.join(n.installDir,"node_modules",".bin"),t=oe.join(e,n.hint);if(await be(t))return{binName:n.hint,binPath:t};let s=await Is(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=oe.join(e,i);if(await be(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=oe.join(e,i);if(await be(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=oe.join(e,n.basename);if(await be(r))return{binName:n.basename,binPath:r}}}async function be(n){try{return await K.access(n),!0}catch{return!1}}var fo=x.object({package:x.string(),bin:x.string().optional(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),_e=x.object({archive:x.string().url().optional(),cmd:x.string().optional(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),po=x.object({"darwin-aarch64":_e.optional(),"darwin-x86_64":_e.optional(),"linux-aarch64":_e.optional(),"linux-x86_64":_e.optional(),"windows-x86_64":_e.optional(),"windows-aarch64":_e.optional()}),mo=x.object({package:x.string(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),go=x.object({command:x.string(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),ho=x.object({command:x.string().optional(),url:x.string().optional(),description:x.string().optional()}),yo=x.object({npx:fo.optional(),binary:po.optional(),uvx:mo.optional(),exec:go.optional()}),wo=x.object({id:x.string(),name:x.string(),version:x.string().optional(),description:x.string().optional(),authors:x.array(x.string()).optional(),license:x.string().optional(),icon:x.string().optional(),repository:x.string().optional(),website:x.string().optional(),distribution:yo,onboarding:ho.optional()}),bs=x.object({version:x.string(),agents:x.array(wo),extensions:x.array(x.unknown()).optional()}),ze=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=>ln(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:vo(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=bs.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 re(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=bs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await Z(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function vo(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 ln(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 $e(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 fn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function fn(n){let e=ie();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=on(n.distribution.binary,e);if(s?.cmd){let r=ht.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await Ss(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??ln(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=ht.join(i,"node_modules",".bin",r);if(await Ss(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Ss(n){try{return await As.access(n),!0}catch{return!1}}async function ae(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??ln(n)??r.package,a=t.onInstallProgress;return{command:await ws({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=on(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ie()??"this platform"}.`);let i=t.onInstallProgress,o=await hs({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 Ao}from"child_process";import*as vt from"fs";import*as Hs 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 F}from"zod";var ks=F.object({protocolVersion:F.number().optional(),clientCapabilities:F.record(F.unknown()).optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional()}),Io=F.enum(["full","pending_only","none","after_message"]),xs=F.object({cwd:F.string(),mcpServers:F.array(F.unknown()).optional(),_meta:F.record(F.unknown()).optional()}),Cs=F.object({upstreamSessionId:F.string(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),agentArgs:F.array(F.string()).optional()}),Ms=F.object({sessionId:F.string(),historyPolicy:Io.default("full"),afterMessageId:F.string().optional(),clientId:F.string().optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional(),_meta:F.record(F.unknown()).optional()});import{z as R}from"zod";var Rs=R.object({sessionId:R.string()}),Es=R.object({cwd:R.string().optional(),cursor:R.string().optional()}),pn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional()}),Ru=R.object({sessionId:R.string(),upstreamSessionId:R.string().optional(),cwd:R.string(),title:R.string().optional(),agentId:R.string().optional(),currentModel:R.string().optional(),currentUsage:pn.optional(),importedFromMachine:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),originatingClient:R.object({name:R.string(),version:R.string().optional()}).optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),updatedAt:R.string(),attachedClients:R.number().int().nonnegative(),status:R.enum(["live","cold"]).default("live"),busy:R.boolean().default(!1),awaitingInput:R.boolean().default(!1),_meta:R.record(R.unknown()).optional()}),bo=R.object({sessionId:R.string(),cwd:R.string(),title:R.string().optional(),updatedAt:R.string().optional(),_meta:R.record(R.unknown()).optional()}),Eu=R.object({sessions:R.array(bo),nextCursor:R.string().optional()});function yt(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 Ps(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:We(n._meta,yt(n))};return n.title!==void 0&&(e.title=n.title),e}var Qe="hydra-acp";function Ve(n){if(!n)return{};let e=n[Qe];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=Cs.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=pn.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}:{}}}return t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),s}function We(n,e){return{...n??{},[Qe]:e}}import{z as b}from"zod";var Ts=b.object({sessionId:b.string(),prompt:b.array(b.unknown()),_meta:b.record(b.unknown()).optional()}),wt=b.object({sessionId:b.string()}),_s=b.object({clientId:b.string(),name:b.string().optional(),version:b.string().optional()}),Fu=b.object({sessionId:b.string(),messageId:b.string(),originator:_s,prompt:b.array(b.unknown()),position:b.number().int().nonnegative(),queueDepth:b.number().int().positive(),enqueuedAt:b.number()}),Nu=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Hu=b.object({sessionId:b.string(),messageId:b.string(),reason:b.enum(["started","cancelled","abandoned"])}),$s=b.object({sessionId:b.string(),messageId:b.string()}),ju=b.object({cancelled:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Os=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Bu=b.object({updated:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Fs=b.object({sessionId:b.string(),targetMessageId:b.string(),prompt:b.array(b.unknown()),replaceQueue:b.boolean().optional(),onTargetCompleted:b.enum(["reject","send_anyway"]).optional()}),Uu=b.object({amended:b.boolean(),reason:b.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:b.string().optional()}),Du=b.object({sessionId:b.string(),cancelledMessageId:b.string(),newMessageId:b.string(),prompt:b.array(b.unknown()),originator:_s,amendedAt:b.number()});import{z as he}from"zod";var Ju=he.object({agentId:he.string(),version:he.string(),source:he.enum(["binary","npm"]),phase:he.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:he.number().optional(),totalBytes:he.number().optional(),packageSpec:he.string().optional()}),Ns="hydra-acp/agents/install_progress";function mn(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(`
|
|
1
|
+
import*as Ei from"fs";import*as Ie from"fs/promises";import Dc from"fastify";import Lc from"@fastify/websocket";var Vn="acp.v1";function Gn(n,e){return n.has(Vn)?Vn:!1}import Ri from"pino";import qc from"pino-roll";import*as Zn from"fs/promises";import{homedir as tn}from"os";import{z as v}from"zod";import*as T from"path";import*as Zt from"os";var Pi="HYDRA_ACP_HOME";function Me(n){let e=Zt.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function $(){let n=process.env[Pi];if(n&&n.length>0)return T.resolve(n);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return T.join(Zt.homedir(),".hydra-acp")}var w={home:$,config:()=>T.join($(),"config.json"),authToken:()=>T.join($(),"auth-token"),remotes:()=>T.join($(),"remotes.json"),pidFile:()=>T.join($(),"daemon.pid"),logFile:()=>T.join($(),"daemon.log"),currentLogFile:()=>T.join($(),"current.log"),registryCache:()=>T.join($(),"registry.json"),agentsDir:()=>T.join($(),"agents"),agentLogFile:n=>T.join($(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>T.join($(),"sessions"),sessionDir:n=>T.join($(),"sessions",n),sessionFile:n=>T.join($(),"sessions",n,"meta.json"),historyFile:n=>T.join($(),"sessions",n,"history.jsonl"),toolsDir:n=>T.join($(),"sessions",n,"tools"),toolBlobFile:(n,e)=>T.join($(),"sessions",n,"tools",e),queueFile:n=>T.join($(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>T.join($(),"sessions",".tombstones"),tombstoneAgentDir:n=>T.join($(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>T.join($(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>T.join($(),"extensions"),extensionLogFile:n=>T.join($(),"extensions",`${n}.log`),extensionPidFile:n=>T.join($(),"extensions",`${n}.pid`),transformersDir:()=>T.join($(),"transformers"),transformerLogFile:n=>T.join($(),"transformers",`${n}.log`),transformerPidFile:n=>T.join($(),"transformers",`${n}.pid`),transformerState:(n,e)=>T.join($(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>T.join($(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>T.join($(),"prompt-history"),tuiLogFile:()=>T.join($(),"tui.log"),shimWireLogFile:()=>T.join($(),"shim-wire.log")};import*as Re from"fs/promises";function ft(){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 Yn(){try{let e=(await Re.readFile(w.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ti(){let n=await Yn();if(!n)throw new Error(`No service token found at ${w.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function en(n){await Re.mkdir(w.home(),{recursive:!0}),await Re.writeFile(w.authToken(),n+`
|
|
2
|
+
`,{encoding:"utf8",mode:384})}async function _i(){let n=await Yn();if(n)return n;let e=ft();return await en(e),process.stderr.write(`hydra-acp: initialized ${w.authToken()} with a fresh service token.
|
|
3
|
+
`),e}import*as re from"fs/promises";import*as Kn from"fs";import{randomBytes as $i}from"crypto";async function Z(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
4
|
+
`;await Oi(n,r,t)}async function Oi(n,e,t={}){let s=Fi(n);await re.mkdir(s,{recursive:!0});let r=`${n}.tmp-${process.pid}-${Ni()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await re.writeFile(r,e,i),await re.rename(r,n)}catch(i){throw await re.unlink(r).catch(()=>{}),i}if(t.mode!==void 0)try{Kn.chmodSync(n,t.mode)}catch{}}async function ie(n){let e;try{e=await re.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 Fi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Ni(){return $i(4).toString("hex")}var es="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",ji=v.object({cert:v.string(),key:v.string()}),ts=55514,Hi=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(ts),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:ji.optional(),sessionIdleTimeoutSeconds:v.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:v.number().int().positive().default(1e4),agentStderrTailBytes:v.number().int().positive().default(4096),publicHost:v.string().optional(),agentSyncIntervalMinutes:v.number().nonnegative().default(60),sessionGcIntervalMinutes:v.number().nonnegative().default(60),sessionGcMaxAgeDays:v.number().positive().default(2)}),Bi=v.object({url:v.string().url().default(es),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),Ui=v.object({name:v.string().optional(),description:v.string().optional(),command:v.string().optional(),args:v.array(v.string()).optional(),env:v.record(v.string()).optional()}),Di=v.object({packageSpec:v.string().optional()}),Li=v.object({repaintThrottleMs:v.number().int().nonnegative().default(1e3),maxScrollbackLines:v.number().int().positive().default(1e4),mouse:v.boolean().default(!1),inAppSelection:v.boolean().optional(),selectionClipboard:v.enum(["primary","clipboard","both"]).default("both"),logMaxBytes:v.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:v.number().int().positive().default(32),progressIndicator:v.boolean().default(!0),defaultEnterAction:v.enum(["enqueue","amend"]).default("amend"),showThoughts:v.boolean().default(!0),ambiguousWidth:v.enum(["narrow","wide"]).default("wide"),toolContent:v.enum(["inline","references"]).default("references"),diffContextLines:v.number().int().min(0).default(3),promptHistoryMaxEntries:v.number().int().positive().default(2e3),maxToolItems:v.number().int().nonnegative().default(5),maxPlanItems:v.number().int().nonnegative().default(5),showFileUpdates:v.enum(["none","edit","diff"]).default("edit"),sessionColumns:v.array(v.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Xn=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),qi=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),Ji=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),ns=v.object({daemon:Hi.default({}),registry:Bi.default({url:es,ttlHours:24,pinned:!1}),agents:v.record(v.string(),Ui).default({}),agentOverrides:v.record(v.string(),Di).default({}),defaultAgent:v.string().default("opencode"),defaultModels:v.record(v.string(),v.string()).default({}),synopsisAgent:v.string().optional(),synopsisModel:v.string().optional(),synopsisOnClose:v.boolean().default(!1),defaultCwd:v.string().default("~"),compressToolContent:v.boolean().default(!0),sessionListColdLimit:v.number().int().nonnegative().default(20),extensions:v.record(Xn,qi).default({}),transformers:v.record(Xn,Ji).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Li.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!1,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"wide",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function ss(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function rs(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function is(){return await ie(w.config())??{}}async function zi(){let n=await is(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Zn.access(w.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${w.authToken()} and ${w.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await en(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await Z(w.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${w.config()} to ${w.authToken()}.
|
|
5
|
+
`)}async function os(){return await zi(),ns.parse(await is())}async function Wi(n){await Z(w.config(),n,{mode:384})}function Qi(){return ns.parse({})}function Ee(n){return n==="~"||n==="$HOME"?tn():n.startsWith("~/")?tn()+n.slice(1):n.startsWith("$HOME/")?tn()+n.slice(5):n}import*as z from"fs/promises";import{createHash as Vi}from"crypto";import{gzip as Gi,gunzip as Yi}from"zlib";import{promisify as as}from"util";var ds=as(Gi),Ki=as(Yi),cs=/^[A-Za-z0-9_-]+$/,Xi=/^[a-f0-9]{64}$/,nn=!0;function us(n){nn=n}function pt(n,e){return cs.test(n)?e===void 0||Xi.test(e):!1}function gt(n,e){return`${w.toolBlobFile(n,e)}.gz`}async function sn(n,e){if(!pt(n))return null;let t=Vi("sha256").update(e,"utf8").digest("hex"),s=gt(n,t),r=w.toolBlobFile(n,t);for(let a of[s,r])try{return await z.access(a),t}catch{}await z.mkdir(w.toolsDir(n),{recursive:!0});let i=nn?s:r,o=nn?await ds(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await z.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function mt(n,e){if(!pt(n,e))return null;try{let t=await z.readFile(gt(n,e));return(await Ki(t)).toString("utf8")}catch{}try{return await z.readFile(w.toolBlobFile(n,e),"utf8")}catch{return null}}async function ls(n,e){if(!pt(n,e))return null;try{return await z.readFile(gt(n,e))}catch{}try{let t=await z.readFile(w.toolBlobFile(n,e));return await ds(t)}catch{return null}}async function fs(n,e,t){if(!pt(n,e))return;let s=gt(n,e);try{await z.access(s);return}catch{}await z.mkdir(w.toolsDir(n),{recursive:!0}),await z.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function ps(n){cs.test(n)&&await z.rm(w.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as ks from"fs/promises";import*as ht from"path";import{z as C}from"zod";import*as ms from"fs";import*as Q from"fs/promises";import*as he from"path";import{spawn as hs}from"child_process";import{Readable as Zi}from"stream";function oe(){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 an(n,e=oe()){if(e)return n[e]}var Pe=n=>{process.stderr.write(n+`
|
|
6
|
+
`)};function dn(n){Pe=n??(e=>process.stderr.write(e+`
|
|
7
|
+
`))}async function ys(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${oe()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=oe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentInstallDir(n.agentId,e,n.version),s=he.resolve(t,n.target.cmd);if(await on(s))return s;if(await eo({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await on(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Q.chmod(s,493).catch(()=>{}),s}async function eo(n){await Q.mkdir(he.dirname(n.installDir),{recursive:!0});let e=await Q.mkdtemp(`${n.installDir}.partial-`);try{Pe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await to({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Pe(`hydra-acp: extracting ${n.agentId}`),Te(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await so(t,e),await Q.unlink(t).catch(()=>{});try{await Q.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await on(n.installDir)){await Q.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Te(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Pe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Te(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Q.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Te(n,e){if(n)try{n(e)}catch{}}async function to(n){let e=no(n.url),t=he.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=ms.createWriteStream(t),o=Zi.fromWeb(s.body);Te(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),c=0,f=2e3,u=150;return o.on("data",l=>{a+=l.length;let p=Date.now();p-c>=u&&(c=p,Te(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=f&&(d=p,Pe(gs(n.agentId,a,r)))}),await new Promise((l,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>l()),o.pipe(i)}),Pe(gs(n.agentId,a,r,!0)),Te(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function gs(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function no(n){let e=new URL(n);return he.posix.basename(e.pathname)||"archive"}async function so(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await rn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ro("unzip")){await rn("unzip",["-q",n,"-d",e]);return}await rn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function rn(n,e){return new Promise((t,s)=>{let r=hs(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function ro(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=hs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function on(n){try{return await Q.access(n),!0}catch{return!1}}import*as K from"fs/promises";import*as ae from"path";import{spawn as io}from"child_process";var un=n=>{process.stderr.write(n+`
|
|
8
|
+
`)};function ln(n){un=n??(e=>process.stderr.write(e+`
|
|
9
|
+
`))}async function vs(n){let e=oe();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentNpmInstallDir(n.agentId,e,n.version),s=lo(n.packageSpec),r=fo(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=ae.join(t,"node_modules",".bin",n.bin);if(await be(o))return o;if(await be(t)){let u=await ws(i);if(u)return u.binPath}await oo({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await ws(i);if(a)return a.binPath;let d=await bs(t,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],f=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${f}`)}async function oo(n){await K.mkdir(ae.dirname(n.installDir),{recursive:!0});let e=await K.mkdtemp(`${n.installDir}.partial-`);try{un(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),cn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await uo({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await K.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await be(n.installDir)){await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),cn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}un(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),cn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function cn(n,e){if(n)try{n(e)}catch{}}var ao=5,co=25;function uo(n){return Is(n,0)}async function Is(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=io("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,d)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,f=o.trim();s(new Error(f?`npm install ${n.packageSpec} failed (${c})
|
|
10
|
+
stderr: ${f}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<ao)return await new Promise(r=>setTimeout(r,co*(e+1))),Is(n,e+1);throw t}}function lo(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 fo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function bs(n,e){let t=ae.join(n,"node_modules",e,"package.json");try{let s=await K.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=ae.join(n.installDir,"node_modules",".bin"),t=ae.join(e,n.hint);if(await be(t))return{binName:n.hint,binPath:t};let s=await bs(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=ae.join(e,i);if(await be(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=ae.join(e,i);if(await be(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=ae.join(e,n.basename);if(await be(r))return{binName:n.basename,binPath:r}}}async function be(n){try{return await K.access(n),!0}catch{return!1}}var po=C.object({package:C.string(),bin:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),_e=C.object({archive:C.string().url().optional(),cmd:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),go=C.object({"darwin-aarch64":_e.optional(),"darwin-x86_64":_e.optional(),"linux-aarch64":_e.optional(),"linux-x86_64":_e.optional(),"windows-x86_64":_e.optional(),"windows-aarch64":_e.optional()}),mo=C.object({package:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),ho=C.object({command:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),yo=C.object({command:C.string().optional(),url:C.string().optional(),description:C.string().optional()}),wo=C.object({npx:po.optional(),binary:go.optional(),uvx:mo.optional(),exec:ho.optional()}),vo=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:wo,onboarding:yo.optional()}),Ss=C.object({version:C.string(),agents:C.array(vo),extensions:C.array(C.unknown()).optional()}),ze=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=>fn(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:Io(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=Ss.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 ie(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Ss.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await Z(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Io(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 fn(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 $e(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 pn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function pn(n){let e=oe();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=an(n.distribution.binary,e);if(s?.cmd){let r=ht.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await As(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??fn(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=ht.join(i,"node_modules",".bin",r);if(await As(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function As(n){try{return await ks.access(n),!0}catch{return!1}}async function ee(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??fn(n)??r.package,a=t.onInstallProgress;return{command:await vs({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=an(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${oe()??"this platform"}.`);let i=t.onInstallProgress,o=await ys({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 xo}from"child_process";import*as vt from"fs";import*as Hs 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 F}from"zod";var xs=F.object({protocolVersion:F.number().optional(),clientCapabilities:F.record(F.unknown()).optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional()}),bo=F.enum(["full","pending_only","none","after_message"]),Cs=F.object({cwd:F.string(),mcpServers:F.array(F.unknown()).optional(),_meta:F.record(F.unknown()).optional()}),Ms=F.object({upstreamSessionId:F.string(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),agentArgs:F.array(F.string()).optional()}),Rs=F.object({sessionId:F.string(),historyPolicy:bo.default("full"),afterMessageId:F.string().optional(),clientId:F.string().optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional(),_meta:F.record(F.unknown()).optional()});import{z as M}from"zod";var Es=M.object({sessionId:M.string()}),Ps=M.object({cwd:M.string().optional(),cursor:M.string().optional()}),gn=M.object({used:M.number().optional(),size:M.number().optional(),costAmount:M.number().optional(),costCurrency:M.string().optional()}),Pu=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:gn.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()}),So=M.object({sessionId:M.string(),cwd:M.string(),title:M.string().optional(),updatedAt:M.string().optional(),_meta:M.record(M.unknown()).optional()}),Tu=M.object({sessions:M.array(So),nextCursor:M.string().optional()});function yt(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 Ts(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:We(n._meta,yt(n))};return n.title!==void 0&&(e.title=n.title),e}var Qe="hydra-acp";function Ao(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 Ve(n){if(!n)return{};let e=n[Qe];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=Ms.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=gn.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=Ao(t.env);r!==void 0&&(s.env=r)}return s}function We(n,e){return{...n??{},[Qe]:e}}import{z as b}from"zod";var _s=b.object({sessionId:b.string(),prompt:b.array(b.unknown()),_meta:b.record(b.unknown()).optional()}),wt=b.object({sessionId:b.string()}),$s=b.object({clientId:b.string(),name:b.string().optional(),version:b.string().optional()}),ju=b.object({sessionId:b.string(),messageId:b.string(),originator:$s,prompt:b.array(b.unknown()),position:b.number().int().nonnegative(),queueDepth:b.number().int().positive(),enqueuedAt:b.number()}),Hu=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Bu=b.object({sessionId:b.string(),messageId:b.string(),reason:b.enum(["started","cancelled","abandoned"])}),Os=b.object({sessionId:b.string(),messageId:b.string()}),Uu=b.object({cancelled:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Fs=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Du=b.object({updated:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Ns=b.object({sessionId:b.string(),targetMessageId:b.string(),prompt:b.array(b.unknown()),replaceQueue:b.boolean().optional(),onTargetCompleted:b.enum(["reject","send_anyway"]).optional()}),Lu=b.object({amended:b.boolean(),reason:b.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:b.string().optional()}),qu=b.object({sessionId:b.string(),cancelledMessageId:b.string(),newMessageId:b.string(),prompt:b.array(b.unknown()),originator:$s,amendedAt:b.number()});import{z as ye}from"zod";var Wu=ye.object({agentId:ye.string(),version:ye.string(),source:ye.enum(["binary","npm"]),phase:ye.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ye.number().optional(),totalBytes:ye.number().optional(),packageSpec:ye.string().optional()}),js="hydra-acp/agents/install_progress";function mn(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
11
|
`);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let f=JSON.parse(c);for(let u of s)u(f)}catch(f){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse ndjson line: ${f.message}`}})}d=t.indexOf(`
|
|
12
12
|
`)}}),n.on("end",()=>o()),n.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let d=JSON.stringify(a)+`
|
|
13
|
-
`;await new Promise((c,f)=>{e.write(d,u=>{if(u){f(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as
|
|
13
|
+
`;await new Promise((c,f)=>{e.write(d,u=>{if(u){f(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as ko}from"nanoid";var hn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Se=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 hn;let s=ko(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:I.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??I.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 Co=4096,fe=class n{agentId;version;cwd;connection;authMethods;child;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??Co,this.killEscalationMs=e.killEscalationMs??Mo,this.logger=e.logger,this.fileLog=Ro(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
|
|
14
14
|
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=mn(t.stdout,t.stdin);this.connection=new Se(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
|
|
15
15
|
`),this.connection.fail(new Error(i))}),t.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
16
16
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
17
|
-
stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=
|
|
17
|
+
stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=xo(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)})}},
|
|
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)})}},Mo=2e3;function Ro(n){try{let e=w.agentLogFile(n);vt.mkdirSync(Hs.dirname(e),{recursive:!0});let t=vt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as xe from"fs/promises";import*as Pt from"os";import*as st from"path";import{customAlphabet as Ua}from"nanoid";import{customAlphabet as Qs}from"nanoid";import*as Us from"fs/promises";var Eo=64*1024*1024,Po=1*1024*1024,Oe=64*1024,To=6e4,_o=100,$o=1e3,Oo=64*1024,Fo=256*1024,Bs=20;function No(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var It=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??Eo,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Po,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,Oe));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),f={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(f.gap=i),this.closed&&r+d>=this.writeCursor&&(f.eof=!0),f}tail(e){let t=Math.max(0,Math.min(e,Oe)),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,Oe)),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,To));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(No(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??_o,$o)),l=Math.max(1,Math.min(e.maxBytes??Oo,Fo)),p=Math.max(0,Math.min(e.contextBefore??0,Bs)),g=Math.max(0,Math.min(e.contextAfter??0,Bs)),m=[],h=[],y=[],k=0,S=!1,A=0,N=0,H=(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--,k+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==f&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let me of D.before)k+=me.line.length}k+=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=k>=l;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(A,R).toString("utf8"),j=r+A;if(A=R+1,N=A,H(j,P)){S=!0;break}}if(!S&&A<o.length&&this.closed){let R=o.subarray(A).toString("utf8"),P=r+A;H(P,R)&&(S=!0),N=o.length}let Y=Math.min(r+N,this.writeCursor),J={matches:m,truncated:S,nextCursor:Y,scannedBytes:N};return i>0&&(J.gap=i),this.closed&&Y>=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(()=>Us.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var bt=[{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."}],fl=new Map(bt.map(n=>[n.verb,n]));function Ds(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Fe(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.some(r=>r.modelId===n))return{kind:"exact",modelId:n};let t=Ds(n),s=e.map(r=>r.modelId).filter(r=>Ds(r)===t);return s.length===1?{kind:"resolved",modelId:s[0],requested:n}:s.length>1?{kind:"ambiguous",requested:n,candidates:s}:{kind:"unknown",requested:n}}function Ls(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=yn(d);if(c?.sessionUpdate!=="tool_call_update")continue;let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&(e.set(f,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(f,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(f);u?u.push(...c.content):t.set(f,[...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=yn(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let f=c.sessionUpdate;if(f==="agent_message_chunk"||f==="agent_thought_chunk"||f==="user_message_chunk"){i&&i.kind===f?Ho(r,i.outIndex,jo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:f});continue}if(i=null,f==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let l=u!==void 0&&t.has(u)?Bo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Uo(l)&&(l=Do(l,s.get(u))),r.push(l);continue}if(f==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(f==="prompt_received"||f==="turn_complete")&&(o=null),r.push(d)}return r}function yn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function jo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Ho(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 Bo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Uo(n){let t=yn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Do(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as de from"fs/promises";async function Ge(n,e){let t=w.queueFile(n);if(e.length===0){await de.unlink(t).catch(()=>{});return}await de.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
20
20
|
`)+`
|
|
21
|
-
`;await de.writeFile(t,s,"utf8")}async function
|
|
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 qs(n){let e=w.queueFile(n);await de.unlink(e).catch(()=>{})}import*as Ys from"fs/promises";var Qs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Vs=Ws(Qs,16),Js=Ws(Qs,16),pe="hydra_session_";function Ne(){return`m_${Vs()}`}function Gs(n){return n.startsWith(pe)?n.slice(pe.length):n}var Uo=1e3,yn=300*1e3,Do=64,Ae=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;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??`${pe}${Vs()}`,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.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??Uo,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){Vo(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 f=`t_${Js()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:f,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 l=u?.action??"continue";if(l==="stop")return;if(l==="processing"){let p=d,m=i,g=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:c.name}),this.runResponseChain(m,new Set([...g,c.name]),p+1).then(()=>h()).catch(()=>h()))},yn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:g,side:"response"})});return}t.add(c.name)}let o=Go(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Qo(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:Ds(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?vn(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=Ne();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ve((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=He(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:Ne()};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>Do;){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(f=>f.messageId===r&&f.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=Ne(),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=Ne(),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 f=`t_${Js()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:f,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 l=u?.action??"continue";if(l==="stop")return i==="notification"?void 0:u?.payload??wn(e);if(l==="processing"){let p=a,m=o,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:d.name}),this.forwardRequest(e,m,new Set([...g,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:wn(e))))},yn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:m,chainIdx:p,originatedBy:g,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):yn,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:wn(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=He((e??{}).prompt),r=In(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=je(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=je(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=Ye(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=je(o.options);if(d.length>0){let c=Ye(o.options),f=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,l=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:m,options:f})}}}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(Jo(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(",")}]`),Wo(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}`,f={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(f.description=s.description),e.push(f)}}}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(bt.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=bt.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:l}of this.extensionCommands.list())u.has(l)||(c.push(l),u.add(l))}let f=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw f.code=I.InvalidParams,f}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(m=>m.verb===o)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},f=new Promise(m=>{c=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>c({stopReason:"cancelled",reason:m})});let u,l=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",d),g=await Promise.race([m,f]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return l=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=g}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!l&&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:`
|
|
21
|
+
`;await de.writeFile(t,s,"utf8")}async function qs(n){let e=w.queueFile(n),t;try{t=await de.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
|
|
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 Js(n){let e=w.queueFile(n);await de.unlink(e).catch(()=>{})}import*as Ks from"fs/promises";var Vs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Gs=Qs(Vs,16),zs=Qs(Vs,16),pe="hydra_session_";function Ne(){return`m_${Gs()}`}function Ys(n){return n.startsWith(pe)?n.slice(pe.length):n}var Lo=1e3,wn=300*1e3,qo=64,Ae=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??`${pe}${Gs()}`,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??Lo,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){Yo(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 f=`t_${zs()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:f,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 l=u?.action??"continue";if(l==="stop")return;if(l==="processing"){let p=d,g=i,m=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:c.name}),this.runResponseChain(g,new Set([...m,c.name]),p+1).then(()=>h()).catch(()=>h()))},wn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{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=Ko(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Go(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:Ls(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?In(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=Ne();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ve((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=je(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}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:Ne()};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>qo;){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(f=>f.messageId===r&&f.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=Ne(),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=Ne(),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 f=`t_${zs()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:f,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 l=u?.action??"continue";if(l==="stop")return i==="notification"?void 0:u?.payload??vn(e);if(l==="processing"){let p=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:vn(e))))},wn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{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):wn,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:vn(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=je((e??{}).prompt),r=bn(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=He(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=He(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=Ye(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=He(o.options);if(d.length>0){let c=Ye(o.options),f=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,l=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:g,options:f})}}}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(Wo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Qo(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(",")}]`),Vo(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}`,f={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(f.description=s.description),e.push(f)}}}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(bt.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=bt.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:l}of this.extensionCommands.list())u.has(l)||(c.push(l),u.add(l))}let f=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw f.code=I.InvalidParams,f}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=()=>{},f=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,l=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,f]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return l=!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&&!l&&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:`
|
|
23
23
|
${e}
|
|
24
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 i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",d=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${d}`});e=`Sessions (${t.length}):
|
|
25
25
|
${s.join(`
|
|
@@ -42,7 +42,7 @@ Available models:
|
|
|
42
42
|
${o}
|
|
43
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(i=>i.id).join(", ");throw X(new Error(`unknown mode: ${t} (known: ${r})`),I.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 a=this.buildConfigOptions();if(a.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
44
44
|
_(no config options advertised yet)_
|
|
45
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>
|
|
45
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>Ws(c));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
46
46
|
${d.join(`
|
|
47
47
|
|
|
48
48
|
`)}
|
|
@@ -52,17 +52,17 @@ ${d.join(`
|
|
|
52
52
|
Available options:
|
|
53
53
|
${a}
|
|
54
54
|
`},_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
|
-
${
|
|
55
|
+
${Ws(o)}
|
|
56
56
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};if(!o.options.some(a=>a.value===r)){let a=o.options.map(d=>d.value).join(`
|
|
57
57
|
`);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
58
58
|
"${r}" is not a valid value for "${s}".
|
|
59
59
|
Valid values:
|
|
60
60
|
${a}
|
|
61
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:r}),{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 X(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw X(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw X(new Error("agent switching not configured for this session"),I.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(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 X(new Error("agent restart not configured for this session"),I.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw X(new Error("session is closing"),I.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.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let
|
|
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 It(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??Oe,Oe)),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(()=>qs(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(()=>Ys.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=!qo(e,r),o=i?Yo(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=Ko(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:l};this.inFlightPermissions.add(c);let f=this.sessionId,u=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function l(p){if(a)return;let m=p.connection.request("session/request_permission",s);d.push({client:p}),m.then(g=>{u(()=>{let h=Xo({toolCallId:r,result:g,resolver:p});for(let y of d)y.client.clientId!==p.clientId&&y.client.connection.notify("session/update",{sessionId:f,update:h}).catch(()=>{});i(g)})}).catch(g=>{u(()=>o(g))})}for(let p of t)l(p)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ne(),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},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),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(()=>Ge(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=He(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
|
|
61
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:r}),{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 X(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw X(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw X(new Error("agent switching not configured for this session"),I.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(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 X(new Error("agent restart not configured for this session"),I.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw X(new Error("session is closing"),I.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let g=je(u.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let g=u.status,m=u.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${g}`})}}if(s.length===0)return"";let i=[],o;for(let c of s)o&&o.speaker===c.speaker?o.text+=c.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:c.speaker,text:c.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
|
|
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 It(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??Oe,Oe)),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(()=>Js(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(()=>Ks.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=!zo(e,r),o=i?Xo(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=Zo(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:l};this.inFlightPermissions.add(c);let f=this.sessionId,u=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function l(p){if(a)return;let g=p.connection.request("session/request_permission",s);d.push({client:p}),g.then(m=>{u(()=>{let h=ea({toolCallId:r,result:m,resolver:p});for(let y of d)y.client.clientId!==p.clientId&&y.client.connection.notify("session/update",{sessionId:f,update:h}).catch(()=>{});i(m)})}).catch(m=>{u(()=>o(m))})}for(let p of t)l(p)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ne(),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},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),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(()=>Ge(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=je(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 Jo=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function zo(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Jo.has(s)}function Wo(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 Qo(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 Vo(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 He(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 Ye(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 Go(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 Yo(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 Ko(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 Xo(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:Ne()}}}function In(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 Zo(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 ea(n){let e=ta(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=na(n.resolver),t}function ta(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 na(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function je(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function vn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Ws(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}
|
|
64
64
|
${s.join(`
|
|
65
|
-
`)}`}function
|
|
65
|
+
`)}`}function bn(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 Be from"fs/promises";import*as Rl from"path";import{customAlphabet as ia}from"nanoid";import{z as x}from"zod";import{z as te}from"zod";var Ke=te.object({goal:te.string().optional(),outcome:te.string().optional(),files_touched:te.array(te.string()).optional(),tools_used:te.array(te.string()).optional(),rejected_approaches:te.array(te.string()).optional(),open_threads:te.array(te.string()).optional()}),sa=200,Sn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
66
66
|
{
|
|
67
67
|
"title": "short summary, max 80 chars",
|
|
68
68
|
"synopsis": {
|
|
@@ -72,41 +72,41 @@ ${s.join(`
|
|
|
72
72
|
"open_threads": ["work started but not finished"]
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
-
Use empty arrays/strings where a field doesn't apply.`;function
|
|
76
|
-
`,
|
|
77
|
-
`),t)}function
|
|
78
|
-
`);for(;t.length>0;){let s=
|
|
79
|
-
`);if(s.length<=e)return s;t.shift()}return
|
|
75
|
+
Use empty arrays/strings where a field doesn't apply.`;function Zs(n){let e=n.trim();if(e.length===0)return;let t=Xs(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(t=Xs(e.slice(i,o+1)),t===void 0))return}if(t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,sa))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Ke.safeParse(s.synopsis);i.success&&ra(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Xs(n){try{return JSON.parse(n)}catch{return}}function ra(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}var oa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",aa=ia(oa,16),da="hydra_lineage_";function Xe(){return`${da}${aa()}`}var kn=x.object({name:x.string(),description:x.string().optional()}),xn=x.object({id:x.string(),name:x.string().optional(),description:x.string().optional()}),ca=x.object({modelId:x.string(),name:x.string().optional(),description:x.string().optional()}),Cn=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional(),cumulativeCost:x.number().optional()}),Mn=x.object({name:x.string(),version:x.string().optional()}),ua=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:Ke.optional(),summarizedThroughEntry:x.number().int().nonnegative().optional(),agentArgs:x.array(x.string()).optional(),currentModel:x.string().optional(),currentMode:x.string().optional(),currentUsage:Cn.optional(),agentCommands:x.array(kn).optional(),agentModes:x.array(xn).optional(),agentModels:x.array(ca).optional(),pendingHistorySync:x.boolean().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:Mn.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()}),An=/^[A-Za-z0-9_-]+$/;function la(n){if(!An.test(n))throw new Error(`unsafe session id: ${n}`)}var St=class{async write(e){la(e.sessionId);let t={version:1,...e};await Z(w.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!An.test(e))return;let t=await ie(w.sessionFile(e));if(t!==void 0)try{return ua.parse(t)}catch{return}}async delete(e){if(An.test(e)){try{await Be.unlink(w.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Be.rmdir(w.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 Be.readdir(w.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 Rn(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,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 ge from"fs/promises";import{z as ce}from"zod";var fa=ce.object({version:ce.literal(1),agentId:ce.string(),upstreamSessionId:ce.string(),deletedAt:ce.string(),upstreamUpdatedAt:ce.string().optional(),cwd:ce.string().optional(),title:ce.string().optional(),reason:ce.enum(["user","expired"]).optional(),interactive:ce.boolean().optional()}),At=class{async add(e){let t={version:1,...e};await Z(w.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await ge.access(w.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=w.tombstoneFile(e,t),r=await ie(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 fa.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await ge.unlink(w.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await ge.rmdir(w.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 ge.readdir(w.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await ge.readdir(w.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function er(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as ur from"fs/promises";import{fileURLToPath as pa}from"url";import*as Ze from"path";import*as kt from"fs";function ga(){try{let n=Ze.dirname(pa(import.meta.url));for(let e=0;e<8;e+=1){let t=Ze.join(n,"package.json");if(kt.existsSync(t)){let r=JSON.parse(kt.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=Ze.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var V=ga(),xt="hydra-acp-cat";var tr=`[older history truncated]
|
|
76
|
+
`,ma=["file_path","path","command","pattern","query"];function nr(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received"){i();let f=va(d.prompt).trim();f.length>0&&s.push(`User: ${f}`)}else if(c==="agent_message_chunk"){let f=Ia(d.content);f.length>0&&(r+=f)}else c==="tool_call"?(i(),s.push(ha(d))):c==="turn_complete"&&i()}return i(),Sa(s.join(`
|
|
77
|
+
`),t)}function ha(n){let e=ya(n),t=wa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function ya(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function wa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of ma){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${ba(r,200)}`)}return t}function va(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 Ia(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function ba(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Sa(n,e){if(n.length<=e)return n;let t=n.split(`
|
|
78
|
+
`);for(;t.length>0;){let s=tr+t.join(`
|
|
79
|
+
`);if(s.length<=e)return s;t.shift()}return tr}var Aa=12e4;async function rr(n){let e=n.timeoutMs??Aa,t,s,r=!1;try{let i=(async()=>{t=fe.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let o=await t.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:V}}),a=await t.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`);return}if(n.modelId){let g=xa(a);if(g.size===0||g.has(n.modelId))try{await t.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];t.connection.onNotification("session/update",g=>{let m=ka(g);m.length>0&&c.push(m)});let f=nr(n.history,{maxChars:n.maxTranscriptChars}),u=f.length>0?`${f}
|
|
80
80
|
|
|
81
|
-
${
|
|
82
|
-
`;await
|
|
81
|
+
${Sn}`:Sn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let l=c.join(""),p=Zs(l);return p||n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse as snapshot JSON (replyLen=${l.length} preview=${JSON.stringify(l.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 ka(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 xa(n){let e=new Set;sr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&sr(e,t.availableModels),e}function sr(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 Ca(n){let e=new Map;for(let t of cr(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 ar(n){return Ca(n).map(e=>e.name)}function Ma(n){let e=new Map;for(let t of cr(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 dr(n){return Ma(n).map(e=>e.path)}function cr(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:ir(i),paths:new Set},e.set(d,c)):c.toolName=ir(i);for(let f of or(i.rawInput,i.locations))c.paths.add(f);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 or(i.rawInput,i.locations))a.paths.add(d)}return e}function ir(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function or(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 Ra=2,Ct=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ra}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 ee(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await ur.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 f=await rr({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!f){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}f.title&&await this.opts.persistTitle(e,f.title);let u=Ea(f.synopsis,s);u&&Pa(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${Ta(u)}`)):f.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(t){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${t.message}`)}}};function Ea(n,e){let t=dr(e),s=ar(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 Pa(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 Ta(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 G from"fs/promises";function lr(n){return n==="summary"?"summary":"inline"}var En=256;function fr(n,e){return e!=="summary"?n:n.map(_a)}function _a(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(pr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=Pn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function $a(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function pr(n){if($a(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=Pn(e.text)),typeof e.content=="string"?t.content=Pn(e.content):e.content&&typeof e.content=="object"&&(t.content=pr(e.content)),t}function Pn(n){if(typeof n=="string"&&n.length>En){let e=n.length-En;return`${n.slice(0,En)}\u2026[+${e} chars omitted from summary export]`}return n}var Oa=2048;function gr(n){let e=new Set,t=s=>{if(mr(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 mr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Fa(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 $n(n,e){if(!Fa(n))return n;let t=n.params,s=t.update,r=await Tn(s,e);return{...n,params:{...t,update:r}}}async function Tn(n,e){if(typeof n=="string"){if(n.length<=Oa)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 Tn(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Tn(r,e);return t}return n}async function hr(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await _n(t,e);return s===t?n:{...n,params:s}}async function _n(n,e){if(mr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await _n(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 _n(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var et=/^[A-Za-z0-9_-]+$/,Na=1e3,Mt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Na}async append(e,t){if(et.test(e))return this.enqueue(e,async()=>{await G.mkdir(w.sessionDir(e),{recursive:!0});let s=await $n(t,i=>sn(e,i)),r=JSON.stringify(s)+`
|
|
82
|
+
`;await G.appendFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(et.test(e))return this.enqueue(e,async()=>{await G.mkdir(w.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await $n(i,o=>sn(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
|
|
83
83
|
`)+`
|
|
84
|
-
`;await
|
|
85
|
-
`).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await
|
|
84
|
+
`;await G.writeFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(et.test(e))return this.enqueue(e,async()=>{let s;try{s=await G.readFile(w.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
|
|
85
|
+
`).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await G.writeFile(w.historyFile(e),i.join(`
|
|
86
86
|
`)+`
|
|
87
|
-
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!et.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await
|
|
88
|
-
`)){if(u.length===0)continue;let l;try{l=JSON.parse(u)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let p=l;typeof p.method=="string"&&typeof p.recordedAt=="number"&&o.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=o.length>this.maxEntries?o.slice(-this.maxEntries):o;if(!s)return a;let d=new Map,c=async u=>{let l=d.get(u);if(l!==void 0)return l;let p=await
|
|
87
|
+
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!et.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await G.readFile(w.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
|
|
88
|
+
`)){if(u.length===0)continue;let l;try{l=JSON.parse(u)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let p=l;typeof p.method=="string"&&typeof p.recordedAt=="number"&&o.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=o.length>this.maxEntries?o.slice(-this.maxEntries):o;if(!s)return a;let d=new Map,c=async u=>{let l=d.get(u);if(l!==void 0)return l;let p=await mt(e,u);return d.set(u,p),p},f=[];for(let u of a)f.push(await hr(u,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(et.test(e))return this.enqueue(e,async()=>{try{await G.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await ps(e);try{await G.rmdir(w.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),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};import{promises as yr}from"fs";import*as wr from"path";async function vr(n,e){await yr.mkdir(wr.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await yr.writeFile(n,t.length>0?t.join(`
|
|
89
89
|
`)+`
|
|
90
|
-
`:"")}import{z as O}from"zod";var
|
|
91
|
-
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=xr(a??{}),c=e.agentModes??Sr(kr(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(g=>g.id))}`);let f=await Cr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=br(a??{}),l=Sr(Ar(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Mr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let g=i.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 Ae({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:g=>this.bootstrapAgent({...g,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId)});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,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Cr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Mr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Ae({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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await xe.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:Ee(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 ae(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Pt.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}})}catch(p){throw await r.kill().catch(()=>{}),ke(p,r)}if(r.authMethods=Et(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 f=w.sessionsDir(),u=[],l=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(d.has(m)){l+=1;continue}if(Ua(p.cwd,f)){l+=1;continue}let g=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(g){if(!Zs(g,p.updatedAt)){l+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}d.add(m);let h=`${pe}${Rt()}`,y=new Date().toISOString(),S=p.updatedAt??y,M={sessionId:h,lineageId:Xe(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:S,updatedAt:S};p.title!==void 0&&(M.title=p.title);let k=Mn(M);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:l}}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 f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}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 ae(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}}),o=i.agentCapabilities;r.authMethods=Et(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=br(a),f=Ar(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let m=Fe(u,f),g=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,d,u,g)&&(c=u);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(r,d,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(c=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(c)}`);else{let h=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=kr(a),p=xr(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ke(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 ae(r,[],{npmRegistry:this.npmRegistry}),o=t??Ee(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:Q}});a.authMethods=Et(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),ke(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}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=Ue({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:Er(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=Da(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 gt(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:La(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}}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=He(r.update.prompt),o=In(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(pe))return;let t=pe+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 nt(t.sessionId),d=Ue({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 nt(s.sessionId),i=Ue(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=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>nt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Ue({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let m=l.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:m,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>nt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Ue(u,l.hasContent);if(!r(p))continue;let m=l.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:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((f,u)=>f.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=Xe(),f={...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=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Rr(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of pr(o)){let f=await us(e,c);f&&(d[c]=f.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=`${pe}${Rt()}`;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=I.SessionNotFound,m}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let g=new Error(`agent ${r} not found in registry`);throw g.code=I.AgentNotInstalled,g}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=vn(o,t.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw m.code=I.InvalidParams,m}d=t.forkAt}else{let m=za(o);m?(a=m.index,d=m.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await Rr(e),u={...s,lineageId:Xe(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},...i?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=tt({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:Q,machine:Pt.hostname()}),p=`${pe}${Rt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,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 ls(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await xe.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await wr(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 nt(e),r=Ue(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 Ls(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ir),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ir/1e3}s)`),await Ge(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 Ge(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 Ua(n,e){if(typeof n!="string"||n.length===0)return!1;let t=st.resolve(n),s=st.resolve(e);return t===s||t.startsWith(s+st.sep)}function Da(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return Mn({sessionId:n.sessionId,lineageId:e?.lineageId??Xe(),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:Er(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,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Er(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 La(n){return n?{...n}:void 0}function qa(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Tt(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=Ja(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function br(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>ue(e.currentModelId)??ue(e.currentModel)??ue(e.modelId)??ue(e.model),fromConfig:e=>ue(e.currentValue)})}function ke(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 Et(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;e.push({id:s.id,description:r,...i&&{type:i}})}return e.length>0?e:void 0}function ue(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Ja(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 Sr(n){return n.length>0?n:void 0}function Ar(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=je(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=je(e.options);return t.length>0?t:void 0}})??[]}function kr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Ye(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Ye(e.options);return t.length>0?t:void 0}})??[]}function xr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ue(e.currentModeId)??ue(e.currentMode)??ue(e.modeId)??ue(e.mode),fromConfig:e=>ue(e.currentValue)})}async function Cr(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 Mr(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 Rr(n){try{let e=await xe.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 nt(n){try{let e=await xe.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ue(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===xt?!1:e?!0:void 0}import{spawn as
|
|
90
|
+
`:"")}import{z as O}from"zod";var ja=O.object({method:O.string(),params:O.unknown(),recordedAt:O.number()}),Ha=O.object({sessionId:O.string(),lineageId:O.string(),upstreamSessionId:O.string().optional(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),synopsis:Ke.optional(),summarizedThroughEntry:O.number().int().nonnegative().optional(),currentModel:O.string().optional(),currentMode:O.string().optional(),currentUsage:Cn.optional(),agentCommands:O.array(kn).optional(),agentModes:O.array(xn).optional(),interactive:O.boolean().optional(),originatingClient:Mn.optional(),priority:O.number().int().nonnegative().optional(),createdAt:O.string(),updatedAt:O.string()}),Ba=O.object({version:O.literal(1),exportedAt:O.string(),exportedFrom:O.object({hydraVersion:O.string(),machine:O.string(),hydraHost:O.string().optional()}),session:Ha,history:O.array(ja),promptHistory:O.array(O.string()).optional(),toolBlobs:O.record(O.string()).optional()});function tt(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 Ir(n){return Ba.parse(n)}var br=900*1e3,Da="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Rt=Ua(Da,16),rt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>fe.spawn(i)),this.store=s??new St,this.tombstones=r.tombstones??new At,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Mt({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 Ct({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 $e(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_${Rt()}`,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 Ae({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 ee(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:V}});o=m.agentCapabilities,i.authMethods=Et(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),ke(m,i)}let a;try{let m=za(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(()=>{}),ke(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=Cr(a??{}),c=e.agentModes??Ar(xr(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 f=await Mr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=Sr(a??{}),l=Ar(kr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.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 Rr({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 Ae({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:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,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 Mr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Rr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Ae({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 xe.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:Ee(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 ee(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Pt.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:V}})}catch(p){throw await r.kill().catch(()=>{}),ke(p,r)}if(r.authMethods=Et(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 f=w.sessionsDir(),u=[],l=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){l+=1;continue}if(La(p.cwd,f)){l+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!er(m,p.updatedAt)){l+=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=`${pe}${Rt()}`,y=new Date().toISOString(),k=p.updatedAt??y,S={sessionId:h,lineageId:Xe(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:k,updatedAt:k};p.title!==void 0&&(S.title=p.title);let A=Rn(S);await this.store.write(A),u.push({version:1,...A})}return{synced:u,skipped:l}}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 f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}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 ee(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:V}}),o=i.agentCapabilities;r.authMethods=Et(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=Sr(a),f=kr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=Fe(u,f),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=f.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 l=xr(a),p=Cr(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ke(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 ee(r,[],{npmRegistry:this.npmRegistry}),o=t??Ee(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:V}});a.authMethods=Et(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),ke(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 ee(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=Ue({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:Pr(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=qa(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 mt(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:Ja(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=je(r.update.prompt),o=bn(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(pe))return;let t=pe+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 nt(t.sessionId),d=Ue({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 nt(s.sessionId),i=Ue(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=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>nt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Ue({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let g=l.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(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>nt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Ue(u,l.hasContent);if(!r(p))continue;let g=l.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((f,u)=>f.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=Xe(),f={...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=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Er(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of gr(o)){let f=await ls(e,c);f&&(d[c]=f.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=`${pe}${Rt()}`;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=In(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=Qa(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await Er(e),u={...s,lineageId:Xe(),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}:{}},l=tt({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:V,machine:Pt.hostname()}),p=`${pe}${Rt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,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 fs(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await xe.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await vr(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 nt(e),r=Ue(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<br),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${br/1e3}s)`),await Ge(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 Ge(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 La(n,e){if(typeof n!="string"||n.length===0)return!1;let t=st.resolve(n),s=st.resolve(e);return t===s||t.startsWith(s+st.sep)}function qa(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return Rn({sessionId:n.sessionId,lineageId:e?.lineageId??Xe(),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:Pr(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 Pr(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 Ja(n){return n?{...n}:void 0}function za(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Tt(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=Wa(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Sr(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>ue(e.currentModelId)??ue(e.currentModel)??ue(e.modelId)??ue(e.model),fromConfig:e=>ue(e.currentValue)})}function ke(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 Et(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 ue(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Wa(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 Ar(n){return n.length>0?n:void 0}function kr(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=He(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=He(e.options);return t.length>0?t:void 0}})??[]}function xr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Ye(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Ye(e.options);return t.length>0?t:void 0}})??[]}function Cr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ue(e.currentModeId)??ue(e.currentMode)??ue(e.modeId)??ue(e.mode),fromConfig:e=>ue(e.currentValue)})}async function Mr(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 Rr(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 Qa(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 Er(n){try{let e=await xe.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 nt(n){try{let e=await xe.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ue(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===xt?!1:e?!0:void 0}import{spawn as Va}from"child_process";import*as Le from"fs";import*as ve from"fs/promises";import*as Tr from"path";var _t=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Ga=1e3,Ya=6e4,On=3e3,De=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??Ga,this.restartCapMs=r.restartCapMs??Ya;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await ve.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 i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},On);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw it(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw it(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 it(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 it(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 it(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},On);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 _t(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await ve.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=Tr.join(this.adapter.paths.dir(),t),r;try{let i=await ve.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Fn(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+On;for(;Date.now()<i&&Fn(r);)await new Promise(o=>setTimeout(o,50));if(Fn(r))try{process.kill(r,"SIGKILL")}catch{}}await ve.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,i=r.command.length>0?r.command:[r.name],o=Le.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
|
|
93
93
|
`);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let d={...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},[c,...f]=i;if(c===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
|
|
94
|
-
`),o.end();return}let u=[...f,...r.args],l;try{l=
|
|
94
|
+
`),o.end();return}let u=[...f,...r.args],l;try{l=Va(c,u,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
|
|
95
95
|
`),o.end(),this.scheduleRestart(e,t);return}if(l.stdout&&l.stdout.pipe(o,{end:!1}),l.stderr&&l.stderr.pipe(o,{end:!1}),typeof l.pid=="number")try{Le.writeFileSync(this.adapter.paths.pidFile(r.name),`${l.pid}
|
|
96
96
|
`,{encoding:"utf8",mode:384})}catch(p){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${p.message}
|
|
97
97
|
`)}e.child=l,e.logStream=o,e.pid=typeof l.pid=="number"?l.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,l.on("error",p=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
|
|
98
|
-
`)}),l.on("exit",(p,
|
|
99
|
-
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof p=="number"?p:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let
|
|
100
|
-
`);try{o.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
|
|
101
|
-
`)};function
|
|
102
|
-
`))}async function Tr(n,e){let t=ie();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=Nt.join(w.agentsDir(),t),a;try{a=await at.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;ot(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,f=r.get(c);if(f===void 0)continue;let u=i.get(c)??new Set,l=Nt.join(o,c),p;try{p=await at.readdir(l,{withFileTypes:!0})}catch(m){ot(`hydra-acp: prune: failed to read ${l}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let g=m.name;if(g===f||u.has(g)||g.includes(".partial-"))continue;let h=Nt.join(l,g);try{await at.rm(h,{recursive:!0,force:!0}),ot(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(y){ot(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function _r(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let f=await n.registry.load();for(let u of f.agents)await fn(u)==="yes"&&a.push(u.id)}catch(f){return r("warn",`registry load failed: ${f.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:f,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${f.length}, skipped ${u}`)}catch(f){r("warn",`${c}: ${f.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 Nn(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},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 g=Date.parse(p.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||o.push({sessionId:p.sessionId,lastUsedMs:g}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,f=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(m){f+=1,t("warn",`delete ${p} failed: ${m.message}`)}let u=o.length-a.length;if(n.verbose||c>0||f>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Ka(n.maxAgeMs)}`+(f>0?`; ${f} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let l={considered:o.length,deleted:c,failed:f,deferred:u};return d!==void 0&&(l.oldestLastUsedMs=d),l}function $r(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Nn({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 Ka(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 Xa}from"crypto";function Hn(n){if(Array.isArray(n))return n.map(Hn);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Hn(n[t]);return e}return n}function Or(n){let e=JSON.stringify(Hn(n));return Xa("sha256").update(e).digest("hex").slice(0,16)}import*as Hr from"path";import{createHash as Za,randomBytes as ed,timingSafeEqual as td}from"crypto";var jr="hydra_session_",nd=3600*24*30,Fr=12,sd=32,rd=50;function id(){return Hr.join(w.home(),"session-tokens.json")}function Nr(n){return Za("sha256").update(n).digest("hex")}function Br(n){return ed(n).toString("hex")}function od(){return Br(Fr).slice(0,Fr*2)}function ad(){return`${jr}${Br(sd)}`}var Ht=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=id(),s=await re(t);s&&Array.isArray(s.records)&&(e=s.records.filter(dd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=ad(),s=Nr(t),r=od(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:nd,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(jr))return;let t=Nr(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||!td(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(()=>{})},rd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Z(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 dd(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 Ur="Bearer ",jt=class{constructor(e){this.token=e}token;async validate(e){return cd(e,this.token)?"service":void 0}},Bt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Ut=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 Dr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Ur)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Ur.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Lr(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 Dt=class{tokens=new Map;mint(e,t){let s=ft();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 cd(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 Lt=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 ut from"os";import*as oi from"path";import{posix as ud}from"path";import ld from"strip-ansi";function dt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var fd=/[\x00-\x08\x0b-\x1f\x7f]/g;function te(n){return ld(n).replace(fd,"")}function B(n){return te(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function zr(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 vd(t);case"agent_thought_chunk":case"agent_thought":return Id(t);case"user_message_chunk":return bd(t);case"prompt_received":return Sd(t);case"tool_call":return Ad(t,e);case"tool_call_update":return Rd(t,e);case"plan":return Td(t);case"current_mode_update":return _d(t);case"current_model_update":return $d(t);case"turn_complete":return Od(t);case"usage_update":return wd(t);case"available_commands_update":return hd(t);case"available_modes_update":return yd(t);case"session_info_update":return md(t);case"config_option_update":return pd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function pd(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 md(n){let e=H(n,"title"),t=e!==void 0?B(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 gd(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:B(r)};typeof s.description=="string"&&(i.description=B(s.description)),e.push(i)}return e}function hd(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:gd(e)}:null}function yd(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:B(r.id)};typeof r.name=="string"&&(i.name=B(r.name)),typeof r.description=="string"&&(i.description=B(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function wd(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 vd(n){let e=ct(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:dt(n)}}function Id(n){let e=typeof n.text=="string"?te(n.text):ct(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:dt(n)}}function bd(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=ct(n.content);return t===null?null:{kind:"user-text",text:t}}function Sd(n){let e=Fd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Wr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function qr(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 qt(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=qr(r.oldText),o=qr(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 Qr(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:te(t)}function Ad(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title")??H(n,"name")??H(n,"label")??"tool call",r=H(n,"name")??H(n,"title");if(Wr(r)){let l=Qr(n);if(l!==null){let p=H(n,"status"),m={kind:"exit-plan-mode",toolCallId:t,plan:l};return p!==void 0&&(m.status=p),m}}let i=Gr(B(s),n,e),o=H(n,"status"),a=H(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=qt(n);c!==null&&(d.editDiff=c);let f=Vr(n);f!==void 0&&(d.detail=f);let u=dt(n);return u!==void 0&&(d.workerTaskId=u),d}var Jr=64;function Vr(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){let i=B(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return Cd(i,Jr)}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 Md(Me(B(s)),Jr)}var kd=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function xd(n){for(let e of kd)if(n.startsWith(e))return!0;return!1}function Gr(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,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 Me(o)}return xd(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(ud.resolve(t.cwd,n)):n}function Cd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Md(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 Rd(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title"),r=s!==void 0?Gr(B(s),n,e):void 0,i=H(n,"status"),o=qt(n),a=Vr(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=H(n,"name")??s;if(Wr(c)){let l={kind:"exit-plan-mode",toolCallId:t},p=Qr(n);return p!==null&&(l.plan=p),i!==void 0&&(l.status=i),l}let f={kind:"tool-call-update",toolCallId:t};if(r!==void 0&&(f.title=r),a!==void 0&&(f.detail=a),i!==void 0&&(f.status=i),o!==null&&(f.editDiff=o),i==="failed"){let l=Ed(n);l!==null&&(f.errorText=l),Pd(n,l)&&(f.upstreamInterrupted=!0)}let u=dt(n);return u!==void 0&&(f.workerTaskId=u),f}function Ed(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ct(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 te(s)}return null}function Pd(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 Td(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"?B(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 _d(n){let e=H(n,"currentModeId")??H(n,"currentMode")??H(n,"mode");return e?{kind:"mode-changed",mode:B(e)}:null}function $d(n){let e=H(n,"currentModel")??H(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:B(e),...s&&s.length>0?{availableModels:s}:{}}}function Od(n){let e=H(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 ct(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?te(e.text):null}function Fd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=ct(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function H(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Yr(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=Hd(o);if(c.length===0)continue;let f=c;if(d!==void 0){let u=e.get(d)??[],l=[];for(let p of c)u.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||l.push(p);if(l.length===0)continue;e.set(d,[...u,...l]),f=l}for(let u of f)Nd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Kr(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 Nd(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 Hd(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,f=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;f===void 0||u===void 0||e.push({path:o,oldText:f,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=qt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Xr(n){let e=jd(n),t=Bd(e),s=[];Ud(s,n),Dd(s,e,t);let r=s.join(`
|
|
98
|
+
`)}),l.on("exit",(p,g)=>{try{Le.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"null"}
|
|
99
|
+
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof p=="number"?p:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let m=e.exitWaiters.splice(0);for(let y of m)y();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let h=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof h=="object"){e.failureReason=h.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${h.tripped}
|
|
100
|
+
`);try{o.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 Fn(n){try{return process.kill(n,0),!0}catch{return!1}}function it(n,e){return n.code=e,n}var Ka={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},$t=class extends De{constructor(e,t,s={}){super(e,Ka,t,s)}};var Xa={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},Ot=class extends De{connected=new Map;constructor(e,t,s={}){super(e,Xa,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 Ft=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 at from"fs/promises";import*as Nt from"path";var ot=n=>{process.stderr.write(n+`
|
|
101
|
+
`)};function Nn(n){ot=n??(e=>process.stderr.write(e+`
|
|
102
|
+
`))}async function _r(n,e){let t=oe();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=Nt.join(w.agentsDir(),t),a;try{a=await at.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;ot(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,f=r.get(c);if(f===void 0)continue;let u=i.get(c)??new Set,l=Nt.join(o,c),p;try{p=await at.readdir(l,{withFileTypes:!0})}catch(g){ot(`hydra-acp: prune: failed to read ${l}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===f||u.has(m)||m.includes(".partial-"))continue;let h=Nt.join(l,m);try{await at.rm(h,{recursive:!0,force:!0}),ot(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){ot(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function $r(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let f=await n.registry.load();for(let u of f.agents)await pn(u)==="yes"&&a.push(u.id)}catch(f){return r("warn",`registry load failed: ${f.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:f,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${f.length}, skipped ${u}`)}catch(f){r("warn",`${c}: ${f.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 jn(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,f=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(g){f+=1,t("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(n.verbose||c>0||f>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Za(n.maxAgeMs)}`+(f>0?`; ${f} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let l={considered:o.length,deleted:c,failed:f,deferred:u};return d!==void 0&&(l.oldestLastUsedMs=d),l}function Or(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await jn({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 Za(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 ed}from"crypto";function Hn(n){if(Array.isArray(n))return n.map(Hn);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Hn(n[t]);return e}return n}function Fr(n){let e=JSON.stringify(Hn(n));return ed("sha256").update(e).digest("hex").slice(0,16)}import*as Hr from"path";import{createHash as td,randomBytes as nd,timingSafeEqual as sd}from"crypto";var Br="hydra_session_",rd=3600*24*30,Nr=12,id=32,od=50;function ad(){return Hr.join(w.home(),"session-tokens.json")}function jr(n){return td("sha256").update(n).digest("hex")}function Ur(n){return nd(n).toString("hex")}function dd(){return Ur(Nr).slice(0,Nr*2)}function cd(){return`${Br}${Ur(id)}`}var jt=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=ad(),s=await ie(t);s&&Array.isArray(s.records)&&(e=s.records.filter(ud));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=cd(),s=jr(t),r=dd(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:rd,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(Br))return;let t=jr(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||!sd(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(()=>{})},od))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Z(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 ud(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 Dr="Bearer ",Ht=class{constructor(e){this.token=e}token;async validate(e){return ld(e,this.token)?"service":void 0}},Bt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Ut=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 Lr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Dr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Dr.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 Dt=class{tokens=new Map;mint(e,t){let s=ft();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 ld(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 Lt=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 ut from"os";import*as ai from"path";import{posix as fd}from"path";import pd from"strip-ansi";function dt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var gd=/[\x00-\x08\x0b-\x1f\x7f]/g;function ne(n){return pd(n).replace(gd,"")}function L(n){return ne(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Wr(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 bd(t);case"agent_thought_chunk":case"agent_thought":return Sd(t);case"user_message_chunk":return Ad(t);case"prompt_received":return kd(t);case"tool_call":return xd(t,e);case"tool_call_update":return Pd(t,e);case"plan":return $d(t);case"current_mode_update":return Od(t);case"current_model_update":return Fd(t);case"turn_complete":return Nd(t);case"usage_update":return Id(t);case"available_commands_update":return wd(t);case"available_modes_update":return vd(t);case"session_info_update":return hd(t);case"config_option_update":return md(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function md(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 hd(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 yd(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 wd(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:yd(e)}:null}function vd(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 Id(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 bd(n){let e=ct(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:dt(n)}}function Sd(n){let e=typeof n.text=="string"?ne(n.text):ct(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:dt(n)}}function Ad(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=ct(n.content);return t===null?null:{kind:"user-text",text:t}}function kd(n){let e=jd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Qr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Jr(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 qt(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=Jr(r.oldText),o=Jr(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 Vr(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:ne(t)}function xd(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(Qr(r)){let l=Vr(n);if(l!==null){let p=U(n,"status"),g={kind:"exit-plan-mode",toolCallId:t,plan:l};return p!==void 0&&(g.status=p),g}}let i=Yr(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=qt(n);c!==null&&(d.editDiff=c);let f=Gr(n);f!==void 0&&(d.detail=f);let u=dt(n);return u!==void 0&&(d.workerTaskId=u),d}var zr=64;function Gr(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){let i=L(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return Rd(i,zr)}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 Ed(Me(L(s)),zr)}var Cd=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Md(n){for(let e of Cd)if(n.startsWith(e))return!0;return!1}function Yr(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,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 Me(o)}return Md(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(fd.resolve(t.cwd,n)):n}function Rd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Ed(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 Pd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?Yr(L(s),n,e):void 0,i=U(n,"status"),o=qt(n),a=Gr(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(Qr(c)){let l={kind:"exit-plan-mode",toolCallId:t},p=Vr(n);return p!==null&&(l.plan=p),i!==void 0&&(l.status=i),l}let f={kind:"tool-call-update",toolCallId:t};if(r!==void 0&&(f.title=r),a!==void 0&&(f.detail=a),i!==void 0&&(f.status=i),o!==null&&(f.editDiff=o),i==="failed"){let l=Td(n);l!==null&&(f.errorText=l),_d(n,l)&&(f.upstreamInterrupted=!0)}let u=dt(n);return u!==void 0&&(f.workerTaskId=u),f}function Td(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ct(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 ne(s)}return null}function _d(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 $d(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 Od(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Fd(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 Nd(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 ct(n){if(typeof n=="string")return ne(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ne(e.text):null}function jd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=ct(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 Kr(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=Bd(o);if(c.length===0)continue;let f=c;if(d!==void 0){let u=e.get(d)??[],l=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||l.push(p);if(l.length===0)continue;e.set(d,[...u,...l]),f=l}for(let u of f)Hd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Xr(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 Hd(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 Bd(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,f=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;f===void 0||u===void 0||e.push({path:o,oldText:f,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=qt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Zr(n){let e=Ud(n),t=Dd(e),s=[];Ld(s,n),qd(s,e,t);let r=s.join(`
|
|
103
103
|
`);return r.endsWith(`
|
|
104
104
|
`)||(r+=`
|
|
105
|
-
`),r}function
|
|
106
|
-
`)),n.push("")}function
|
|
105
|
+
`),r}function Ud(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=Wr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Dd(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 Ld(n,e){let t=e.session,s=Ys(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Ce(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Bn(a.size)}`:void 0;d.push(c?`${Bn(a.used)} / ${c} tokens`:`${Bn(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
|
|
106
|
+
`)),n.push("")}function qd(n,e,t){if(!e.some(c=>Jd(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},d=()=>{o||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),o=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),n.push("**User:**"),n.push("");for(let f of c.text.split(`
|
|
107
107
|
`))n.push(`> ${Ce(f)}`);n.push(""),n.push("**Assistant:**"),n.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let f=c.text.split(`
|
|
108
|
-
`);for(let u of f)n.push(`> _${Ce(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let f=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Jd(f.status)} ${qd(f)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let f of c.entries){let u=f.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Ce(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Ce(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Ce(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Ld(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function qd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Ce(n.title)}${t}`}function Jd(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 Ce(n){return n.replace(/</g,"<").replace(/>/g,">")}function jn(n){return n.toLocaleString("en-US")}function Zr(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 f of s){let u=f.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(f)}o?i="AND":a&&(i="OR");let c=d.map(f=>Wd(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function Wd(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ei(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:ei(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ei(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Qd(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Vd=5,Gd=200,ti=30;async function ri(n,e,t={}){let s=zd(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Vd,i=t.maxSessions??Gd,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],f=!1;for(let u of d){if(c.length>=i){f=!0;break}let l=await n.loadHistory(u.sessionId).catch(()=>[]),p=Yd(l,s,r);if(p.snippets.length===0)continue;let m={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(m.title=u.title),c.push(m)}return{query:e,truncated:f,results:c}}function Yd(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=Kd(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 Kd(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Xd(a).filter(c=>Qd(t,c.kind));for(let c of d){let f=c.text.toLowerCase(),u=f.indexOf(r);if(u===-1)continue;let l=0;for(;u!==-1;)l++,u=f.indexOf(r,u+r.length);if(i+=l,o.length<s){let p=f.indexOf(r),m={kind:c.kind,text:sc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Xd(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=Jt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?te(s.text):Jt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(tc(s))return[];let i=Jt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=nc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Zd(s);default:return[]}}function Zd(n){let e=ni(n,"name"),t=ni(n,"title"),s=[];if(t!==void 0){let a=B(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=B(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=si(r);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=si(i);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=ec(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function ec(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=B(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=B(s);if(r.length>0)return r}}return null}function tc(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 Jt(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?te(e.text):""}function nc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Jt(t);s.length>0&&e.push(s)}return e.join("")}function ni(n,e){let t=n[e];return typeof t=="string"?t:void 0}function si(n){try{return JSON.stringify(n)}catch{return""}}function sc(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-ti),d=Math.min(s.length,o+i.length+ti),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function ii(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Zr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ai(n,e,t){n.get("/v1/sessions",async s=>{let r=s.query,i=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:i})}}),n.get("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.getOne(o);return a||(r.code(404).send({error:"session not found"}),r)}),n.post("/v1/sessions/search",async(s,r)=>{let i=s.body??{},o=typeof i.q=="string"?i.q:"";if(o.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(i.sessionIds)?i.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await ri(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Ee(i.cwd??t.cwd),a=i.agentId??t.agentId;try{let d=await e.create({cwd:o,agentId:a,mcpServers:i.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),n.post("/v1/sessions/collect",async(s,r)=>{let i=s.body??{},o=typeof i.maxAgeDays=="number"&&i.maxAgeDays>0?i.maxAgeDays*24*60*60*1e3:0,a=typeof i.limit=="number"&&i.limit>0?i.limit:1e3,d=i.selection==="explicit"||i.selection==="unpromoted"?i.selection:"unpromoted";try{let c=await Nn({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),n.post("/v1/sessions/:id/kill",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=f=>oi.join(ut.tmpdir(),`hydra-acp-stdin-${f}.log`));try{return a.openStream(c)}catch(f){return r.code(409).send({error:f.message}),r}}),n.post("/v1/sessions/:id/stdin",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",f=d.eof===!0;try{return a.streamWrite(c,f)}catch(u){return r.code(409).send({error:u.message}),r}}),n.patch("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{};if(a.priority!==void 0){let c=a.priority,f;if(c===null||c===0)f=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)f=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,f)){r.code(404).send({error:"session not found"});return}r.code(204).send();return}if(a.regen===!0){if(!(e.get(o)!==void 0||await e.hasRecord(o))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(o),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(o,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.delete("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.get("/v1/sessions/:id/export",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.query?.tools,d=a==="references"?"references":ur(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=tt({record:c.record,history:d==="summary"?lr(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:Q,machine:ut.hostname(),hydraHost:ii(t)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(f)}),n.get("/v1/sessions/:id/diff",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=s.query??{},c=d.fold==="true"||d.fold==="1",f=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(l=>l.trim()).filter(l=>l.length>0)):void 0,u=Yr(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:Kr(l.hunks)}))),r.code(200).send(u)}),n.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let i=s.params,o=await e.resolveCanonicalId(i.id)??i.id,a=await e.loadToolBlob(o,i.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),n.get("/v1/sessions/:id/transcript",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=tt({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:Q,machine:ut.hostname(),hydraHost:ii(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Xr(d))}),n.post("/v1/sessions/:id/fork",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=Ee(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}if(a.title!==void 0){if(typeof a.title!="string"){r.code(400).send({error:"title must be a string"});return}d.title=a.title}try{let c=await e.forkSession(o,d);r.code(201).send(c)}catch(c){let f=c;if(f.code===I.SessionNotFound){r.code(404).send({error:f.message});return}if(f.code===I.InvalidParams||f.code===I.AgentNotInstalled){r.code(400).send({error:f.message});return}r.code(500).send({error:f.message})}}),n.post("/v1/sessions/import",async(s,r)=>{let i=s.body??{};if(i.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let o;if(i.cwd!==void 0){if(typeof i.cwd!="string"||i.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}o=i.cwd}let a;try{a=vr(i.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:i.replace===!0,...o!==void 0?{cwd:o}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===I.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),n.get("/v1/sessions/:id/history",async(s,r)=>{let i=s.params.id,o=s.query,a=o?.follow==="1"||o?.follow==="true",d=await e.resolveCanonicalId(i)??i,c=e.get(d),f,u,l=!1,p=1e4,m=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
|
|
109
|
-
`):(
|
|
110
|
-
`);let y=h;typeof y.recordedAt=="number"&&
|
|
111
|
-
`)}}return l=!0,u||r.raw.end(),r})}function di(n,e,t,s={}){n.get("/v1/agents",async()=>$e(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 ae(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 ci(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var rc=/^[A-Za-z0-9._-]+$/;function zt(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=ic(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){lt(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){lt(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){lt(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){lt(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){lt(o,d)}})}function lt(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 ic(n){let e=n.name;if(typeof e!="string"||!rc.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 ui(n,e){zt(n,"extension",e)}function li(n,e){zt(n,"transformer",e)}function fi(n,e){n.get("/v1/config",async()=>e)}import{z as Je}from"zod";import*as qe from"fs/promises";import*as pi from"path";import{randomBytes as Up,scrypt as oc,timingSafeEqual as ac}from"crypto";import{promisify as dc}from"util";var cc=dc(oc);function mi(){return pi.join(w.home(),"password-hash")}var uc=128*1024*1024;async function gi(){try{return(await qe.readFile(mi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function hi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await qe.readFile(mi(),"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 cc(n,o,a.length,{N:s,r,p:i,maxmem:uc});return d.length!==a.length?!1:ac(d,a)}var lc=Je.object({password:Je.string().min(1),label:Je.string().min(1).max(256).optional(),ttlSec:Je.number().int().positive().optional()}),fc=Je.object({id:Je.string().optional()}).optional();function yi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=pc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=lc.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await gi())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await hi(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=fc.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 pc(n){return n.ip||"unknown"}import{nanoid as Jn}from"nanoid";function Bn(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 vi}from"crypto";function $(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function wc(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 ne(n,e,t){let s=n.get(e);if(!s)throw $(I.SessionNotFound,t??`session ${e} not found`);return s}async function Un(n,e){let t=bi(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),kc(s,n),s}function Ii(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Lr({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=Bn(t),a=new Se(o),d={clientId:`hydra_client_${Jn(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,l)=>{if(d.attached.get(u)?.readonly)throw $(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=ks.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),Ac()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},m=Array.isArray(p.commands)?p.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 u.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let p=l??{},m=typeof p.instructions=="string"?p.instructions:void 0,g=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 S={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(S.outputSchema=y.outputSchema),S}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let l=u??{},p=Array.isArray(l.intercepts)?l.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.method=="string"?l.method:void 0,g=l.envelope,h=l.route;if(!p||!m)throw $(-32602,"emit_message requires sessionId and method");let y=ne(e.manager,p),S=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(S)return y.dischargeClaim(S,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,m,g)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,m,g)};throw $(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(-32602,"hydra-acp/session/request_permission requires sessionId");return ne(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>bc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,S=y&&typeof y.title=="string"?y.title:void 0;if(!m&&g){let N=e.manager.get(g);N&&(m=N.cwd)}if(!m)throw $(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let M=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:g,interactive:M,transformChain:[],title:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=e.manager.get(p);if(m)return await m.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 l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,m=l.until==="idle"?"idle":"turn_complete",g=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw $(-32602,"await_child requires childSessionId");let h=ne(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let k=[],N=[],U=0,G=!1,L,A,T=!1,j=()=>{T||(T=!0,clearTimeout(q),L?.(),A?.(),y(G?{entries:k,truncated:!0}:{entries:k}))};L=h.onBroadcast(Y=>{let D=wc(Y);for(k.push(Y),N.push(D),U+=D;k.length>0&&(k.length>1e3||U>1048576);)k.shift(),U-=N.shift()??0,G=!0;m==="turn_complete"&&Y.params?.update?.sessionUpdate==="turn_complete"&&j()});let q=setTimeout(j,g);typeof q.unref=="function"&&q.unref(),A=h.onClose(()=>j())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!p)throw $(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let l=u??{},p=typeof l.token=="string"?l.token:void 0,m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw $(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=await e.manager.loadToolBlob(p,l.hash);if(m===null)throw $(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async u=>vc(u,e)),a.onRequest("session/new",async u=>{let l=xs.parse(u),p=Ve(u?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(A=>typeof A=="string")?p.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,S=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=vi(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let T={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};S=[...l.mcpServers??[],T]}let M=bi(e);M!==void 0&&(S=[...S??[],...M.descriptors]);let k;try{k=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:S,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:wi(a),transformChain:g,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(A){throw y!==void 0&&y.abandon(A instanceof Error?A:void 0),M!==void 0&&M.abandon(A instanceof Error?A:void 0),A}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let A=h,T=e.mcpTokenRegistry;y.complete(k),k.onClose(()=>{T.unbind(A)})}M!==void 0&&M.bindToSession(k);let N,U;try{N=Wt(a,k,d),{entries:U}=await k.attach(N,"full")}catch(A){throw await k.close({deleteRecord:!1}).catch(()=>{}),A}d.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let A of U){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}})()});let G=Dn(k),L=Ln(k);return{sessionId:k.sessionId,...G?{modes:G}:{},...L?{models:L}:{},configOptions:k.buildConfigOptions(),_meta:qn(e.manager,k,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let l=Ms.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Ve(l._meta),g=m.resume,h=m.readonly===!0;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(y);if(!S&&h){let A=await e.manager.loadFromDisk(y);if(!A)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);let T=await e.manager.loadHistory(y),j=l.clientId??`cli_${Jn(8)}`;d.attached.set(A.hydraSessionId,{sessionId:A.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${A.hydraSessionId} clientId=${j} attachedCount=${d.attached.size} replayed=${T.length}`);for(let q of T)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:A.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:T.length,_meta:Sc(A)}}if(!S){let A=await e.manager.loadFromDisk(y),T=A;if(g&&(T={...A,hydraSessionId:l.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!T)throw $(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let j=T.originatingClient?T:{...T,originatingClient:d.clientInfo};S=await Un(e,{...j,onInstallProgress:wi(a)})}let M=Wt(a,S,d,l.clientInfo,l.clientId),k=m.replayMode==="drip",{entries:N,appliedPolicy:U}=await S.attach(M,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:k,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:M.clientId,readonly:h}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${M.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${U} replayed=${N.length} readonly=${h}${k?" replayMode=drip":""}`),k){let A=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,T=750;(async()=>{let j=null;for(let q of N){let Y=typeof q.recordedAt=="number"?q.recordedAt:null;if(j!==null&&Y!==null){let D=Math.min(T,Math.max(0,(Y-j)/A));D>0&&await new Promise(Ie=>setTimeout(Ie,D))}Y!==null&&(j=Y);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let A=0;A<N.length&&!a.isClosed();A++){let T=N[A],j=a.notify(T.method,T.params).catch(()=>{});(A+1)%200===0&&await j}S.replayPendingPermissions(M);let G=Dn(S),L=Ln(S);return{sessionId:S.sessionId,clientId:M.clientId,connectedClients:S.connectedClients(M.clientId),historyPolicy:U,replayed:N.length,...G?{modes:G}:{},...L?{models:L}:{},configOptions:S.buildConfigOptions(),_meta:qn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=Rs.parse(u),p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(l.sessionId);return m?.detach(p.clientId),d.attached.delete(l.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Qe]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=Es.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==xt).map(Ps)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw $(I.InternalError,"agent registry unavailable");return $e(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Ts.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),$(I.SessionNotFound,"not attached to session");let m=e.manager.get(l.sessionId);if(!m){let g=await e.manager.loadFromDisk(l.sessionId);if(!g)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),m=await Un(e,g);let h=Wt(a,m,d,void 0,p.clientId);await m.attach(h,"none")}return m.prompt(p.clientId,l)});let f=u=>{let l;try{l=wt.parse(u)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let m=e.manager.get(l.sessionId);m&&m.cancel(p.clientId).catch(g=>{n.log.warn(`session/cancel for ${l.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=$s.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ne(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ne(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Os.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ne(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Fs.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"not attached to session");return ne(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,g=e.manager.get(m);if(!g){let k=await e.manager.loadFromDisk(m);if(!k)throw $(I.SessionNotFound,`session ${p} not found in memory or on disk`);g=await Un(e,k)}let h=Wt(a,g,d),{entries:y}=await g.attach(h,"pending_only");d.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let k of y){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}g.replayPendingPermissions(h);let S=Dn(g),M=Ln(g);return{sessionId:g.sessionId,...S?{modes:S}:{},...M?{models:M}:{},configOptions:g.buildConfigOptions(),_meta:qn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Ic(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:m}=p,g=await p.session.forwardRequest("session/set_model",{...u,modelId:m});return p.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async u=>{let l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw $(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw $(I.InvalidParams,"session/set_mode requires string modeId");let m=ne(e.manager,l.sessionId),g=await m.forwardRequest("session/set_mode",u);return m.applyModeChange(l.modeId),g}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>$(I.InvalidParams,y),m=l?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let g=ne(e.manager,l.sessionId),h=g.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),g.applyModelChange(l.value);break}case"mode":{l.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),g.applyModeChange(l.value);break}case"agent":{l.value!==g.agentId&&await g.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw $(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw $(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),ne(e.manager,p).forwardRequest(l,u)})})}async function vc(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 c=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(c)}let d=(a.authMethods??[]).map(c=>c.id);if(!d.includes(s))throw $(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${d.map(c=>JSON.stringify(c)).join(", ")}]`);try{return await a.connection.request("authenticate",{methodId:s})}catch(c){throw ke(c,a)}}function wi(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(Ns,t).catch(()=>{})}}function Dn(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 Ln(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 Ic(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=Fe(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 bc(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 ne(t.manager,r).addTransformer(i),{ok:!0}}function Sc(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{[Qe]:yt(e,t)}}function qn(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 We(e.agentMeta,yt(s,r))}function Ac(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Q},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:We(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function kc(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 Wt(n,e,t,s,r){return{clientId:r??`cli_${Jn(8)}`,connection:n,clientInfo:s}}function bi(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=vi(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var Qt=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 xc}from"crypto";import{McpServer as Cc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Mc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z}from"zod";var Si="Bearer ";function Vt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Si))return;let t=e.slice(Si.length).trim();return t.length>0?t:void 0}function Rc(n){let e=new Cc({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:z.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:z.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:z.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:z.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:z.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:z.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:z.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:z.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:z.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:z.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:z.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:z.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:z.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:z.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:z.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:z.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 Ec=1e4;function Ai(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=Rc(a),f=new Mc({sessionIdGenerator:()=>xc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Vt(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 f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(g=>{l=setTimeout(()=>g(void 0),Ec)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),m===void 0){a.code(503).send({error:"session not ready"});return}f=m}let u=await s(d,f);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 Gt=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 Nc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Hc}from"crypto";import{Server as Pc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Tc,ListToolsRequestSchema as _c}from"@modelcontextprotocol/sdk/types.js";var $c=6e4;function ki(n,e,t,s={}){let r=s.invokeTimeoutMs??$c,i=typeof t=="function"?async()=>t():async()=>t,o=new Pc({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(_c,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Tc,async d=>{let c=d.params.name;if(!a.has(c))return Yt(`unknown tool: ${c}`);try{let f=await i(),u=await Oc(e.connection,n,c,d.params.arguments??{},f,r);return Fc(u,c)}catch(f){return Yt(f instanceof Error?f.message:String(f))}}),o}async function Oc(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 Fc(n,e){if(n===null||typeof n!="object")return Yt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Yt(`extension ${e} omitted content array`)}function Yt(n){return{content:[{type:"text",text:n}],isError:!0}}var jc=1e4;function xi(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let S=r.get(f);if(S!==void 0){r.delete(f);for(let M of S.values())await i(M)}}));let p=l.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let h=ki(u,m,async()=>{let S=e.lookup(f);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let M,k=new Promise(U=>{M=setTimeout(()=>U(void 0),jc)}),N=await Promise.race([S.sessionReady.catch(()=>{}),k]);if(M!==void 0&&clearTimeout(M),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new Nc({sessionIdGenerator:()=>Hc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Vt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let m=f.params.name,g=await a(l,m);if(g===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await g.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Lc(n,e){Jc(n);let t=n.daemon.tls?{key:await ve.readFile(n.daemon.tls.key),cert:await ve.readFile(n.daemon.tls.cert)}:void 0;await ve.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await qc(n.daemon.logLevel),i=Bc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Uc,{options:{handleProtocols:Vn}}),an(E=>{i.log.info(E)}),un(E=>{i.log.info(E)});let o=await Ht.load(),a=new Lt,d=new Dt,c=new Ut([new jt(e),new Bt(o),d]),f=Dr({validator:c});i.addHook("onRequest",async(E,le)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,le)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new ze(n,{onFetched:()=>{Tr(p,y)}});Fn(E=>i.log.info(E));let m={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},g=E=>fe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});cs(n.compressToolContent);let h=new Ft,y=new rt(p,g,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:m,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),S=new $t(ns(n),void 0,{tokenRegistry:d}),M=new Ot(ss(n),void 0,{tokenRegistry:d});ci(i,Q,Or(n)),ai(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),di(i,p,y,{npmRegistry:n.npmRegistry}),ui(i,S),li(i,M),fi(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]}),yi(i,{store:o,rateLimiter:a});let k=new Qt,N=new Gt;Ai(i,k),xi(i,k,N);let U,G=()=>{if(U!==void 0)return U;let E=i.server.address(),le=E&&typeof E=="object"?E.port:n.daemon.port;return U=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${le}`,U};Ii(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,le)=>S.reportVersion(E,le),onTransformerVersion:(E,le)=>M.reportVersion(E,le),transformers:M,extensionCommands:h,mcpTokenRegistry:k,extensionMcp:N,getDaemonOrigin:G,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let L=i.server.address(),A=L&&typeof L=="object"?L.port:n.daemon.port;await ve.mkdir(w.home(),{recursive:!0}),await ve.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:A,startedAt:new Date().toISOString()})+`
|
|
112
|
-
`,{encoding:"utf8",mode:384});let
|
|
108
|
+
`);for(let u of f)n.push(`> _${Ce(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let f=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Wd(f.status)} ${zd(f)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let f of c.entries){let u=f.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Ce(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Ce(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Ce(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Jd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function zd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Ce(n.title)}${t}`}function Wd(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 Ce(n){return n.replace(/</g,"<").replace(/>/g,">")}function Bn(n){return n.toLocaleString("en-US")}function ei(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Qd(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 f of s){let u=f.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(f)}o?i="AND":a&&(i="OR");let c=d.map(f=>Vd(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function Vd(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ti(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:ti(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ti(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Gd(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Yd=5,Kd=200,ni=30;async function ii(n,e,t={}){let s=Qd(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Yd,i=t.maxSessions??Kd,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],f=!1;for(let u of d){if(c.length>=i){f=!0;break}let l=await n.loadHistory(u.sessionId).catch(()=>[]),p=Xd(l,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:f,results:c}}function Xd(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=Zd(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 Zd(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=ec(a).filter(c=>Gd(t,c.kind));for(let c of d){let f=c.text.toLowerCase(),u=f.indexOf(r);if(u===-1)continue;let l=0;for(;u!==-1;)l++,u=f.indexOf(r,u+r.length);if(i+=l,o.length<s){let p=f.indexOf(r),g={kind:c.kind,text:ic(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 ec(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=Jt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ne(s.text):Jt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(sc(s))return[];let i=Jt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=rc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return tc(s);default:return[]}}function tc(n){let e=si(n,"name"),t=si(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=ri(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=ri(i);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=nc(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function nc(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 sc(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 Jt(n){if(typeof n=="string")return ne(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ne(e.text):""}function rc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Jt(t);s.length>0&&e.push(s)}return e.join("")}function si(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ri(n){try{return JSON.stringify(n)}catch{return""}}function ic(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-ni),d=Math.min(s.length,o+i.length+ni),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function oi(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ei(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function di(n,e,t){n.get("/v1/sessions",async s=>{let r=s.query,i=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:i})}}),n.get("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.getOne(o);return a||(r.code(404).send({error:"session not found"}),r)}),n.post("/v1/sessions/search",async(s,r)=>{let i=s.body??{},o=typeof i.q=="string"?i.q:"";if(o.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(i.sessionIds)?i.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await ii(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Ee(i.cwd??t.cwd),a=i.agentId??t.agentId;try{let d=await e.create({cwd:o,agentId:a,mcpServers:i.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),n.post("/v1/sessions/collect",async(s,r)=>{let i=s.body??{},o=typeof i.maxAgeDays=="number"&&i.maxAgeDays>0?i.maxAgeDays*24*60*60*1e3:0,a=typeof i.limit=="number"&&i.limit>0?i.limit:1e3,d=i.selection==="explicit"||i.selection==="unpromoted"?i.selection:"unpromoted";try{let c=await jn({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),n.post("/v1/sessions/:id/kill",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=f=>ai.join(ut.tmpdir(),`hydra-acp-stdin-${f}.log`));try{return a.openStream(c)}catch(f){return r.code(409).send({error:f.message}),r}}),n.post("/v1/sessions/:id/stdin",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",f=d.eof===!0;try{return a.streamWrite(c,f)}catch(u){return r.code(409).send({error:u.message}),r}}),n.patch("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{};if(a.priority!==void 0){let c=a.priority,f;if(c===null||c===0)f=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)f=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,f)){r.code(404).send({error:"session not found"});return}r.code(204).send();return}if(a.regen===!0){if(!(e.get(o)!==void 0||await e.hasRecord(o))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(o),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(o,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.delete("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.get("/v1/sessions/:id/export",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.query?.tools,d=a==="references"?"references":lr(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=tt({record:c.record,history:d==="summary"?fr(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:V,machine:ut.hostname(),hydraHost:oi(t)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(f)}),n.get("/v1/sessions/:id/diff",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=s.query??{},c=d.fold==="true"||d.fold==="1",f=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(l=>l.trim()).filter(l=>l.length>0)):void 0,u=Kr(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:Xr(l.hunks)}))),r.code(200).send(u)}),n.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let i=s.params,o=await e.resolveCanonicalId(i.id)??i.id,a=await e.loadToolBlob(o,i.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),n.get("/v1/sessions/:id/transcript",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=tt({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:V,machine:ut.hostname(),hydraHost:oi(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Zr(d))}),n.post("/v1/sessions/:id/fork",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=Ee(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}if(a.title!==void 0){if(typeof a.title!="string"){r.code(400).send({error:"title must be a string"});return}d.title=a.title}try{let c=await e.forkSession(o,d);r.code(201).send(c)}catch(c){let f=c;if(f.code===I.SessionNotFound){r.code(404).send({error:f.message});return}if(f.code===I.InvalidParams||f.code===I.AgentNotInstalled){r.code(400).send({error:f.message});return}r.code(500).send({error:f.message})}}),n.post("/v1/sessions/import",async(s,r)=>{let i=s.body??{};if(i.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let o;if(i.cwd!==void 0){if(typeof i.cwd!="string"||i.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}o=i.cwd}let a;try{a=Ir(i.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:i.replace===!0,...o!==void 0?{cwd:o}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===I.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),n.get("/v1/sessions/:id/history",async(s,r)=>{let i=s.params.id,o=s.query,a=o?.follow==="1"||o?.follow==="true",d=await e.resolveCanonicalId(i)??i,c=e.get(d),f,u,l=!1,p=1e4,g=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
|
|
109
|
+
`):(g.push(h),g.length>p&&g.shift()))})),s.raw.on("close",()=>{u?.(),r.raw.writableEnded||r.raw.end()});try{f=await c.getHistorySnapshot()}catch(h){throw u?.(),h}}else{let h=await e.getHistory(d);if(h===void 0)return r.code(404).send({error:"session not found"}),r;f=h}r.raw.setHeader("Content-Type","application/x-ndjson"),r.raw.setHeader("Cache-Control","no-cache"),r.raw.statusCode=200;let m=new Set;for(let h of f??[]){r.raw.write(JSON.stringify(h)+`
|
|
110
|
+
`);let y=h;typeof y.recordedAt=="number"&&m.add(String(y.recordedAt))}for(;g.length>0;){let h=g.splice(0,g.length);for(let y of h){let k=y,S=typeof k.recordedAt=="number"?String(k.recordedAt):"";S&&m.has(S)||r.raw.write(JSON.stringify(y)+`
|
|
111
|
+
`)}}return l=!0,u||r.raw.end(),r})}function ci(n,e,t,s={}){n.get("/v1/agents",async()=>$e(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 ee(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 ui(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var oc=/^[A-Za-z0-9._-]+$/;function zt(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=ac(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){lt(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){lt(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){lt(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){lt(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){lt(o,d)}})}function lt(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 ac(n){let e=n.name;if(typeof e!="string"||!oc.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 li(n,e){zt(n,"extension",e)}function fi(n,e){zt(n,"transformer",e)}function pi(n,e){n.get("/v1/config",async()=>e)}import{z as Je}from"zod";import*as qe from"fs/promises";import*as gi from"path";import{randomBytes as Lp,scrypt as dc,timingSafeEqual as cc}from"crypto";import{promisify as uc}from"util";var lc=uc(dc);function mi(){return gi.join(w.home(),"password-hash")}var fc=128*1024*1024;async function hi(){try{return(await qe.readFile(mi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function yi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await qe.readFile(mi(),"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 lc(n,o,a.length,{N:s,r,p:i,maxmem:fc});return d.length!==a.length?!1:cc(d,a)}var pc=Je.object({password:Je.string().min(1),label:Je.string().min(1).max(256).optional(),ttlSec:Je.number().int().positive().optional()}),gc=Je.object({id:Je.string().optional()}).optional();function wi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=mc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=pc.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await hi())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await yi(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=gc.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 mc(n){return n.ip||"unknown"}import{nanoid as zn}from"nanoid";function Un(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 Ii}from"crypto";import*as bi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Ic(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 se(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function Dn(n,e){let t=Ai(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),Cc(s,n),s}function Si(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=Un(t),a=new Se(o),d={clientId:`hydra_client_${zn(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,l)=>{if(d.attached.get(u)?.readonly)throw _(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=xs.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),xc()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},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 l=>{let p=l??{},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 k={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(k.outputSchema=y.outputSchema),k}).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 l=u??{},p=Array.isArray(l.intercepts)?l.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 l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,m=l.envelope,h=l.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=se(e.manager,p),k=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(k)return y.dischargeClaim(k,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 l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw _(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>Ac(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,k=y&&typeof y.title=="string"?y.title:void 0;if(!g&&m){let N=e.manager.get(m);N&&(g=N.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let S=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:S,transformChain:[],title:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.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 l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.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 l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",m=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=se(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let A=[],N=[],H=0,Y=!1,J,R,P=!1,j=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(Y?{entries:A,truncated:!0}:{entries:A}))};J=h.onBroadcast(q=>{let D=Ic(q);for(A.push(q),N.push(D),H+=D;A.length>0&&(A.length>1e3||H>1048576);)A.shift(),H-=N.shift()??0,Y=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&j()});let B=setTimeout(j,m);typeof B.unref=="function"&&B.unref(),R=h.onClose(()=>j())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.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 l=u??{},p=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.estimatedRemainingMs=="number"?l.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 l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw _(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=await e.manager.loadToolBlob(p,l.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>bc(u,e)),a.onRequest("session/new",async u=>{let l=Cs.parse(u),p=Ve(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,k=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Ii(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}`}]};k=[...l.mcpServers??[],P]}let S=Ai(e);S!==void 0&&(k=[...k??[],...S.descriptors]);let A;try{A=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:k,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:vi(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),S!==void 0&&S.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(A),A.onClose(()=>{P.unbind(R)})}S!==void 0&&S.bindToSession(A);let N,H;try{N=Wt(a,A,d),{entries:H}=await A.attach(N,"full")}catch(R){throw await A.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of H){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let Y=Ln(A),J=qn(A);return{sessionId:A.sessionId,...Y?{modes:Y}:{},...J?{models:J}:{},configOptions:A.buildConfigOptions(),_meta:Jn(e.manager,A,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let l=Rs.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ve(l._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!m} readonly=${h}`);let k=m?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(k);if(!S&&h){let P=await e.manager.loadFromDisk(k);if(!P)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);let j=await e.manager.loadHistory(k),B=l.clientId??`cli_${zn(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=${j.length}`);for(let q of j)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:j.length,_meta:kc(P)}}if(!S){let P=await e.manager.loadFromDisk(k),j=P;if(m&&(j={...P,hydraSessionId:l.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!j)throw _(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let B=j.originatingClient?j:{...j,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;S=await Dn(e,{...q,onInstallProgress:vi(a)})}let A=Wt(a,S,d,l.clientInfo,l.clientId),N=g.replayMode==="drip",{entries:H,appliedPolicy:Y}=await S.attach(A,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:N,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(S.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${Y} replayed=${H.length} readonly=${h}${N?" replayMode=drip":""}`),N){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,j=750;(async()=>{let B=null;for(let q of H){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let me=Math.min(j,Math.max(0,(D-B)/P));me>0&&await new Promise(Kt=>setTimeout(Kt,me))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<H.length&&!a.isClosed();P++){let j=H[P],B=a.notify(j.method,j.params).catch(()=>{});(P+1)%200===0&&await B}S.replayPendingPermissions(A);let J=Ln(S),R=qn(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:Y,replayed:H.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:S.buildConfigOptions(),_meta:Jn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=Es.parse(u),p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(l.sessionId);return g?.detach(p.clientId),d.attached.delete(l.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Qe]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=Ps.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==xt).map(Ts)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return $e(e.registry)}),a.onRequest("session/prompt",async u=>{let l=_s.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),_(I.SessionNotFound,"not attached to session");let g=e.manager.get(l.sessionId);if(!g){let m=await e.manager.loadFromDisk(l.sessionId);if(!m)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),g=await Dn(e,m);let h=Wt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,l)});let f=u=>{let l;try{l=wt.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let g=e.manager.get(l.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${l.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=Os.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Fs.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),se(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Ns.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"not attached to session");return se(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.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 A=await e.manager.loadFromDisk(g);if(!A)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Dn(e,A)}let h=Wt(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 A of y){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}m.replayPendingPermissions(h);let k=Ln(m),S=qn(m);return{sessionId:m.sessionId,...k?{modes:k}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Jn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Sc(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 l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw _(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw _(I.InvalidParams,"session/set_mode requires string modeId");let g=se(e.manager,l.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(l.modeId),m}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>_(I.InvalidParams,y),g=l?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let m=se(e.manager,l.sessionId),h=m.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),m.applyModelChange(l.value);break}case"mode":{l.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),m.applyModeChange(l.value);break}case"agent":{l.value!==m.agentId&&await m.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw _(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw _(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),se(e.manager,p).forwardRequest(l,u)})})}async function bc(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 l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],c=d.find(l=>l.id===s);if(!c){let l=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(p=>JSON.stringify(p)).join(", ")}]`)}let f=c._meta?.type;if((c.type??(f==="agent"||f==="terminal"?f:"agent"))==="terminal"){let l=c._meta?.args,p=[];if(l!==void 0){if(!Array.isArray(l))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${l===null?"null":typeof l}`);for(let y of l)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=l}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,k]of Object.entries(process.env))typeof k=="string"&&(m[y]=k);Object.assign(m,g.env);let h=bi.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(l){throw ke(l,a)}}function vi(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(js,t).catch(()=>{})}}function Ln(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 qn(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 Sc(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=Fe(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 Ac(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 se(t.manager,r).addTransformer(i),{ok:!0}}function kc(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{[Qe]:yt(e,t)}}function Jn(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 We(e.agentMeta,yt(s,r))}function xc(){return{protocolVersion:1,agentInfo:{name:"hydra",version:V},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:We(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Cc(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 Wt(n,e,t,s,r){return{clientId:r??`cli_${zn(8)}`,connection:n,clientInfo:s}}function Ai(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=Ii(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var Qt=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 Mc}from"crypto";import{McpServer as Rc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ec}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as W}from"zod";var ki="Bearer ";function Vt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(ki))return;let t=e.slice(ki.length).trim();return t.length>0?t:void 0}function Pc(n){let e=new Rc({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:W.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:W.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:W.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:W.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:W.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:W.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:W.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:W.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:W.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:W.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:W.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:W.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:W.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:W.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:W.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:W.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 Tc=1e4;function xi(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=Pc(a),f=new Ec({sessionIdGenerator:()=>Mc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Vt(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 f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(m=>{l=setTimeout(()=>m(void 0),Tc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),g===void 0){a.code(503).send({error:"session not ready"});return}f=g}let u=await s(d,f);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 Gt=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 Hc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Bc}from"crypto";import{Server as _c}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as $c,ListToolsRequestSchema as Oc}from"@modelcontextprotocol/sdk/types.js";var Fc=6e4;function Ci(n,e,t,s={}){let r=s.invokeTimeoutMs??Fc,i=typeof t=="function"?async()=>t():async()=>t,o=new _c({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(Oc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler($c,async d=>{let c=d.params.name;if(!a.has(c))return Yt(`unknown tool: ${c}`);try{let f=await i(),u=await Nc(e.connection,n,c,d.params.arguments??{},f,r);return jc(u,c)}catch(f){return Yt(f instanceof Error?f.message:String(f))}}),o}async function Nc(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 jc(n,e){if(n===null||typeof n!="object")return Yt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Yt(`extension ${e} omitted content array`)}function Yt(n){return{content:[{type:"text",text:n}],isError:!0}}var Uc=1e4;function Mi(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let k=r.get(f);if(k!==void 0){r.delete(f);for(let S of k.values())await i(S)}}));let p=l.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Ci(u,g,async()=>{let k=e.lookup(f);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let S,A=new Promise(H=>{S=setTimeout(()=>H(void 0),Uc)}),N=await Promise.race([k.sessionReady.catch(()=>{}),A]);if(S!==void 0&&clearTimeout(S),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new Hc({sessionIdGenerator:()=>Bc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Vt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=f.params.name,m=await a(l,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Jc(n,e){Wc(n);let t=n.daemon.tls?{key:await Ie.readFile(n.daemon.tls.key),cert:await Ie.readFile(n.daemon.tls.cert)}:void 0;await Ie.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await zc(n.daemon.logLevel),i=Dc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Lc,{options:{handleProtocols:Gn}}),dn(E=>{i.log.info(E)}),ln(E=>{i.log.info(E)});let o=await jt.load(),a=new Lt,d=new Dt,c=new Ut([new Ht(e),new Bt(o),d]),f=Lr({validator:c});i.addHook("onRequest",async(E,le)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,le)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new ze(n,{onFetched:()=>{_r(p,y)}});Nn(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>fe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});us(n.compressToolContent);let h=new Ft,y=new rt(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}),k=new $t(ss(n),void 0,{tokenRegistry:d}),S=new Ot(rs(n),void 0,{tokenRegistry:d});ui(i,V,Fr(n)),di(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),ci(i,p,y,{npmRegistry:n.npmRegistry}),li(i,k),fi(i,S),pi(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]}),wi(i,{store:o,rateLimiter:a});let A=new Qt,N=new Gt;xi(i,A),Mi(i,A,N);let H,Y=()=>{if(H!==void 0)return H;let E=i.server.address(),le=E&&typeof E=="object"?E.port:n.daemon.port;return H=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${le}`,H};Si(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,le)=>k.reportVersion(E,le),onTransformerVersion:(E,le)=>S.reportVersion(E,le),transformers:S,extensionCommands:h,mcpTokenRegistry:A,extensionMcp:N,getDaemonOrigin:Y,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 Ie.mkdir(w.home(),{recursive:!0}),await Ie.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
|
|
112
|
+
`,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",j=n.daemon.tls?"wss":"ws",B={daemonUrl:`${P}://${n.daemon.host}:${R}`,daemonHost:n.daemon.host,daemonPort:R,serviceToken:e,daemonWsUrl:`${j}://${n.daemon.host}:${R}/acp`,hydraHome:w.home()};k.setContext(B),S.setContext(B),await k.start(),await S.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let q=n.daemon.agentSyncIntervalMinutes*60*1e3,D=q>0?$r({registry:p,manager:y,intervalMs:q,logger:g}):void 0,me=n.daemon.sessionGcIntervalMinutes*60*1e3,Kt=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Wn=me>0?Or({manager:y,intervalMs:me,maxAgeMs:Kt,logger:g}):void 0;return{app:i,manager:y,registry:p,extensions:k,transformers:S,mcpTokenRegistry:A,extensionMcp:N,processRegistry:d,shutdown:async()=>{Wn&&Wn(),D&&D(),clearInterval(u),clearInterval(l);let E=async(le,Qn)=>{try{await Qn()}catch(Xt){i.log.warn(`shutdown step ${le} failed: ${Xt instanceof Error?Xt.message:String(Xt)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>k.stop()),await E("transformers.stop",()=>S.stop()),await E("manager.closeAll",()=>y.closeAll()),await E("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await E("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await E("manager.flushMetaWrites",()=>y.flushMetaWrites()),await E("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),dn(null),ln(null),Nn(null),await E("app.close",()=>i.close());try{Ei.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function zc(n){let e=await qc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=Ri.destination(2);return{stream:Ri.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Wc(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{fe as AgentInstance,Se as JsonRpcConnection,ze as Registry,Ae as Session,rt as SessionManager,Qi as defaultConfig,_i as ensureServiceToken,ft as generateServiceToken,os as loadConfig,Ti as loadServiceToken,mn as ndjsonStreamFromStdio,w as paths,ee as planSpawn,Jc as startDaemon,Wi as writeConfig,Un as wsToMessageStream};
|