@hydra-acp/cli 0.1.70 → 0.1.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +294 -294
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- var hg=Object.defineProperty;var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var gg=(t,e)=>{for(var n in e)hg(t,n,{get:e[n],enumerable:!0})};import*as ae from"path";import*as $a from"os";function Be(t){let e=$a.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function ye(){let t=process.env[Ig];if(t&&t.length>0)return ae.resolve(t);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return ae.join($a.homedir(),".hydra-acp")}var Ig,P,ue=V(()=>{"use strict";Ig="HYDRA_ACP_HOME";P={home:ye,config:()=>ae.join(ye(),"config.json"),authToken:()=>ae.join(ye(),"auth-token"),remotes:()=>ae.join(ye(),"remotes.json"),pidFile:()=>ae.join(ye(),"daemon.pid"),logFile:()=>ae.join(ye(),"daemon.log"),currentLogFile:()=>ae.join(ye(),"current.log"),registryCache:()=>ae.join(ye(),"registry.json"),agentsDir:()=>ae.join(ye(),"agents"),agentLogFile:t=>ae.join(ye(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ae.join(ye(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ae.join(ye(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ae.join(ye(),"sessions"),sessionDir:t=>ae.join(ye(),"sessions",t),sessionFile:t=>ae.join(ye(),"sessions",t,"meta.json"),historyFile:t=>ae.join(ye(),"sessions",t,"history.jsonl"),toolsDir:t=>ae.join(ye(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ae.join(ye(),"sessions",t,"tools",e),queueFile:t=>ae.join(ye(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ae.join(ye(),"sessions",".tombstones"),tombstoneAgentDir:t=>ae.join(ye(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ae.join(ye(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ae.join(ye(),"extensions"),extensionLogFile:t=>ae.join(ye(),"extensions",`${t}.log`),extensionPidFile:t=>ae.join(ye(),"extensions",`${t}.pid`),transformersDir:()=>ae.join(ye(),"transformers"),transformerLogFile:t=>ae.join(ye(),"transformers",`${t}.log`),transformerPidFile:t=>ae.join(ye(),"transformers",`${t}.pid`),transformerState:(t,e)=>ae.join(ye(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ae.join(ye(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ae.join(ye(),"prompt-history"),tuiLogFile:()=>ae.join(ye(),"tui.log"),shimWireLogFile:()=>ae.join(ye(),"shim-wire.log")}});import*as Fs from"fs/promises";function Ls(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Bs(){try{let e=(await Fs.readFile(P.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function de(){let t=await Bs();if(!t)throw new Error(`No service token found at ${P.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Ns(t){await Fs.mkdir(P.home(),{recursive:!0}),await Fs.writeFile(P.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function Lr(){let t=await Bs();if(t)return t;let e=Ls();return await Ns(e),process.stderr.write(`hydra-acp: initialized ${P.authToken()} with a fresh service token.
4
- `),e}var ft=V(()=>{"use strict";ue()});import*as Yt from"fs/promises";import*as ul from"fs";import{randomBytes as Sg}from"crypto";async function It(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await kg(t,r,n)}async function kg(t,e,n={}){let s=xg(t);await Yt.mkdir(s,{recursive:!0});let r=`${t}.tmp-${process.pid}-${Ag()}`;try{let i={encoding:"utf8"};n.mode!==void 0&&(i.mode=n.mode),await Yt.writeFile(r,e,i),await Yt.rename(r,t)}catch(i){throw await Yt.unlink(r).catch(()=>{}),i}if(n.mode!==void 0)try{ul.chmodSync(t,n.mode)}catch{}}async function Pt(t){let e;try{e=await Yt.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function xg(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Ag(){return Sg(4).toString("hex")}var ls=V(()=>{"use strict"});import*as pl from"fs/promises";import{homedir as _a}from"os";import{z as L}from"zod";function gl(t){return t.tui.inAppSelection??t.tui.mouse}function yl(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function wl(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Di(){return await Pt(P.config())??{}}async function Hi(){let t=await Di(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await pl.access(P.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${P.authToken()} and ${P.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ns(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await It(P.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${P.config()} to ${P.authToken()}.
6
- `)}async function G(){return await Hi(),hl.parse(await Di())}async function Hs(t){await Hi();let e=await Di();t(e),hl.parse(e),await It(P.config(),e,{mode:384})}async function Br(t,e){await Hs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Ui(t){await Hs(e=>{e.defaultAgent=t})}async function bl(t,e){await Hs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function vl(t,e){await Hs(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function Oa(t,e){await Hs(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function Il(t){await Hs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Sl(){let t=await Di();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Dt(t){return t==="~"||t==="$HOME"?_a():t.startsWith("~/")?_a()+t.slice(1):t.startsWith("$HOME/")?_a()+t.slice(5):t}var ml,Cg,Ds,Rg,Tg,Eg,Pg,Mg,fl,$g,_g,hl,Oe=V(()=>{"use strict";ue();ft();ls();ml="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Cg=L.object({cert:L.string(),key:L.string()}),Ds=55514,Rg=L.object({host:L.string().default("127.0.0.1"),port:L.number().int().positive().default(Ds),logLevel:L.enum(["debug","info","warn","error"]).default("info"),tls:Cg.optional(),sessionIdleTimeoutSeconds:L.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:L.number().int().positive().default(1e4),agentStderrTailBytes:L.number().int().positive().default(4096),publicHost:L.string().optional(),agentSyncIntervalMinutes:L.number().nonnegative().default(60),sessionGcIntervalMinutes:L.number().nonnegative().default(60),sessionGcMaxAgeDays:L.number().positive().default(2)}),Tg=L.object({url:L.string().url().default(ml),ttlHours:L.number().positive().default(24),pinned:L.boolean().default(!1)}),Eg=L.object({name:L.string().optional(),description:L.string().optional(),command:L.string().optional(),args:L.array(L.string()).optional(),env:L.record(L.string()).optional()}),Pg=L.object({packageSpec:L.string().optional()}),Mg=L.object({repaintThrottleMs:L.number().int().nonnegative().default(1e3),maxScrollbackLines:L.number().int().positive().default(1e4),mouse:L.boolean().default(!1),inAppSelection:L.boolean().optional(),selectionClipboard:L.enum(["primary","clipboard","both"]).default("both"),logMaxBytes:L.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:L.number().int().positive().default(32),progressIndicator:L.boolean().default(!0),defaultEnterAction:L.enum(["enqueue","amend"]).default("amend"),showThoughts:L.boolean().default(!0),ambiguousWidth:L.enum(["narrow","wide"]).default("wide"),toolContent:L.enum(["inline","references"]).default("references"),diffContextLines:L.number().int().min(0).default(3),promptHistoryMaxEntries:L.number().int().positive().default(2e3),maxToolItems:L.number().int().nonnegative().default(5),maxPlanItems:L.number().int().nonnegative().default(5),showFileUpdates:L.enum(["none","edit","diff"]).default("edit"),sessionColumns:L.array(L.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),fl=L.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),$g=L.object({command:L.array(L.string()).default([]),args:L.array(L.string()).default([]),env:L.record(L.string()).default({}),enabled:L.boolean().default(!0)}),_g=L.object({command:L.array(L.string()).default([]),args:L.array(L.string()).default([]),env:L.record(L.string()).default({}),enabled:L.boolean().default(!0)}),hl=L.object({daemon:Rg.default({}),registry:Tg.default({url:ml,ttlHours:24,pinned:!1}),agents:L.record(L.string(),Eg).default({}),agentOverrides:L.record(L.string(),Pg).default({}),defaultAgent:L.string().default("opencode"),defaultModels:L.record(L.string(),L.string()).default({}),synopsisAgent:L.string().optional(),synopsisModel:L.string().optional(),synopsisOnClose:L.boolean().default(!1),defaultCwd:L.string().default("~"),compressToolContent:L.boolean().default(!0),sessionListColdLimit:L.number().int().nonnegative().default(20),extensions:L.record(fl,$g).default({}),transformers:L.record(fl,_g).default({}),defaultTransformers:L.array(L.string()).default([]),npmRegistry:L.string().url().optional(),tui:Mg.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 pn(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Fa(t){return pn(t)?{httpScheme:"http",wsScheme:"ws"}:{httpScheme:"https",wsScheme:"wss"}}function La(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${ji(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${ji(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let c=Number(n[1]);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Og(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${ji(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${ji(t)}`);let i=pn(r),o;if(s.port){let c=Number(s.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=c}else o=i?Ds:443;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function kl(t){let n=pn(t.host)?Ds:443,s=t.port!==void 0&&t.port!==n?`:${t.port}`:"",r=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${s}${r}`}function Og(t){try{return new URL(t)}catch{return null}}function ji(t){return t.length>80?`${t.slice(0,77)}...`:t}var Nr=V(()=>{"use strict";Oe()});function Ba(t,e){return`${t}:${e}`}function xl(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Fg(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Lg(){let t=await Pt(P.remotes());return t===void 0?{version:1,entries:{}}:Bg(t)}function Bg(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),s[r]=a}return{version:1,entries:s}}async function Na(t){await It(P.remotes(),t,{mode:384})}var qi,Al=V(()=>{"use strict";ue();ls();qi=class t{data;constructor(e){this.data=e}static async load(){let e=await Lg(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(xl(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Na(i),new t(i)}get(e,n){let s=this.data.entries[Ba(e,n)];if(s&&!xl(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ba(e,n)]=s,await Na(this.data)}async delete(e,n){let s=Ba(e,n);return s in this.data.entries?(delete this.data.entries[s],await Na(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Fg(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Us(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",d),r||s.setRawMode(!1),s.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
7
- `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},d=c=>{o(),n(c)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",d)}):Ng()}function Ng(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
- `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var Da=V(()=>{"use strict"});import*as Cl from"path";function Fn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=Cl.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Wi=V(()=>{"use strict"});import*as Tl from"os";async function Qt(t){let e=await Lr(),n=t.daemon.host,s=t.daemon.port,r=!!t.daemon.tls,i=r?"https":"http",o=r?"wss":"ws";return{baseUrl:`${i}://${n}:${s}`,wsUrl:`${o}://${n}:${s}/acp`,token:e,display:`${n}:${s}`,isLocal:pn(n)}}function Ha(t,e){let{httpScheme:n,wsScheme:s}=Fa(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Pl(t),isLocal:t.isLoopback}}async function El(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Us,r=e.preferServiceToken??!0,i=e.allowPrompt??!0;if(t.isLoopback&&r){let g=await Bs();if(g)return Ha(t,g)}let o=e.store??await qi.load(),a=o.get(t.host,t.port);if(a)return Ha(t,a.token);if(!i)throw new Ua(t.host,t.port);let d=Pl(t),c=await s(`Password for ${d}: `);if(c.length===0)throw new Error("Password is required to attach to a remote daemon.");let{httpScheme:l}=Fa(t.host),f=`${l}://${t.host}:${t.port}`,u=await n(`${f}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:c,label:Rl()})});if(u.status===401)throw new Error(`Wrong password for ${d}.`);if(u.status===403)throw new Error(`No password is configured on ${d}. Run \`hydra-acp auth password\` on the daemon host first.`);if(u.status===429)throw new Error(`Too many failed login attempts on ${d}; try again later.`);if(!u.ok)throw new Error(`Login to ${d} failed: HTTP ${u.status}`);let p=await u.json();if(!p.session_token||!p.expires_at)throw new Error(`Login to ${d} returned a malformed response.`);return await o.set(t.host,t.port,{token:p.session_token,expiresAt:p.expires_at,label:Rl()}),Ha(t,p.session_token)}function Rl(){try{let t=Tl.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Pl(t){let e=t.isLoopback?Ds:443;return t.port===e?t.host:`${t.host}:${t.port}`}var Ua,js=V(()=>{"use strict";Oe();ft();Nr();Al();Da();Wi();Nr();Ua=class extends Error{host;port;constructor(e,n){let s=n===443?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Fn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{z as A}from"zod";function kt(t){if(!t)return{};let e=t[pt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=uy.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=iu.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.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(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.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(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.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(n.availableModes)){let r=[];for(let i of n.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(n.availableModels)){let r=[];for(let i of n.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((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}return n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),s}function Qi(t,e){return{...t??{},[pt]:e}}function Gi(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue)),n}function ou(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Qi(t._meta,Gi(t))};return t.title!==void 0&&(e.title=t.title),e}var tt,N,eu,ly,tu,uy,nu,pt,su,ru,iu,_A,fy,OA,au,Xi,du,FA,LA,BA,cu,NA,lu,DA,uu,HA,UA,fu,Zi,nt=V(()=>{"use strict";tt=1,N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014},eu=A.object({protocolVersion:A.number().optional(),clientCapabilities:A.record(A.unknown()).optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional()}),ly=A.enum(["full","pending_only","none","after_message"]),tu=A.object({cwd:A.string(),mcpServers:A.array(A.unknown()).optional(),_meta:A.record(A.unknown()).optional()}),uy=A.object({upstreamSessionId:A.string(),agentId:A.string(),cwd:A.string(),title:A.string().optional(),agentArgs:A.array(A.string()).optional()}),nu=A.object({sessionId:A.string(),historyPolicy:ly.default("full"),afterMessageId:A.string().optional(),clientId:A.string().optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional(),_meta:A.record(A.unknown()).optional()}),pt="hydra-acp";su=A.object({sessionId:A.string()}),ru=A.object({cwd:A.string().optional(),cursor:A.string().optional()}),iu=A.object({used:A.number().optional(),size:A.number().optional(),costAmount:A.number().optional(),costCurrency:A.string().optional()}),_A=A.object({sessionId:A.string(),upstreamSessionId:A.string().optional(),cwd:A.string(),title:A.string().optional(),agentId:A.string().optional(),currentModel:A.string().optional(),currentUsage:iu.optional(),importedFromMachine:A.string().optional(),importedFromUpstreamSessionId:A.string().optional(),parentSessionId:A.string().optional(),forkedFromSessionId:A.string().optional(),forkedFromMessageId:A.string().optional(),originatingClient:A.object({name:A.string(),version:A.string().optional()}).optional(),interactive:A.boolean().optional(),priority:A.number().int().nonnegative().optional(),updatedAt:A.string(),attachedClients:A.number().int().nonnegative(),status:A.enum(["live","cold"]).default("live"),busy:A.boolean().default(!1),awaitingInput:A.boolean().default(!1),_meta:A.record(A.unknown()).optional()}),fy=A.object({sessionId:A.string(),cwd:A.string(),title:A.string().optional(),updatedAt:A.string().optional(),_meta:A.record(A.unknown()).optional()}),OA=A.object({sessions:A.array(fy),nextCursor:A.string().optional()});au=A.object({sessionId:A.string(),prompt:A.array(A.unknown()),_meta:A.record(A.unknown()).optional()}),Xi=A.object({sessionId:A.string()}),du=A.object({clientId:A.string(),name:A.string().optional(),version:A.string().optional()}),FA=A.object({sessionId:A.string(),messageId:A.string(),originator:du,prompt:A.array(A.unknown()),position:A.number().int().nonnegative(),queueDepth:A.number().int().positive(),enqueuedAt:A.number()}),LA=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),BA=A.object({sessionId:A.string(),messageId:A.string(),reason:A.enum(["started","cancelled","abandoned"])}),cu=A.object({sessionId:A.string(),messageId:A.string()}),NA=A.object({cancelled:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),lu=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),DA=A.object({updated:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),uu=A.object({sessionId:A.string(),targetMessageId:A.string(),prompt:A.array(A.unknown()),replaceQueue:A.boolean().optional(),onTargetCompleted:A.enum(["reject","send_anyway"]).optional()}),HA=A.object({amended:A.boolean(),reason:A.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:A.string().optional()}),UA=A.object({sessionId:A.string(),cancelledMessageId:A.string(),newMessageId:A.string(),prompt:A.array(A.unknown()),originator:du,amendedAt:A.number()}),fu=A.object({agentId:A.string(),version:A.string(),source:A.enum(["binary","npm"]),phase:A.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:A.number().optional(),totalBytes:A.number().optional(),packageSpec:A.string().optional()}),Zi="hydra-acp/agents/install_progress"});import{nanoid as py}from"nanoid";var Mt,Ks=V(()=>{"use strict";nt();Mt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(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)}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)return{id:"",response:Promise.reject(new Error("connection is closed"))};let s=py(),r={jsonrpc:"2.0",id:s,method:e,params:n},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,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};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 n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:N.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(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??N.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);s||(s=[],this.bufferedNotifications.set(e.method,s)),s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=this.pending.get(e.id);if(!n){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,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});import*as hu from"fs/promises";function Ay(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var wy,by,Vs,vy,Iy,Sy,ky,xy,mu,no,gu=V(()=>{"use strict";wy=64*1024*1024,by=1*1024*1024,Vs=64*1024,vy=6e4,Iy=100,Sy=1e3,ky=64*1024,xy=256*1024,mu=20;no=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??wy,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(by,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,n){let s=Math.max(0,Math.min(n,Vs));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Vs)),s=this.oldestAvailable,r=this.writeCursor-n,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 n=Math.max(0,Math.min(e,Vs)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,vy));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 n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),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(Ay(e.pattern),d),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Iy,Sy)),u=Math.max(1,Math.min(e.maxBytes??ky,xy)),p=Math.max(0,Math.min(e.contextBefore??0,mu)),g=Math.max(0,Math.min(e.contextAfter??0,mu)),h=[],y=[],v=[],b=0,x=!1,C=0,F=0,z=(D,$)=>{for(let he of v)he.remaining>0&&(he.match.after===void 0&&(he.match.after=[]),he.match.after.push({cursor:D,line:$}),he.remaining--,b+=$.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(c.test($)!==l&&h.length<f){let he={cursor:D,line:$};if(p>0&&y.length>0){he.before=y.slice();for(let ke of he.before)b+=ke.line.length}b+=$.length,h.push(he),g>0&&v.push({match:he,remaining:g})}if(p>0)for(y.push({cursor:D,line:$});y.length>p;)y.shift();let K=h.length>=f&&v.length===0,ee=b>=u;return K||ee};for(let D=0;D<o.length;D++){if(o[D]!==10)continue;let $=o.subarray(C,D).toString("utf8"),W=r+C;if(C=D+1,F=C,z(W,$)){x=!0;break}}if(!x&&C<o.length&&this.closed){let D=o.subarray(C).toString("utf8"),$=r+C;z($,D)&&(x=!0),F=o.length}let J=Math.min(r+F,this.writeCursor),X={matches:h,truncated:x,nextCursor:J,scannedBytes:F};return i>0&&(X.gap=i),this.closed&&J>=this.writeCursor&&(X.eof=!0),X}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&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 n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===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(()=>hu.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var so,eC,yu=V(()=>{"use strict";so=[{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."}],eC=new Map(so.map(t=>[t.verb,t]))});function wu(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Ys(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.some(r=>r.modelId===t))return{kind:"exact",modelId:t};let n=wu(t),s=e.map(r=>r.modelId).filter(r=>wu(r)===n);return s.length===1?{kind:"resolved",modelId:s[0],requested:t}:s.length>1?{kind:"ambiguous",requested:t,candidates:s}:{kind:"unknown",requested:t}}var ro=V(()=>{"use strict"});function bu(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=ed(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let f=n.get(l);f?f.push(...c.content):n.set(l,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=ed(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Ry(r,i.outIndex,Cy(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?Ty(d,n.get(f)??[]):d;f!==void 0&&s.has(f)&&!Ey(u)&&(u=Py(u,s.get(f))),r.push(u);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function ed(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Cy(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Ry(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function Ty(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function Ey(t){let n=ed(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Py(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var vu=V(()=>{"use strict"});import*as Zt from"fs/promises";async function Dr(t,e){let n=P.queueFile(t);if(e.length===0){await Zt.unlink(n).catch(()=>{});return}await Zt.mkdir(P.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
2
+ var gg=Object.defineProperty;var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var yg=(t,e)=>{for(var n in e)gg(t,n,{get:e[n],enumerable:!0})};import*as ue from"path";import*as Fa from"os";function Ne(t){let e=Fa.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function ye(){let t=process.env[Sg];if(t&&t.length>0)return ue.resolve(t);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return ue.join(Fa.homedir(),".hydra-acp")}var Sg,E,me=V(()=>{"use strict";Sg="HYDRA_ACP_HOME";E={home:ye,config:()=>ue.join(ye(),"config.json"),authToken:()=>ue.join(ye(),"auth-token"),remotes:()=>ue.join(ye(),"remotes.json"),pidFile:()=>ue.join(ye(),"daemon.pid"),logFile:()=>ue.join(ye(),"daemon.log"),currentLogFile:()=>ue.join(ye(),"current.log"),registryCache:()=>ue.join(ye(),"registry.json"),agentsDir:()=>ue.join(ye(),"agents"),agentLogFile:t=>ue.join(ye(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ue.join(ye(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ue.join(ye(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ue.join(ye(),"sessions"),sessionDir:t=>ue.join(ye(),"sessions",t),sessionFile:t=>ue.join(ye(),"sessions",t,"meta.json"),historyFile:t=>ue.join(ye(),"sessions",t,"history.jsonl"),toolsDir:t=>ue.join(ye(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ue.join(ye(),"sessions",t,"tools",e),queueFile:t=>ue.join(ye(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ue.join(ye(),"sessions",".tombstones"),tombstoneAgentDir:t=>ue.join(ye(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ue.join(ye(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ue.join(ye(),"extensions"),extensionLogFile:t=>ue.join(ye(),"extensions",`${t}.log`),extensionPidFile:t=>ue.join(ye(),"extensions",`${t}.pid`),transformersDir:()=>ue.join(ye(),"transformers"),transformerLogFile:t=>ue.join(ye(),"transformers",`${t}.log`),transformerPidFile:t=>ue.join(ye(),"transformers",`${t}.pid`),transformerState:(t,e)=>ue.join(ye(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ue.join(ye(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ue.join(ye(),"prompt-history"),tuiLogFile:()=>ue.join(ye(),"tui.log"),shimWireLogFile:()=>ue.join(ye(),"shim-wire.log")}});import*as Hs from"fs/promises";function Us(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function js(){try{let e=(await Hs.readFile(E.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function fe(){let t=await js();if(!t)throw new Error(`No service token found at ${E.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function qs(t){await Hs.mkdir(E.home(),{recursive:!0}),await Hs.writeFile(E.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function jr(){let t=await js();if(t)return t;let e=Us();return await qs(e),process.stderr.write(`hydra-acp: initialized ${E.authToken()} with a fresh service token.
4
+ `),e}var mt=V(()=>{"use strict";me()});import*as Gt from"fs/promises";import*as ml from"fs";import{randomBytes as kg}from"crypto";async function St(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await xg(t,r,n)}async function xg(t,e,n={}){let s=Ag(t);await Gt.mkdir(s,{recursive:!0});let r=`${t}.tmp-${process.pid}-${Cg()}`;try{let i={encoding:"utf8"};n.mode!==void 0&&(i.mode=n.mode),await Gt.writeFile(r,e,i),await Gt.rename(r,t)}catch(i){throw await Gt.unlink(r).catch(()=>{}),i}if(n.mode!==void 0)try{ml.chmodSync(t,n.mode)}catch{}}async function Et(t){let e;try{e=await Gt.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Ag(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Cg(){return kg(4).toString("hex")}var ms=V(()=>{"use strict"});import*as gl from"fs/promises";import{homedir as La}from"os";import{z as B}from"zod";function bl(t){return t.tui.inAppSelection??t.tui.mouse}function vl(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Il(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function ji(){return await Et(E.config())??{}}async function qi(){let t=await ji(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await gl.access(E.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${E.authToken()} and ${E.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await qs(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await St(E.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${E.config()} to ${E.authToken()}.
6
+ `)}async function G(){return await qi(),wl.parse(await ji())}async function zs(t){await qi();let e=await ji();t(e),wl.parse(e),await St(E.config(),e,{mode:384})}async function qr(t,e){await zs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Wi(t){await zs(e=>{e.defaultAgent=t})}async function Sl(t,e){await zs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function kl(t,e){await zs(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function Ba(t,e){await zs(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function xl(t){await zs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Al(){let t=await ji();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Ut(t){return t==="~"||t==="$HOME"?La():t.startsWith("~/")?La()+t.slice(1):t.startsWith("$HOME/")?La()+t.slice(5):t}var yl,Rg,Ws,Tg,Eg,Pg,Mg,$g,hl,_g,Og,wl,Oe=V(()=>{"use strict";me();mt();ms();yl="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Rg=B.object({cert:B.string(),key:B.string()}),Ws=55514,Tg=B.object({host:B.string().default("127.0.0.1"),port:B.number().int().positive().default(Ws),logLevel:B.enum(["debug","info","warn","error"]).default("info"),tls:Rg.optional(),sessionIdleTimeoutSeconds:B.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:B.number().int().positive().default(1e4),agentStderrTailBytes:B.number().int().positive().default(4096),publicHost:B.string().optional(),agentSyncIntervalMinutes:B.number().nonnegative().default(60),sessionGcIntervalMinutes:B.number().nonnegative().default(60),sessionGcMaxAgeDays:B.number().positive().default(2)}),Eg=B.object({url:B.string().url().default(yl),ttlHours:B.number().positive().default(24),pinned:B.boolean().default(!1)}),Pg=B.object({name:B.string().optional(),description:B.string().optional(),command:B.string().optional(),args:B.array(B.string()).optional(),env:B.record(B.string()).optional()}),Mg=B.object({packageSpec:B.string().optional()}),$g=B.object({repaintThrottleMs:B.number().int().nonnegative().default(1e3),maxScrollbackLines:B.number().int().positive().default(1e4),mouse:B.boolean().default(!1),inAppSelection:B.boolean().optional(),selectionClipboard:B.enum(["primary","clipboard","both"]).default("both"),logMaxBytes:B.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:B.number().int().positive().default(32),progressIndicator:B.boolean().default(!0),defaultEnterAction:B.enum(["enqueue","amend"]).default("amend"),showThoughts:B.boolean().default(!0),ambiguousWidth:B.enum(["narrow","wide"]).default("wide"),toolContent:B.enum(["inline","references"]).default("references"),diffContextLines:B.number().int().min(0).default(3),promptHistoryMaxEntries:B.number().int().positive().default(2e3),maxToolItems:B.number().int().nonnegative().default(5),maxPlanItems:B.number().int().nonnegative().default(5),showFileUpdates:B.enum(["none","edit","diff"]).default("edit"),sessionColumns:B.array(B.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),hl=B.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),_g=B.object({command:B.array(B.string()).default([]),args:B.array(B.string()).default([]),env:B.record(B.string()).default({}),enabled:B.boolean().default(!0)}),Og=B.object({command:B.array(B.string()).default([]),args:B.array(B.string()).default([]),env:B.record(B.string()).default({}),enabled:B.boolean().default(!0)}),wl=B.object({daemon:Tg.default({}),registry:Eg.default({url:yl,ttlHours:24,pinned:!1}),agents:B.record(B.string(),Pg).default({}),agentOverrides:B.record(B.string(),Mg).default({}),defaultAgent:B.string().default("opencode"),defaultModels:B.record(B.string(),B.string()).default({}),synopsisAgent:B.string().optional(),synopsisModel:B.string().optional(),synopsisOnClose:B.boolean().default(!1),defaultCwd:B.string().default("~"),compressToolContent:B.boolean().default(!0),sessionListColdLimit:B.number().int().nonnegative().default(20),extensions:B.record(hl,_g).default({}),transformers:B.record(hl,Og).default({}),defaultTransformers:B.array(B.string()).default([]),npmRegistry:B.string().url().optional(),tui:$g.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 gn(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Na(t){return gn(t)?{httpScheme:"http",wsScheme:"ws"}:{httpScheme:"https",wsScheme:"wss"}}function Da(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${zi(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${zi(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let c=Number(n[1]);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Fg(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${zi(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${zi(t)}`);let i=gn(r),o;if(s.port){let c=Number(s.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=c}else o=i?Ws:443;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function Cl(t){let n=gn(t.host)?Ws:443,s=t.port!==void 0&&t.port!==n?`:${t.port}`:"",r=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${s}${r}`}function Fg(t){try{return new URL(t)}catch{return null}}function zi(t){return t.length>80?`${t.slice(0,77)}...`:t}var Wr=V(()=>{"use strict";Oe()});function Ha(t,e){return`${t}:${e}`}function Rl(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Lg(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Bg(){let t=await Et(E.remotes());return t===void 0?{version:1,entries:{}}:Ng(t)}function Ng(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),s[r]=a}return{version:1,entries:s}}async function Ua(t){await St(E.remotes(),t,{mode:384})}var Ji,Tl=V(()=>{"use strict";me();ms();Ji=class t{data;constructor(e){this.data=e}static async load(){let e=await Bg(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Rl(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Ua(i),new t(i)}get(e,n){let s=this.data.entries[Ha(e,n)];if(s&&!Rl(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ha(e,n)]=s,await Ua(this.data)}async delete(e,n){let s=Ha(e,n);return s in this.data.entries?(delete this.data.entries[s],await Ua(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Lg(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Js(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",d),r||s.setRawMode(!1),s.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
7
+ `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},d=c=>{o(),n(c)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",d)}):Dg()}function Dg(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var ja=V(()=>{"use strict"});import*as El from"path";function Dn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=El.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Ki=V(()=>{"use strict"});import*as Ml from"os";async function Xt(t){let e=await jr(),n=t.daemon.host,s=t.daemon.port,r=!!t.daemon.tls,i=r?"https":"http",o=r?"wss":"ws";return{baseUrl:`${i}://${n}:${s}`,wsUrl:`${o}://${n}:${s}/acp`,token:e,display:`${n}:${s}`,isLocal:gn(n)}}function qa(t,e){let{httpScheme:n,wsScheme:s}=Na(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:_l(t),isLocal:t.isLoopback}}async function $l(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Js,r=e.preferServiceToken??!0,i=e.allowPrompt??!0;if(t.isLoopback&&r){let g=await js();if(g)return qa(t,g)}let o=e.store??await Ji.load(),a=o.get(t.host,t.port);if(a)return qa(t,a.token);if(!i)throw new Wa(t.host,t.port);let d=_l(t),c=await s(`Password for ${d}: `);if(c.length===0)throw new Error("Password is required to attach to a remote daemon.");let{httpScheme:l}=Na(t.host),u=`${l}://${t.host}:${t.port}`,f=await n(`${u}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:c,label:Pl()})});if(f.status===401)throw new Error(`Wrong password for ${d}.`);if(f.status===403)throw new Error(`No password is configured on ${d}. Run \`hydra-acp auth password\` on the daemon host first.`);if(f.status===429)throw new Error(`Too many failed login attempts on ${d}; try again later.`);if(!f.ok)throw new Error(`Login to ${d} failed: HTTP ${f.status}`);let p=await f.json();if(!p.session_token||!p.expires_at)throw new Error(`Login to ${d} returned a malformed response.`);return await o.set(t.host,t.port,{token:p.session_token,expiresAt:p.expires_at,label:Pl()}),qa(t,p.session_token)}function Pl(){try{let t=Ml.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function _l(t){let e=t.isLoopback?Ws:443;return t.port===e?t.host:`${t.host}:${t.port}`}var Wa,Ks=V(()=>{"use strict";Oe();mt();Wr();Tl();ja();Ki();Wr();Wa=class extends Error{host;port;constructor(e,n){let s=n===443?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Dn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{z as A}from"zod";function xt(t){if(!t)return{};let e=t[ht];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=fy.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=du.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.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(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.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(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.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(n.availableModes)){let r=[];for(let i of n.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(n.availableModels)){let r=[];for(let i of n.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((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}return n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),s}function Zi(t,e){return{...t??{},[ht]:e}}function eo(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue)),n}function cu(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Zi(t._meta,eo(t))};return t.title!==void 0&&(e.title=t.title),e}var nt,N,su,uy,ru,fy,iu,ht,ou,au,du,OA,py,FA,lu,to,uu,LA,BA,NA,fu,DA,pu,HA,mu,UA,jA,hu,no,st=V(()=>{"use strict";nt=1,N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014},su=A.object({protocolVersion:A.number().optional(),clientCapabilities:A.record(A.unknown()).optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional()}),uy=A.enum(["full","pending_only","none","after_message"]),ru=A.object({cwd:A.string(),mcpServers:A.array(A.unknown()).optional(),_meta:A.record(A.unknown()).optional()}),fy=A.object({upstreamSessionId:A.string(),agentId:A.string(),cwd:A.string(),title:A.string().optional(),agentArgs:A.array(A.string()).optional()}),iu=A.object({sessionId:A.string(),historyPolicy:uy.default("full"),afterMessageId:A.string().optional(),clientId:A.string().optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional(),_meta:A.record(A.unknown()).optional()}),ht="hydra-acp";ou=A.object({sessionId:A.string()}),au=A.object({cwd:A.string().optional(),cursor:A.string().optional()}),du=A.object({used:A.number().optional(),size:A.number().optional(),costAmount:A.number().optional(),costCurrency:A.string().optional()}),OA=A.object({sessionId:A.string(),upstreamSessionId:A.string().optional(),cwd:A.string(),title:A.string().optional(),agentId:A.string().optional(),currentModel:A.string().optional(),currentUsage:du.optional(),importedFromMachine:A.string().optional(),importedFromUpstreamSessionId:A.string().optional(),parentSessionId:A.string().optional(),forkedFromSessionId:A.string().optional(),forkedFromMessageId:A.string().optional(),originatingClient:A.object({name:A.string(),version:A.string().optional()}).optional(),interactive:A.boolean().optional(),priority:A.number().int().nonnegative().optional(),updatedAt:A.string(),attachedClients:A.number().int().nonnegative(),status:A.enum(["live","cold"]).default("live"),busy:A.boolean().default(!1),awaitingInput:A.boolean().default(!1),_meta:A.record(A.unknown()).optional()}),py=A.object({sessionId:A.string(),cwd:A.string(),title:A.string().optional(),updatedAt:A.string().optional(),_meta:A.record(A.unknown()).optional()}),FA=A.object({sessions:A.array(py),nextCursor:A.string().optional()});lu=A.object({sessionId:A.string(),prompt:A.array(A.unknown()),_meta:A.record(A.unknown()).optional()}),to=A.object({sessionId:A.string()}),uu=A.object({clientId:A.string(),name:A.string().optional(),version:A.string().optional()}),LA=A.object({sessionId:A.string(),messageId:A.string(),originator:uu,prompt:A.array(A.unknown()),position:A.number().int().nonnegative(),queueDepth:A.number().int().positive(),enqueuedAt:A.number()}),BA=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),NA=A.object({sessionId:A.string(),messageId:A.string(),reason:A.enum(["started","cancelled","abandoned"])}),fu=A.object({sessionId:A.string(),messageId:A.string()}),DA=A.object({cancelled:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),pu=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),HA=A.object({updated:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),mu=A.object({sessionId:A.string(),targetMessageId:A.string(),prompt:A.array(A.unknown()),replaceQueue:A.boolean().optional(),onTargetCompleted:A.enum(["reject","send_anyway"]).optional()}),UA=A.object({amended:A.boolean(),reason:A.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:A.string().optional()}),jA=A.object({sessionId:A.string(),cancelledMessageId:A.string(),newMessageId:A.string(),prompt:A.array(A.unknown()),originator:uu,amendedAt:A.number()}),hu=A.object({agentId:A.string(),version:A.string(),source:A.enum(["binary","npm"]),phase:A.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:A.number().optional(),totalBytes:A.number().optional(),packageSpec:A.string().optional()}),no="hydra-acp/agents/install_progress"});import{nanoid as my}from"nanoid";var Pt,Xs=V(()=>{"use strict";st();Pt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(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)}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)return{id:"",response:Promise.reject(new Error("connection is closed"))};let s=my(),r={jsonrpc:"2.0",id:s,method:e,params:n},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,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};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 n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:N.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(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??N.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);s||(s=[],this.bufferedNotifications.set(e.method,s)),s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=this.pending.get(e.id);if(!n){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,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});import*as wu from"fs/promises";function Cy(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var by,vy,Zs,Iy,Sy,ky,xy,Ay,yu,io,bu=V(()=>{"use strict";by=64*1024*1024,vy=1*1024*1024,Zs=64*1024,Iy=6e4,Sy=100,ky=1e3,xy=64*1024,Ay=256*1024,yu=20;io=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??by,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(vy,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,n){let s=Math.max(0,Math.min(n,Zs));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Zs)),s=this.oldestAvailable,r=this.writeCursor-n,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 n=Math.max(0,Math.min(e,Zs)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,Iy));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 n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),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(Cy(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Sy,ky)),f=Math.max(1,Math.min(e.maxBytes??xy,Ay)),p=Math.max(0,Math.min(e.contextBefore??0,yu)),g=Math.max(0,Math.min(e.contextAfter??0,yu)),h=[],y=[],I=[],b=0,x=!1,M=0,_=0,Q=($,D)=>{for(let se of I)se.remaining>0&&(se.match.after===void 0&&(se.match.after=[]),se.match.after.push({cursor:$,line:D}),se.remaining--,b+=D.length);for(;I.length>0&&I[0].remaining===0;)I.shift();if(c.test(D)!==l&&h.length<u){let se={cursor:$,line:D};if(p>0&&y.length>0){se.before=y.slice();for(let Ee of se.before)b+=Ee.line.length}b+=D.length,h.push(se),g>0&&I.push({match:se,remaining:g})}if(p>0)for(y.push({cursor:$,line:D});y.length>p;)y.shift();let Z=h.length>=u&&I.length===0,ie=b>=f;return Z||ie};for(let $=0;$<o.length;$++){if(o[$]!==10)continue;let D=o.subarray(M,$).toString("utf8"),j=r+M;if(M=$+1,_=M,Q(j,D)){x=!0;break}}if(!x&&M<o.length&&this.closed){let $=o.subarray(M).toString("utf8"),D=r+M;Q(D,$)&&(x=!0),_=o.length}let W=Math.min(r+_,this.writeCursor),z={matches:h,truncated:x,nextCursor:W,scannedBytes:_};return i>0&&(z.gap=i),this.closed&&W>=this.writeCursor&&(z.eof=!0),z}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&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 n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===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(()=>wu.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var oo,tC,vu=V(()=>{"use strict";oo=[{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."}],tC=new Map(oo.map(t=>[t.verb,t]))});function Iu(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function er(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.some(r=>r.modelId===t))return{kind:"exact",modelId:t};let n=Iu(t),s=e.map(r=>r.modelId).filter(r=>Iu(r)===n);return s.length===1?{kind:"resolved",modelId:s[0],requested:t}:s.length>1?{kind:"ambiguous",requested:t,candidates:s}:{kind:"unknown",requested:t}}var ao=V(()=>{"use strict"});function Su(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=sd(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=n.get(l);u?u.push(...c.content):n.set(l,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=sd(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Ty(r,i.outIndex,Ry(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?Ey(d,n.get(u)??[]):d;u!==void 0&&s.has(u)&&!Py(f)&&(f=My(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function sd(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Ry(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Ty(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function Ey(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function Py(t){let n=sd(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function My(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var ku=V(()=>{"use strict"});import*as tn from"fs/promises";async function zr(t,e){let n=E.queueFile(t);if(e.length===0){await tn.unlink(n).catch(()=>{});return}await tn.mkdir(E.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
9
9
  `)+`
10
- `;await Zt.writeFile(n,s,"utf8")}async function Iu(t){let e=P.queueFile(t),n;try{n=await Zt.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
11
- `))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 Su(t){let e=P.queueFile(t);await Zt.unlink(e).catch(()=>{})}var td=V(()=>{"use strict";ue()});import{customAlphabet as Au}from"nanoid";import*as Tu from"fs/promises";function Qs(){return`m_${Ru()}`}function je(t){return t.startsWith(mn)?t.slice(mn.length):t}function xt(t,e){return t.code=e,t}function Oy(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&_y.has(s)}function Fy(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Ly(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function By(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Dn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,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 fs(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,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 Ny(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.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 Dy(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function Hy(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.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 Uy(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Qs()}}}function rd(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function jy(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function qy(t){let e=Wy(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=zy(t.resolver),n}function Wy(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function zy(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function Gs(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function sd(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function xu(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
10
+ `;await tn.writeFile(n,s,"utf8")}async function xu(t){let e=E.queueFile(t),n;try{n=await tn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
11
+ `))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 Au(t){let e=E.queueFile(t);await tn.unlink(e).catch(()=>{})}var rd=V(()=>{"use strict";me()});import{customAlphabet as Tu}from"nanoid";import*as Mu from"fs/promises";function tr(){return`m_${Pu()}`}function qe(t){return t.startsWith(yn)?t.slice(yn.length):t}function At(t,e){return t.code=e,t}function Fy(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Oy.has(s)}function Ly(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function By(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Ny(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function qn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,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 gs(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,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 Dy(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.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 Hy(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function Uy(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.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 jy(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:tr()}}}function ad(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function qy(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function Wy(t){let e=zy(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=Jy(t.resolver),n}function zy(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function Jy(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function nr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function od(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Ru(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
12
12
  ${s.join(`
13
- `)}`}function id(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Cu,Ru,ku,mn,My,nd,$y,Xs,_y,en=V(()=>{"use strict";gu();yu();ro();vu();td();nt();Cu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ru=Au(Cu,16),ku=Au(Cu,16),mn="hydra_session_";My=1e3,nd=300*1e3,$y=64,Xs=class t{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??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${mn}${Ru()}`,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??My,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",n=>{if(this.internalPromptCapture){Dy(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.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,n=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(n.has(c.name)||!c.intercepts.has("response:session/update"))continue;let l=`t_${ku()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=d,g=i,h=new Set(n);await new Promise(y=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...h,c.name]),p+1).then(y))},nd);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:()=>y(),timer:v,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(c.name)}let o=Hy(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Ny(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 n=[];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),n.push(r)}return n}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 n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}attach(e,n,s={}){if(this.closed)throw xt(new Error("session is closed"),N.SessionNotFound);if(this.clients.has(e.clientId))throw xt(new Error(`client ${e.clientId} is already attached`),N.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=o=>n.raw?o:bu(o),r=await this.getHistorySnapshot(n.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=n.afterMessageId?rd(r,n.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=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let n of this.inFlightPermissions)n.addClient(e)}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,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,n){let s=this.clients.get(e);if(!s)throw xt(new Error("client not attached"),N.SessionNotFound);if(this.closing)throw xt(new Error("session is closing; new prompts cannot be accepted"),N.SessionClosing);let r=Qs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(kt((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.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:n}},e.clientId);let s=Gs(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,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Qs()};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,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>$y;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.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 n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.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};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,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:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.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 n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,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,n){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=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw xt(new Error("client not attached"),N.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=Qs(),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:n,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,n){let s=Qs(),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:n,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 xt(new Error("client not attached"),N.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 n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=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,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${ku()}`,f;try{f=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??sd(e);if(u==="processing"){let p=a,g=o,h=new Set(s);return new Promise(y=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.forwardRequest(e,g,new Set([...h,d.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:sd(e))))},nd);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:y,timer:v,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:h,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,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):nd,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));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:sd(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,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(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){this.closeHandlers.push(e)}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Gs((e??{}).prompt),r=id(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=Dn(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=Dn(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=fs(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=Dn(o.options);if(d.length>0){let c=fs(o.options),l=c.length>0?c.map(y=>({value:y.id,name:y.name??y.id})):d.map(y=>({value:y.modelId,name:y.name??y.modelId})),f=o.name,u=typeof f=="string"&&f.trim()?f.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(h>=0){let y={...this.agentAdvertisedConfigOptions[h]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:g,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let n={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=n;for(let s of this.usageHandlers)try{s(n)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Fy(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Ly(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),By(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(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 n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(!n)return;if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let n=e.trim();if(!n)return;if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};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 n=e;if(!n.update||typeof n.update!="object")return e;let s=n.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?{...n,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:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){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=n!==void 0;if(so.some(f=>f.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=N.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,n):this.runExtensionCommand(d,o);let c=so.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(c.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=N.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.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(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let f,u=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),h=await Promise.race([g,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=h}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let p=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){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:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
13
+ `)}`}function dd(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Eu,Pu,Cu,yn,$y,id,_y,sr,Oy,nn=V(()=>{"use strict";bu();vu();ao();ku();rd();st();Eu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Pu=Tu(Eu,16),Cu=Tu(Eu,16),yn="hydra_session_";$y=1e3,id=300*1e3,_y=64,sr=class t{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??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${yn}${Pu()}`,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??$y,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",n=>{if(this.internalPromptCapture){Hy(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.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,n=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(n.has(c.name)||!c.intercepts.has("response:session/update"))continue;let l=`t_${Cu()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return;if(f==="processing"){let p=d,g=i,h=new Set(n);await new Promise(y=>{let I=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...h,c.name]),p+1).then(y))},id);typeof I.unref=="function"&&I.unref(),this.pendingClaims.set(l,{resolve:()=>y(),timer:I,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(c.name)}let o=Uy(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Dy(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 n=[];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),n.push(r)}return n}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 n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}attach(e,n,s={}){if(this.closed)throw At(new Error("session is closed"),N.SessionNotFound);if(this.clients.has(e.clientId))throw At(new Error(`client ${e.clientId} is already attached`),N.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=o=>n.raw?o:Su(o),r=await this.getHistorySnapshot(n.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=n.afterMessageId?ad(r,n.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=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,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:n,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let n of this.inFlightPermissions)n.addClient(e)}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,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,n){let s=this.clients.get(e);if(!s)throw At(new Error("client not attached"),N.SessionNotFound);if(this.closing)throw At(new Error("session is closing; new prompts cannot be accepted"),N.SessionClosing);let r=tr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(xt((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.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:n}},e.clientId);let s=nr(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,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:tr()};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,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>_y;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.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 n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.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};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,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:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.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 n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,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,n){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=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw At(new Error("client not attached"),N.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=tr(),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:n,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,n){let s=tr(),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:n,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 At(new Error("client not attached"),N.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 n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=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,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${Cu()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??od(e);if(f==="processing"){let p=a,g=o,h=new Set(s);return new Promise(y=>{let I=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.forwardRequest(e,g,new Set([...h,d.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:od(e))))},id);typeof I.unref=="function"&&I.unref(),this.pendingClaims.set(l,{resolve:y,timer:I,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:h,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,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):id,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));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:od(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,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(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){this.closeHandlers.push(e)}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=nr((e??{}).prompt),r=dd(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=qn(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=qn(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=gs(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=qn(o.options);if(d.length>0){let c=gs(o.options),l=c.length>0?c.map(y=>({value:y.id,name:y.name??y.id})):d.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(h>=0){let y={...this.agentAdvertisedConfigOptions[h]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:g,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let n={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=n;for(let s of this.usageHandlers)try{s(n)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Ly(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(By(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),Ny(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(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 n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(!n)return;if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let n=e.trim();if(!n)return;if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};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 n=e;if(!n.update||typeof n.update!="object")return e;let s=n.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?{...n,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:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){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=n!==void 0;if(oo.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=N.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,n):this.runExtensionCommand(d,o);let c=oo.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(c.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=N.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.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(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let u,f=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),h=await Promise.race([g,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=h}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){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:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
14
14
  ${e}
15
15
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let n=await this.listSessions();if(n.length===0)e="_(no sessions)_";else{let s=n.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 (${n.length}):
16
16
  ${s.join(`
@@ -20,20 +20,20 @@ ${e}
20
20
  ${n.join(`
21
21
  `)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
22
22
  ${s}
23
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let n=e.slice(6).trim();if(n===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let d=o?i.some(l=>l.modelId===o):!0,c=i.map(l=>{let f=l.modelId===o?"\u25B6 ":" ",u=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${f}${l.modelId}${u}`});!d&&o&&c.unshift(`\u25B6 ${o}`),a=c.join(`
23
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let n=e.slice(6).trim();if(n===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let d=o?i.some(l=>l.modelId===o):!0,c=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!d&&o&&c.unshift(`\u25B6 ${o}`),a=c.join(`
24
24
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
25
25
  ${a}
26
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Ys(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(a=>a.modelId).join(`
26
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=er(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(a=>a.modelId).join(`
27
27
  `),o=s.kind==="ambiguous"?`"${n}" matches multiple models: ${s.candidates.join(", ")}`:`"${n}" is not an available model`;return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
28
28
  ${o}.
29
29
  Available models:
30
30
  ${i}
31
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let l=c.id===i?"\u25B6 ":" ",f=c.name&&c.name!==c.id?` ${c.name}`:"";return`${l}${c.id}${f}`});!a&&i&&d.unshift(`\u25B6 ${i}`),o=d.join(`
31
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let l=c.id===i?"\u25B6 ":" ",u=c.name&&c.name!==c.id?` ${c.name}`:"";return`${l}${c.id}${u}`});!a&&i&&d.unshift(`\u25B6 ${i}`),o=d.join(`
32
32
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
33
33
  ${o}
34
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw xt(new Error(`unknown mode: ${n} (known: ${r})`),N.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[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:`
34
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw At(new Error(`unknown mode: ${n} (known: ${r})`),N.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[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:`
35
35
  _(no config options advertised yet)_
36
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>xu(c));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
36
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>Ru(c));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
37
37
  ${d.join(`
38
38
 
39
39
  `)}
@@ -43,15 +43,15 @@ ${d.join(`
43
43
  Available options:
44
44
  ${a}
45
45
  `},_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:`
46
- ${xu(o)}
46
+ ${Ru(o)}
47
47
  `},_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(`
48
48
  `);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
49
49
  "${r}" is not a valid value for "${s}".
50
50
  Valid values:
51
51
  ${a}
52
- `},_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 n={chunks:[]};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.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 xt(new Error("/hydra agent requires an agent id"),N.InvalidParams);if(e===this.agentId)throw xt(new Error(`already on agent ${e}`),N.InvalidParams);if(!this.spawnReplacementAgent)throw xt(new Error("agent switching not configured for this session"),N.InternalError);let n=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await n({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 xt(new Error("agent restart not configured for this session"),N.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw xt(new Error("session is closing"),N.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,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(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let f=(c.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let g=Gs(f.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let h=f.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let g=f.status,h=f.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${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=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=n?.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(`
53
- `)}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,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),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 no(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,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??Vs,Vs)),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,n){return this.requireStreamBuffer().waitForData(e,n)}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=N.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 n=this.promptQueue;this.promptQueue=[];for(let r of n){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(()=>Su(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(()=>Tu.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 n=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(n).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,n){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:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Oy(e,r),o=i?Uy(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 n=[...this.clients.values()];if(n.length===0)throw xt(new Error("no clients attached to handle permission request"),N.PermissionDenied);let s=this.rewriteForClient(e),r=jy(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:u};this.inFlightPermissions.add(c);let l=this.sessionId,f=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function u(p){if(a)return;let g=p.connection.request("session/request_permission",s);d.push({client:p}),g.then(h=>{f(()=>{let y=qy({toolCallId:r,result:h,resolver:p});for(let v of d)v.client.clientId!==p.clientId&&v.client.connection.notify("session/update",{sessionId:l,update:y}).catch(()=>{});i(h)})}).catch(h=>{f(()=>o(h))})}for(let p of n)u(p)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Qs(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).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(n);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["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,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.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 n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Dr(n,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 n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Gs(e.prompt).replace(/\s+$/,""),s=!n.includes(`
54
- `)&&n.startsWith("/")?n.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(n):s==="/model"?i=await this.handleModelCommand(n):i=await this.handleSlashCommand(n,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)}};_y=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"])});import{z as Ht}from"zod";function Pu(t){let e=t.trim();if(e.length===0)return;let n=Eu(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(n=Eu(e.slice(i,o+1)),n===void 0))return}if(n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Jy))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Hr.safeParse(s.synopsis);i.success&&Ky(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Eu(t){try{return JSON.parse(t)}catch{return}}function Ky(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0}var Hr,Jy,od,io=V(()=>{"use strict";Hr=Ht.object({goal:Ht.string().optional(),outcome:Ht.string().optional(),files_touched:Ht.array(Ht.string()).optional(),tools_used:Ht.array(Ht.string()).optional(),rejected_approaches:Ht.array(Ht.string()).optional(),open_threads:Ht.array(Ht.string()).optional()}),Jy=200,od=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
52
+ `},_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 n={chunks:[]};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.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 At(new Error("/hydra agent requires an agent id"),N.InvalidParams);if(e===this.agentId)throw At(new Error(`already on agent ${e}`),N.InvalidParams);if(!this.spawnReplacementAgent)throw At(new Error("agent switching not configured for this session"),N.InternalError);let n=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await n({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 At(new Error("agent restart not configured for this session"),N.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw At(new Error("session is closing"),N.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,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(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){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=nr(u.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let h=u.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let g=u.status,h=u.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${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=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=n?.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(`
53
+ `)}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,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),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 io(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,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??Zs,Zs)),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,n){return this.requireStreamBuffer().waitForData(e,n)}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=N.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 n=this.promptQueue;this.promptQueue=[];for(let r of n){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(()=>Au(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(()=>Mu.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 n=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(n).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,n){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:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Fy(e,r),o=i?jy(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 n=[...this.clients.values()];if(n.length===0)throw At(new Error("no clients attached to handle permission request"),N.PermissionDenied);let s=this.rewriteForClient(e),r=qy(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:f};this.inFlightPermissions.add(c);let l=this.sessionId,u=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function f(p){if(a)return;let g=p.connection.request("session/request_permission",s);d.push({client:p}),g.then(h=>{u(()=>{let y=Wy({toolCallId:r,result:h,resolver:p});for(let I of d)I.client.clientId!==p.clientId&&I.client.connection.notify("session/update",{sessionId:l,update:y}).catch(()=>{});i(h)})}).catch(h=>{u(()=>o(h))})}for(let p of n)f(p)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:tr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).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(n);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["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,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.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 n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>zr(n,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 n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=nr(e.prompt).replace(/\s+$/,""),s=!n.includes(`
54
+ `)&&n.startsWith("/")?n.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(n):s==="/model"?i=await this.handleModelCommand(n):i=await this.handleSlashCommand(n,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)}};Oy=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"])});import{z as jt}from"zod";function _u(t){let e=t.trim();if(e.length===0)return;let n=$u(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(n=$u(e.slice(i,o+1)),n===void 0))return}if(n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Ky))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Jr.safeParse(s.synopsis);i.success&&Vy(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function $u(t){try{return JSON.parse(t)}catch{return}}function Vy(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0}var Jr,Ky,cd,co=V(()=>{"use strict";Jr=jt.object({goal:jt.string().optional(),outcome:jt.string().optional(),files_touched:jt.array(jt.string()).optional(),tools_used:jt.array(jt.string()).optional(),rejected_approaches:jt.array(jt.string()).optional(),open_threads:jt.array(jt.string()).optional()}),Ky=200,cd=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
55
55
  {
56
56
  "title": "short summary, max 80 chars",
57
57
  "synopsis": {
@@ -61,61 +61,61 @@ Valid values:
61
61
  "open_threads": ["work started but not finished"]
62
62
  }
63
63
  }
64
- Use empty arrays/strings where a field doesn't apply.`});import*as Zs from"fs/promises";import*as gC from"path";import{customAlphabet as Vy}from"nanoid";import{z as ne}from"zod";function Ur(){return`${Gy}${Qy()}`}function ew(t){if(!ad.test(t))throw new Error(`unsafe session id: ${t}`)}function fd(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var Yy,Qy,Gy,dd,cd,Xy,ld,ud,Zy,ad,oo,pd=V(()=>{"use strict";ue();ls();io();Yy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qy=Vy(Yy,16),Gy="hydra_lineage_";dd=ne.object({name:ne.string(),description:ne.string().optional()}),cd=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Xy=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),ld=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),ud=ne.object({name:ne.string(),version:ne.string().optional()}),Zy=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:Hr.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:ld.optional(),agentCommands:ne.array(dd).optional(),agentModes:ne.array(cd).optional(),agentModels:ne.array(Xy).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),originatingClient:ud.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),createdAt:ne.string(),updatedAt:ne.string()}),ad=/^[A-Za-z0-9_-]+$/;oo=class{async write(e){ew(e.sessionId);let n={version:1,...e};await It(P.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!ad.test(e))return;let n=await Pt(P.sessionFile(e));if(n!==void 0)try{return Zy.parse(n)}catch{return}}async delete(e){if(ad.test(e)){try{await Zs.unlink(P.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Zs.rmdir(P.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await Zs.readdir(P.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as nw}from"url";import*as jr from"path";import*as co from"fs";function sw(){try{let t=jr.dirname(nw(import.meta.url));for(let e=0;e<8;e+=1){let n=jr.join(t,"package.json");if(co.existsSync(n)){let r=JSON.parse(co.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=jr.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var ce,ps,$t=V(()=>{"use strict";ce=sw(),ps="hydra-acp-cat"});function md(t){let e=new Map;for(let n of Uu(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function Nu(t){return md(t).map(e=>e.name)}function hd(t){let e=new Map;for(let n of Uu(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,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:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function Du(t){return hd(t).map(e=>e.path)}function Hu(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Uu(t){let e=new Map,n=0;for(let s of t){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_${n++}`,c=e.get(d);c===void 0?(c={toolName:Lu(i),paths:new Set},e.set(d,c)):c.toolName=Lu(i);for(let l of Bu(i.rawInput,i.locations))c.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of Bu(i.rawInput,i.locations))a.paths.add(d)}return e}function Lu(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Bu(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.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"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var gd=V(()=>{"use strict"});import{promises as Wr}from"fs";import*as Sd from"path";async function zr(t){let e;try{e=await Wr.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return xw(e)}function xw(t){let e=[];for(let n of t.split(`
65
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Jr(t,e,n=Yu){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function ms(t,e){await Wr.mkdir(Sd.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Wr.writeFile(t,n.length>0?n.join(`
64
+ Use empty arrays/strings where a field doesn't apply.`});import*as rr from"fs/promises";import*as yC from"path";import{customAlphabet as Yy}from"nanoid";import{z as ne}from"zod";function Kr(){return`${Xy}${Gy()}`}function tw(t){if(!ld.test(t))throw new Error(`unsafe session id: ${t}`)}function hd(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var Qy,Gy,Xy,ud,fd,Zy,pd,md,ew,ld,lo,gd=V(()=>{"use strict";me();ms();co();Qy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Gy=Yy(Qy,16),Xy="hydra_lineage_";ud=ne.object({name:ne.string(),description:ne.string().optional()}),fd=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Zy=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),pd=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),md=ne.object({name:ne.string(),version:ne.string().optional()}),ew=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:Jr.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:pd.optional(),agentCommands:ne.array(ud).optional(),agentModes:ne.array(fd).optional(),agentModels:ne.array(Zy).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),originatingClient:md.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),createdAt:ne.string(),updatedAt:ne.string()}),ld=/^[A-Za-z0-9_-]+$/;lo=class{async write(e){tw(e.sessionId);let n={version:1,...e};await St(E.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!ld.test(e))return;let n=await Et(E.sessionFile(e));if(n!==void 0)try{return ew.parse(n)}catch{return}}async delete(e){if(ld.test(e)){try{await rr.unlink(E.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await rr.rmdir(E.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await rr.readdir(E.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as sw}from"url";import*as Vr from"path";import*as fo from"fs";function rw(){try{let t=Vr.dirname(sw(import.meta.url));for(let e=0;e<8;e+=1){let n=Vr.join(t,"package.json");if(fo.existsSync(n)){let r=JSON.parse(fo.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=Vr.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var pe,ys,Mt=V(()=>{"use strict";pe=rw(),ys="hydra-acp-cat"});function yd(t){let e=new Map;for(let n of Wu(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function Uu(t){return yd(t).map(e=>e.name)}function wd(t){let e=new Map;for(let n of Wu(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,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:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function ju(t){return wd(t).map(e=>e.path)}function qu(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Wu(t){let e=new Map,n=0;for(let s of t){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_${n++}`,c=e.get(d);c===void 0?(c={toolName:Du(i),paths:new Set},e.set(d,c)):c.toolName=Du(i);for(let l of Hu(i.rawInput,i.locations))c.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of Hu(i.rawInput,i.locations))a.paths.add(d)}return e}function Du(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Hu(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.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"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var bd=V(()=>{"use strict"});import{promises as Qr}from"fs";import*as Ad from"path";async function Gr(t){let e;try{e=await Qr.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Aw(e)}function Aw(t){let e=[];for(let n of t.split(`
65
+ `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Xr(t,e,n=Xu){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function ws(t,e){await Qr.mkdir(Ad.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Qr.writeFile(t,n.length>0?n.join(`
66
66
  `)+`
67
- `:"")}async function Qu(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Wr.mkdir(Sd.dirname(t),{recursive:!0}),await Wr.appendFile(t,JSON.stringify(n)+`
68
- `,{encoding:"utf8"}))}function fo(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function kd(t,e,n=Yu){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=Jr(r,o,n)))}return r}var Yu,po=V(()=>{"use strict";Yu=500});import{z as we}from"zod";function Kr(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function Ut(t){return Rw.parse(t)}var Aw,Cw,Rw,hs=V(()=>{"use strict";pd();io();Aw=we.object({method:we.string(),params:we.unknown(),recordedAt:we.number()}),Cw=we.object({sessionId:we.string(),lineageId:we.string(),upstreamSessionId:we.string().optional(),agentId:we.string(),cwd:we.string(),title:we.string().optional(),synopsis:Hr.optional(),summarizedThroughEntry:we.number().int().nonnegative().optional(),currentModel:we.string().optional(),currentMode:we.string().optional(),currentUsage:ld.optional(),agentCommands:we.array(dd).optional(),agentModes:we.array(cd).optional(),interactive:we.boolean().optional(),originatingClient:ud.optional(),priority:we.number().int().nonnegative().optional(),createdAt:we.string(),updatedAt:we.string()}),Rw=we.object({version:we.literal(1),exportedAt:we.string(),exportedFrom:we.object({hydraVersion:we.string(),machine:we.string(),hydraHost:we.string().optional()}),session:Cw,history:we.array(Aw),promptHistory:we.array(we.string()).optional(),toolBlobs:we.record(we.string()).optional()})});import{createHash as Uw}from"crypto";function Ed(t){if(Array.isArray(t))return t.map(Ed);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Ed(t[n]);return e}return t}function nr(t){let e=JSON.stringify(Ed(t));return Uw("sha256").update(e).digest("hex").slice(0,16)}var xo=V(()=>{"use strict";Oe()});function Xr(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var vf=V(()=>{"use strict"});import{posix as Zw}from"path";import eb from"strip-ansi";function mt(t){return eb(t).replace(tb,"")}function Ce(t){return mt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function gn(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return ab(n);case"agent_thought_chunk":case"agent_thought":return db(n);case"user_message_chunk":return cb(n);case"prompt_received":return lb(n);case"tool_call":return ub(n,e);case"tool_call_update":return gb(n,e);case"plan":return bb(n);case"current_mode_update":return vb(n);case"current_model_update":return Ib(n);case"turn_complete":return Sb(n);case"usage_update":return ob(n);case"available_commands_update":return rb(n);case"available_modes_update":return ib(n);case"session_info_update":return sb(n);case"config_option_update":return nb(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function nb(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];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}:{}})}n.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:n}}function sb(t){let e=Fe(t,"title"),n=e!==void 0?Ce(e):void 0,s=t._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(n===void 0&&r===void 0)return null;let i={kind:"session-info"};return n!==void 0&&(i.title=n),r!==void 0&&(i.agentId=r),i}function Mo(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Ce(r)};typeof s.description=="string"&&(i.description=Ce(s.description)),e.push(i)}return e}function rb(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Mo(e)}:null}function ib(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];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:Ce(r.id)};typeof r.name=="string"&&(i.name=Ce(r.name)),typeof r.description=="string"&&(i.description=Ce(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function ob(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function ab(t){let e=Zr(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Xr(t)}}function db(t){let e=typeof t.text=="string"?mt(t.text):Zr(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Xr(t)}}function cb(t){let e=t._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 n=Zr(t.content);return n===null?null:{kind:"user-text",text:n}}function lb(t){let e=kb(t.prompt);return e===null?null:{kind:"user-text",text:e}}function kf(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function If(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function $o(t){let e=t.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=If(r.oldText),o=If(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 n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,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 xf(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:mt(n)}function ub(t,e={}){let n=Fe(t,"toolCallId")??Fe(t,"id");if(!n)return null;let s=Fe(t,"title")??Fe(t,"name")??Fe(t,"label")??"tool call",r=Fe(t,"name")??Fe(t,"title");if(kf(r)){let u=xf(t);if(u!==null){let p=Fe(t,"status"),g={kind:"exit-plan-mode",toolCallId:n,plan:u};return p!==void 0&&(g.status=p),g}}let i=Cf(Ce(s),t,e),o=Fe(t,"status"),a=Fe(t,"kind"),d={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=$o(t);c!==null&&(d.editDiff=c);let l=Af(t);l!==void 0&&(d.detail=l);let f=Xr(t);return f!==void 0&&(d.workerTaskId=f),d}function Af(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.command=="string"&&n.command.trim().length>0){let i=Ce(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return mb(i,Sf)}let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return hb(Be(Ce(s)),Sf)}function pb(t){for(let e of fb)if(t.startsWith(e))return!0;return!1}function Cf(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Be(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;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===`/${t}`||o.endsWith(`/${t}`)||o===t))return Be(o)}return pb(t)?Be(`/${t}`):n.cwd&&n.cwd.length>0?Be(Zw.resolve(n.cwd,t)):t}function mb(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function hb(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function gb(t,e={}){let n=Fe(t,"toolCallId")??Fe(t,"id");if(!n)return null;let s=Fe(t,"title"),r=s!==void 0?Cf(Ce(s),t,e):void 0,i=Fe(t,"status"),o=$o(t),a=Af(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=Fe(t,"name")??s;if(kf(c)){let u={kind:"exit-plan-mode",toolCallId:n},p=xf(t);return p!==null&&(u.plan=p),i!==void 0&&(u.status=i),u}let l={kind:"tool-call-update",toolCallId:n};if(r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let u=yb(t);u!==null&&(l.errorText=u),wb(t,u)&&(l.upstreamInterrupted=!0)}let f=Xr(t);return f!==void 0&&(l.workerTaskId=f),l}function yb(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Zr(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return mt(s)}return null}function wb(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function bb(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Ce(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),n.push(o)}return{kind:"plan",entries:n}}function vb(t){let e=Fe(t,"currentModeId")??Fe(t,"currentMode")??Fe(t,"mode");return e?{kind:"mode-changed",mode:Ce(e)}:null}function Ib(t){let e=Fe(t,"currentModel")??Fe(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.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:Ce(e),...s&&s.length>0?{availableModels:s}:{}}}function Sb(t){let e=Fe(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Zr(t){if(typeof t=="string")return mt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?mt(e.text):null}function kb(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Zr(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Fe(t,e){let n=t[e];return typeof n=="string"?n:void 0}var tb,Sf,fb,Un=V(()=>{"use strict";ue();vf();tb=/[\x00-\x08\x0b-\x1f\x7f]/g;Sf=64;fb=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function sr(t){let e=new Map,n=new Map;for(let r of t){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=Ab(o);if(c.length===0)continue;let l=c;if(d!==void 0){let f=e.get(d)??[],u=[];for(let p of c)f.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(d,[...f,...u]),l=u}for(let f of l)xb(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function rr(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function xb(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function Ab(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,f=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||f===void 0||e.push({path:o,oldText:l,newText:f})}if(e.length>0)return e}}let s=t.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=$o(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var _o=V(()=>{"use strict";Un()});function Oo(t){let e=Cb(t),n=Rb(e),s=[];Tb(s,t),Eb(s,e,n);let r=s.join(`
67
+ `:"")}async function Zu(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Qr.mkdir(Ad.dirname(t),{recursive:!0}),await Qr.appendFile(t,JSON.stringify(n)+`
68
+ `,{encoding:"utf8"}))}function ho(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function Cd(t,e,n=Xu){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=Xr(r,o,n)))}return r}var Xu,go=V(()=>{"use strict";Xu=500});import{z as we}from"zod";function Zr(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function qt(t){return Tw.parse(t)}var Cw,Rw,Tw,bs=V(()=>{"use strict";gd();co();Cw=we.object({method:we.string(),params:we.unknown(),recordedAt:we.number()}),Rw=we.object({sessionId:we.string(),lineageId:we.string(),upstreamSessionId:we.string().optional(),agentId:we.string(),cwd:we.string(),title:we.string().optional(),synopsis:Jr.optional(),summarizedThroughEntry:we.number().int().nonnegative().optional(),currentModel:we.string().optional(),currentMode:we.string().optional(),currentUsage:pd.optional(),agentCommands:we.array(ud).optional(),agentModes:we.array(fd).optional(),interactive:we.boolean().optional(),originatingClient:md.optional(),priority:we.number().int().nonnegative().optional(),createdAt:we.string(),updatedAt:we.string()}),Tw=we.object({version:we.literal(1),exportedAt:we.string(),exportedFrom:we.object({hydraVersion:we.string(),machine:we.string(),hydraHost:we.string().optional()}),session:Rw,history:we.array(Cw),promptHistory:we.array(we.string()).optional(),toolBlobs:we.record(we.string()).optional()})});import{createHash as jw}from"crypto";function $d(t){if(Array.isArray(t))return t.map($d);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=$d(t[n]);return e}return t}function ar(t){let e=JSON.stringify($d(t));return jw("sha256").update(e).digest("hex").slice(0,16)}var Ro=V(()=>{"use strict";Oe()});function ri(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var kf=V(()=>{"use strict"});import{posix as eb}from"path";import tb from"strip-ansi";function gt(t){return tb(t).replace(nb,"")}function Ae(t){return gt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function bn(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return db(n);case"agent_thought_chunk":case"agent_thought":return cb(n);case"user_message_chunk":return lb(n);case"prompt_received":return ub(n);case"tool_call":return fb(n,e);case"tool_call_update":return yb(n,e);case"plan":return vb(n);case"current_mode_update":return Ib(n);case"current_model_update":return Sb(n);case"turn_complete":return kb(n);case"usage_update":return ab(n);case"available_commands_update":return ib(n);case"available_modes_update":return ob(n);case"session_info_update":return rb(n);case"config_option_update":return sb(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function sb(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];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}:{}})}n.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:n}}function rb(t){let e=Fe(t,"title"),n=e!==void 0?Ae(e):void 0,s=t._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(n===void 0&&r===void 0)return null;let i={kind:"session-info"};return n!==void 0&&(i.title=n),r!==void 0&&(i.agentId=r),i}function Oo(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Ae(r)};typeof s.description=="string"&&(i.description=Ae(s.description)),e.push(i)}return e}function ib(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Oo(e)}:null}function ob(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];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:Ae(r.id)};typeof r.name=="string"&&(i.name=Ae(r.name)),typeof r.description=="string"&&(i.description=Ae(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function ab(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function db(t){let e=ii(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ri(t)}}function cb(t){let e=typeof t.text=="string"?gt(t.text):ii(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ri(t)}}function lb(t){let e=t._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 n=ii(t.content);return n===null?null:{kind:"user-text",text:n}}function ub(t){let e=xb(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Cf(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function xf(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Fo(t){let e=t.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=xf(r.oldText),o=xf(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 n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,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 Rf(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:gt(n)}function fb(t,e={}){let n=Fe(t,"toolCallId")??Fe(t,"id");if(!n)return null;let s=Fe(t,"title")??Fe(t,"name")??Fe(t,"label")??"tool call",r=Fe(t,"name")??Fe(t,"title");if(Cf(r)){let f=Rf(t);if(f!==null){let p=Fe(t,"status"),g={kind:"exit-plan-mode",toolCallId:n,plan:f};return p!==void 0&&(g.status=p),g}}let i=Ef(Ae(s),t,e),o=Fe(t,"status"),a=Fe(t,"kind"),d={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Fo(t);c!==null&&(d.editDiff=c);let l=Tf(t);l!==void 0&&(d.detail=l);let u=ri(t);return u!==void 0&&(d.workerTaskId=u),d}function Tf(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.command=="string"&&n.command.trim().length>0){let i=Ae(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return hb(i,Af)}let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return gb(Ne(Ae(s)),Af)}function mb(t){for(let e of pb)if(t.startsWith(e))return!0;return!1}function Ef(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ne(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;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===`/${t}`||o.endsWith(`/${t}`)||o===t))return Ne(o)}return mb(t)?Ne(`/${t}`):n.cwd&&n.cwd.length>0?Ne(eb.resolve(n.cwd,t)):t}function hb(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function gb(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function yb(t,e={}){let n=Fe(t,"toolCallId")??Fe(t,"id");if(!n)return null;let s=Fe(t,"title"),r=s!==void 0?Ef(Ae(s),t,e):void 0,i=Fe(t,"status"),o=Fo(t),a=Tf(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=Fe(t,"name")??s;if(Cf(c)){let f={kind:"exit-plan-mode",toolCallId:n},p=Rf(t);return p!==null&&(f.plan=p),i!==void 0&&(f.status=i),f}let l={kind:"tool-call-update",toolCallId:n};if(r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let f=wb(t);f!==null&&(l.errorText=f),bb(t,f)&&(l.upstreamInterrupted=!0)}let u=ri(t);return u!==void 0&&(l.workerTaskId=u),l}function wb(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ii(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return gt(s)}return null}function bb(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function vb(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Ae(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),n.push(o)}return{kind:"plan",entries:n}}function Ib(t){let e=Fe(t,"currentModeId")??Fe(t,"currentMode")??Fe(t,"mode");return e?{kind:"mode-changed",mode:Ae(e)}:null}function Sb(t){let e=Fe(t,"currentModel")??Fe(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.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:Ae(e),...s&&s.length>0?{availableModels:s}:{}}}function kb(t){let e=Fe(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function ii(t){if(typeof t=="string")return gt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?gt(e.text):null}function xb(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=ii(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Fe(t,e){let n=t[e];return typeof n=="string"?n:void 0}var nb,Af,pb,zn=V(()=>{"use strict";me();kf();nb=/[\x00-\x08\x0b-\x1f\x7f]/g;Af=64;pb=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function dr(t){let e=new Map,n=new Map;for(let r of t){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=Cb(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)Ab(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function cr(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function Ab(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function Cb(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.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=Fo(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Lo=V(()=>{"use strict";zn()});function Bo(t){let e=Rb(t),n=Tb(e),s=[];Eb(s,t),Pb(s,e,n);let r=s.join(`
69
69
  `);return r.endsWith(`
70
70
  `)||(r+=`
71
- `),r}function Cb(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=gn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Rb(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function Tb(t,e){let n=e.session,s=je(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${ys(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Pd(a.size)}`:void 0;d.push(c?`${Pd(a.used)} / ${c} tokens`:`${Pd(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 ")}`)}t.push(i.join(`
72
- `)),t.push("")}function Eb(t,e,n){if(!e.some(c=>Pb(c.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},d=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of c.text.split(`
73
- `))t.push(`> ${ys(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let l=c.text.split(`
74
- `);for(let f of l)t.push(`> _${ys(f)}_`);t.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let l=n.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};t.push(`- ${$b(l.status)} ${Mb(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{d(),a(),t.push("**Plan:**"),t.push("");for(let l of c.entries){let f=l.status==="completed"?"[x]":"[ ]";t.push(`- ${f} ${ys(l.content)}`)}t.push("");break}case"mode-changed":d(),a(),t.push(`_mode: ${ys(c.mode)}_`),t.push("");break;case"model-changed":d(),a(),t.push(`_model: ${ys(c.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Pb(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Mb(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${ys(t.title)}${n}`}function $b(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function ys(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Pd(t){return t.toLocaleString("en-US")}var Md=V(()=>{"use strict";Un();en()});function qn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.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:0,error:{code:N.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),t.on("close",()=>r()),t.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)=>{t.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(t.close(),r())}}}var si=V(()=>{"use strict";nt()});import{spawn as Tv}from"child_process";import{setTimeout as Ev}from"timers/promises";async function or(t){await ri(t)||(process.stderr.write(`hydra-acp: daemon not running; starting it...
75
- `),Wo(),await zo(t))}async function ri(t){let n=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{return(await fetch(n,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function ar(t,e=1e3){let s=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{let r=await fetch(s,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!r.ok)return;let i=await r.json();return{version:typeof i.version=="string"?i.version:void 0,configDigest:typeof i.configDigest=="string"?i.configDigest:void 0}}catch{return}}function Wo(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Tv(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function zo(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await ri(t))return;await Ev(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var dr=V(()=>{"use strict"});async function yn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await n(s.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"live",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority})):[]}async function fp(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(d=>d.installed==="yes"):[],i=0,o=0,a=0;for(let d of r)try{let c=await e(`${t.baseUrl}/v1/agents/${d.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});if(!c.ok)continue;let l=await c.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function pp(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description})):[]}async function Jo(t,e,n={},s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function ii(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function mp(t,e,n,s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})});if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function hp(t,e,n,s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})});if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function gp(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})});if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function yp(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await s(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function wp(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Ko(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="live"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var oi=V(()=>{"use strict"});function Dd(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function bp(t,e){let n=t??"?",s=Dd(e);return s?`${n}${Ov}${s}`:n}function vp(t){return t??"?"}function Ip(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Hd(e,n)}function Hd(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var Ov,Ud=V(()=>{"use strict";Ov="\u2022"});function Sp(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!Yo.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Yo.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function mr(t,e=Date.now()){return{session:je(t.sessionId),upstream:Lv(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:Bv(t.status,t.busy,t.awaitingInput),agent:vp(t.agentId),model:Dd(t.currentModel)??"-",age:Nv(t.updatedAt,e),title:t.title??"-",cwd:Be(t.cwd),cost:Ip(t.currentUsage)}}function Lv(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function Bv(t,e,n){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":"LIVE"}function hr(t,e={}){let n=e.columns??fr,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=Dv(pr[r],t.map(i=>i[r]));return s}function Nv(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let d=Math.floor(a/7);if(d<9)return`${d}w`;let c=Math.floor(a/30);return c<12?`${c}mo`:`${Math.floor(a/365)}y`}function Dv(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Jn(t,e,n,s={}){let r=s.columns??fr,i=s.cwdMaxWidth??Fv,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((x,C)=>C===r.length-1?t[x]:o(x)).join(Vo);let a=r.map((b,x)=>({col:b,i:x})).filter(({col:b})=>jd.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=r.map(o).join(Vo);return b.length>n?b.slice(0,n):b}let c=r.filter(b=>!jd.has(b)).reduce((b,x)=>b+e[x],0),l=Math.max(0,r.length-1),f=n-c-l*Vo.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:b,i:x}of a){if(x===d)continue;let C=b==="cwd"?Math.min(e[b],i):e[b],F=Math.min(C,Math.max(0,p-1));u.set(x,F),p=Math.max(0,p-F)}u.set(d,Math.max(0,p));let g=r.length-1,h=(b,x,C)=>{if(b==="cwd")return ai(t[b],x).padEnd(x);let F=Hv(t[b],x);return C?F:F.padEnd(x)},v=r.map((b,x)=>jd.has(b)?h(b,u.get(x)??0,x===g):o(b)).join(Vo);return v.length>n?v.slice(0,n):v}function Hv(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function ai(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var Yo,fr,jd,pr,Vo,Fv,Qo=V(()=>{"use strict";Ud();ue();en();Yo=["session","upstream","host","state","agent","model","age","cwd","title","cost"],fr=["session","state","age","cwd","title","agent","cost"],jd=new Set(["cwd","title"]),pr={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Vo=" ",Fv=32});import*as _t from"fs/promises";import*as Ot from"path";async function xp(t={}){let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=new URL(`${s}/v1/sessions`);(t.includeNonInteractive||t.all)&&r.searchParams.set("includeNonInteractive","true");let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${n}`}});i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
71
+ `),r}function Rb(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=bn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Tb(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function Eb(t,e){let n=e.session,s=qe(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Is(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${_d(a.size)}`:void 0;d.push(c?`${_d(a.used)} / ${c} tokens`:`${_d(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 ")}`)}t.push(i.join(`
72
+ `)),t.push("")}function Pb(t,e,n){if(!e.some(c=>Mb(c.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},d=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of c.text.split(`
73
+ `))t.push(`> ${Is(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let l=c.text.split(`
74
+ `);for(let u of l)t.push(`> _${Is(u)}_`);t.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let l=n.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};t.push(`- ${_b(l.status)} ${$b(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{d(),a(),t.push("**Plan:**"),t.push("");for(let l of c.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${Is(l.content)}`)}t.push("");break}case"mode-changed":d(),a(),t.push(`_mode: ${Is(c.mode)}_`),t.push("");break;case"model-changed":d(),a(),t.push(`_model: ${Is(c.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Mb(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function $b(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Is(t.title)}${n}`}function _b(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function Is(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _d(t){return t.toLocaleString("en-US")}var Od=V(()=>{"use strict";zn();nn()});function Kn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.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:0,error:{code:N.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),t.on("close",()=>r()),t.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)=>{t.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(t.close(),r())}}}var ci=V(()=>{"use strict";st()});import{spawn as Ev}from"child_process";import{setTimeout as Pv}from"timers/promises";async function ur(t){await li(t)||(process.stderr.write(`hydra-acp: daemon not running; starting it...
75
+ `),Ko(),await Vo(t))}async function li(t){let n=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{return(await fetch(n,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function fr(t,e=1e3){let s=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{let r=await fetch(s,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!r.ok)return;let i=await r.json();return{version:typeof i.version=="string"?i.version:void 0,configDigest:typeof i.configDigest=="string"?i.configDigest:void 0}}catch{return}}function Ko(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Ev(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Vo(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await li(t))return;await Pv(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var pr=V(()=>{"use strict"});async function vn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await n(s.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"live",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority})):[]}async function hp(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(d=>d.installed==="yes"):[],i=0,o=0,a=0;for(let d of r)try{let c=await e(`${t.baseUrl}/v1/agents/${d.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});if(!c.ok)continue;let l=await c.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function gp(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description})):[]}async function Yo(t,e,n={},s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function rn(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function yp(t,e,n,s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})});if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function wp(t,e,n,s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})});if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function bp(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})});if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function vp(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await s(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function Ip(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Qo(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="live"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var ui=V(()=>{"use strict"});function jd(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Sp(t,e){let n=t??"?",s=jd(e);return s?`${n}${Fv}${s}`:n}function kp(t){return t??"?"}function xp(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:qd(e,n)}function qd(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var Fv,Wd=V(()=>{"use strict";Fv="\u2022"});function Ap(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!Xo.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Xo.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function br(t,e=Date.now()){return{session:qe(t.sessionId),upstream:Bv(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:Nv(t.status,t.busy,t.awaitingInput),agent:kp(t.agentId),model:jd(t.currentModel)??"-",age:Dv(t.updatedAt,e),title:t.title??"-",cwd:Ne(t.cwd),cost:xp(t.currentUsage)}}function Bv(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function Nv(t,e,n){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":"LIVE"}function vr(t,e={}){let n=e.columns??yr,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=Hv(wr[r],t.map(i=>i[r]));return s}function Dv(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let d=Math.floor(a/7);if(d<9)return`${d}w`;let c=Math.floor(a/30);return c<12?`${c}mo`:`${Math.floor(a/365)}y`}function Hv(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Qn(t,e,n,s={}){let r=s.columns??yr,i=s.cwdMaxWidth??Lv,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((x,M)=>M===r.length-1?t[x]:o(x)).join(Go);let a=r.map((b,x)=>({col:b,i:x})).filter(({col:b})=>zd.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=r.map(o).join(Go);return b.length>n?b.slice(0,n):b}let c=r.filter(b=>!zd.has(b)).reduce((b,x)=>b+e[x],0),l=Math.max(0,r.length-1),u=n-c-l*Go.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:x}of a){if(x===d)continue;let M=b==="cwd"?Math.min(e[b],i):e[b],_=Math.min(M,Math.max(0,p-1));f.set(x,_),p=Math.max(0,p-_)}f.set(d,Math.max(0,p));let g=r.length-1,h=(b,x,M)=>{if(b==="cwd")return fi(t[b],x).padEnd(x);let _=Uv(t[b],x);return M?_:_.padEnd(x)},I=r.map((b,x)=>zd.has(b)?h(b,f.get(x)??0,x===g):o(b)).join(Go);return I.length>n?I.slice(0,n):I}function Uv(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function fi(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var Xo,yr,zd,wr,Go,Lv,Zo=V(()=>{"use strict";Wd();me();nn();Xo=["session","upstream","host","state","agent","model","age","cwd","title","cost"],yr=["session","state","age","cwd","title","agent","cost"],zd=new Set(["cwd","title"]),wr={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Go=" ",Lv=32});import*as $t from"fs/promises";import*as _t from"path";async function Rp(t={}){let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=new URL(`${s}/v1/sessions`);(t.includeNonInteractive||t.all)&&r.searchParams.set("includeNonInteractive","true");let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${n}`}});i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
76
76
  `),process.exit(1));let o=await i.json(),a=o.sessions,d=t.host??"local",c=d==="all"?a:d==="local"?a.filter(b=>!b.importedFromMachine||!!b.upstreamSessionId):a.filter(b=>b.importedFromMachine===d&&!b.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(c,null,2)+`
77
77
  `);return}if(c.length===0){if(d==="local"&&o.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
78
78
  `);return}if(d!=="local"&&d!=="all"){process.stdout.write(`No sessions from ${d}.
79
79
  `);return}process.stdout.write(`No active sessions.
80
- `);return}let l=c.slice().sort((b,x)=>{let C=(x.status==="live"?1:0)-(b.status==="live"?1:0);return C!==0?C:String(x.updatedAt||"").localeCompare(String(b.updatedAt||""))}),f=l,u=0;if(!t.all){let b=l.filter(z=>z.status!=="cold").length,x=e.sessionListColdLimit,C=l.slice(b,b+x),F=l.length-b-C.length;f=[...l.slice(0,b),...C],u=F}let p=Date.now(),g=f.map(b=>mr(b,p)),h={columns:t.columns??e.tui.sessionColumns??fr,cwdMaxWidth:e.tui.cwdColumnMaxWidth},y=hr(g,h),v=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Jn(pr,y,v,h)+`
81
- `);for(let b of g)process.stdout.write(Jn(b,y,v,h)+`
82
- `);u>0&&process.stdout.write(`
83
- ... ${u} more cold session${u===1?"":"s"} hidden. Use --all to show.
84
- `)}async function Ap(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
85
- `),process.exit(2));let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/sessions/${t}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});!r.ok&&r.status!==204&&(process.stderr.write(`Daemon returned HTTP ${r.status}
80
+ `);return}let l=c.slice().sort((b,x)=>{let M=(x.status==="live"?1:0)-(b.status==="live"?1:0);return M!==0?M:String(x.updatedAt||"").localeCompare(String(b.updatedAt||""))}),u=l,f=0;if(!t.all){let b=l.filter(Q=>Q.status!=="cold").length,x=e.sessionListColdLimit,M=l.slice(b,b+x),_=l.length-b-M.length;u=[...l.slice(0,b),...M],f=_}let p=Date.now(),g=u.map(b=>br(b,p)),h={columns:t.columns??e.tui.sessionColumns??yr,cwdMaxWidth:e.tui.cwdColumnMaxWidth},y=vr(g,h),I=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Qn(wr,y,I,h)+`
81
+ `);for(let b of g)process.stdout.write(Qn(b,y,I,h)+`
82
+ `);f>0&&process.stdout.write(`
83
+ ... ${f} more cold session${f===1?"":"s"} hidden. Use --all to show.
84
+ `)}async function Tp(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
85
+ `),process.exit(2));let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/sessions/${t}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});!r.ok&&r.status!==204&&(process.stderr.write(`Daemon returned HTTP ${r.status}
86
86
  `),process.exit(1)),process.stdout.write(`Killed ${t}
87
- `)}async function Cp(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
88
- `),process.exit(2));let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/sessions/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});!r.ok&&r.status!==204&&(process.stderr.write(`Daemon returned HTTP ${r.status}
87
+ `)}async function Ep(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
88
+ `),process.exit(2));let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/sessions/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});!r.ok&&r.status!==204&&(process.stderr.write(`Daemon returned HTTP ${r.status}
89
89
  `),process.exit(1)),process.stdout.write(`Removed ${t}
90
- `)}async function Rp(t){let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=t.maxAgeDays!==void 0?t.maxAgeDays:0,i={maxAgeDays:r};t.limit!==void 0&&(i.limit=t.limit),i.selection=t.keepUndecided?"explicit":"unpromoted";let o=await fetch(`${s}/v1/sessions/collect`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(i)});o.ok||(process.stderr.write(`Daemon returned HTTP ${o.status}
90
+ `)}async function Pp(t){let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=t.maxAgeDays!==void 0?t.maxAgeDays:0,i={maxAgeDays:r};t.limit!==void 0&&(i.limit=t.limit),i.selection=t.keepUndecided?"explicit":"unpromoted";let o=await fetch(`${s}/v1/sessions/collect`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(i)});o.ok||(process.stderr.write(`Daemon returned HTTP ${o.status}
91
91
  `),process.exit(1));let a=await o.json();if(t.json){process.stdout.write(`${JSON.stringify(a,null,2)}
92
92
  `);return}let d=t.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(a.considered===0){let l=r>0?` older than ${r}d`:"";process.stdout.write(`No ${d} sessions${l} found.
93
- `);return}let c=a.oldestLastUsedMs!==void 0?` (oldest: ${Uv(Date.now()-a.oldestLastUsedMs)} ago)`:"";process.stdout.write(`Collected ${a.deleted} of ${a.considered} ${d} session(s)${c}.
93
+ `);return}let c=a.oldestLastUsedMs!==void 0?` (oldest: ${jv(Date.now()-a.oldestLastUsedMs)} ago)`:"";process.stdout.write(`Collected ${a.deleted} of ${a.considered} ${d} session(s)${c}.
94
94
  `),a.failed>0&&process.stdout.write(` ${a.failed} failed (see daemon log).
95
95
  `),a.deferred>0&&process.stdout.write(` ${a.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
96
- `)}function Uv(t){let e=t/864e5;if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return n>=1?`${n.toFixed(n>=10?0:1)}h`:`${(t/(60*1e3)).toFixed(0)}m`}async function Tp(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
97
- `),process.exit(2));let s=await G(),r=await de(),i=fe(s.daemon.host,s.daemon.port,!!s.daemon.tls),o=n==="summary"?"?tools=summary":"",a=await fetch(`${i}/v1/sessions/${encodeURIComponent(t)}/export${o}`,{headers:{Authorization:`Bearer ${r}`}});if(!a.ok){let l=await a.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${a.status}: ${l}
96
+ `)}function jv(t){let e=t/864e5;if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return n>=1?`${n.toFixed(n>=10?0:1)}h`:`${(t/(60*1e3)).toFixed(0)}m`}async function Mp(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
97
+ `),process.exit(2));let s=await G(),r=await fe(),i=he(s.daemon.host,s.daemon.port,!!s.daemon.tls),o=n==="summary"?"?tools=summary":"",a=await fetch(`${i}/v1/sessions/${encodeURIComponent(t)}/export${o}`,{headers:{Authorization:`Bearer ${r}`}});if(!a.ok){let l=await a.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${a.status}: ${l}
98
98
  `),process.exit(1)}let d=await a.text();if(!e){process.stdout.write(d),d.endsWith(`
99
99
  `)||process.stdout.write(`
100
- `);return}let c=e==="."?Kv(a,t):e;await _t.mkdir(Ot.dirname(Ot.resolve(c)),{recursive:!0}),await _t.writeFile(c,d,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
101
- `)}async function Ep(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
102
- `),process.exit(2));let n,s,r=await jv(t);if(r!==null){let o=qv(r.raw);n=Oo(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Ot.basename(t,Ot.extname(t))}-${a}.md`}else{let o=await G(),a=await de(),d=fe(o.daemon.host,o.daemon.port,!!o.daemon.tls),c=await fetch(`${d}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${a}`}});if(!c.ok){let f=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${f}
100
+ `);return}let c=e==="."?Vv(a,t):e;await $t.mkdir(_t.dirname(_t.resolve(c)),{recursive:!0}),await $t.writeFile(c,d,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
101
+ `)}async function $p(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
102
+ `),process.exit(2));let n,s,r=await qv(t);if(r!==null){let o=Wv(r.raw);n=Bo(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${_t.basename(t,_t.extname(t))}-${a}.md`}else{let o=await G(),a=await fe(),d=he(o.daemon.host,o.daemon.port,!!o.daemon.tls),c=await fetch(`${d}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${a}`}});if(!c.ok){let u=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${u}
103
103
  `),process.exit(1)}n=await c.text();let l=new Date().toISOString().replace(/[:.]/g,"-");s=`hydra-${t}-${l}.md`}if(!e){process.stdout.write(n),n.endsWith(`
104
104
  `)||process.stdout.write(`
105
- `);return}let i=e==="."?s:e;await _t.mkdir(Ot.dirname(Ot.resolve(i)),{recursive:!0}),await _t.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
106
- `)}async function jv(t){try{if(!(await _t.stat(t)).isFile())return null}catch{return null}let e=await _t.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
107
- `),process.exit(1)}}function qv(t){try{return Ut(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
108
- `),process.exit(1)}}async function Pp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
109
- `),process.exit(2));let n;if(e.cwd!==void 0){let l=Ot.resolve(e.cwd);try{(await _t.stat(l)).isDirectory()||(process.stderr.write(`--cwd ${l} is not a directory
105
+ `);return}let i=e==="."?s:e;await $t.mkdir(_t.dirname(_t.resolve(i)),{recursive:!0}),await $t.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
106
+ `)}async function qv(t){try{if(!(await $t.stat(t)).isFile())return null}catch{return null}let e=await $t.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
107
+ `),process.exit(1)}}function Wv(t){try{return qt(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
108
+ `),process.exit(1)}}async function _p(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
109
+ `),process.exit(2));let n;if(e.cwd!==void 0){let l=_t.resolve(e.cwd);try{(await $t.stat(l)).isDirectory()||(process.stderr.write(`--cwd ${l} is not a directory
110
110
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${l} does not exist
111
- `),process.exit(1)}n=l}let s;t==="-"?s=await Jv():s=await _t.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(l){process.stderr.write(`Failed to parse bundle: ${l.message}
112
- `),process.exit(1)}if(e.info===!0){let l=await G();zv(r,l.tui.cwdColumnMaxWidth);return}let i=await G(),o=await de(),a=fe(i.daemon.host,i.daemon.port,!!i.daemon.tls),d=await fetch(`${a}/v1/sessions/import`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}})});if(d.status===409){let l=await d.json().catch(()=>({}));process.stderr.write(`Bundle already imported as ${l.existingSessionId??"unknown"}. Use --replace to overwrite.
111
+ `),process.exit(1)}n=l}let s;t==="-"?s=await Kv():s=await $t.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(l){process.stderr.write(`Failed to parse bundle: ${l.message}
112
+ `),process.exit(1)}if(e.info===!0){let l=await G();Jv(r,l.tui.cwdColumnMaxWidth);return}let i=await G(),o=await fe(),a=he(i.daemon.host,i.daemon.port,!!i.daemon.tls),d=await fetch(`${a}/v1/sessions/import`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}})});if(d.status===409){let l=await d.json().catch(()=>({}));process.stderr.write(`Bundle already imported as ${l.existingSessionId??"unknown"}. Use --replace to overwrite.
113
113
  `),process.exit(1)}if(!d.ok){let l=await d.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${d.status}: ${l}
114
114
  `),process.exit(1)}let c=await d.json();process.stdout.write(c.replaced?`Replaced ${c.sessionId} (from ${c.importedFromSessionId})
115
115
  `:`Imported as ${c.sessionId} (from ${c.importedFromSessionId})
116
- `)}function Wv(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold"}}function zv(t,e){let n;try{n=Ut(t)}catch(c){process.stderr.write(`Not a valid bundle: ${c.message}
117
- `),process.exit(1)}let s=Wv(n),r=mr(s),i={columns:Yo,cwdMaxWidth:e},o=hr([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Jn(pr,o,a,i)+`
118
- `),process.stdout.write(Jn(r,o,a,i)+`
116
+ `)}function zv(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold"}}function Jv(t,e){let n;try{n=qt(t)}catch(c){process.stderr.write(`Not a valid bundle: ${c.message}
117
+ `),process.exit(1)}let s=zv(n),r=br(s),i={columns:Xo,cwdMaxWidth:e},o=vr([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Qn(wr,o,a,i)+`
118
+ `),process.stdout.write(Qn(r,o,a,i)+`
119
119
  `);let d=n.session.upstreamSessionId??"-";process.stdout.write(`
120
120
  lineage: ${n.session.lineageId}
121
121
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -123,327 +123,327 @@ origin session: ${n.session.sessionId}
123
123
  origin upstream: ${d}
124
124
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
125
125
  `:`
126
- `))}async function Jv(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function Kv(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}function fe(t,e,n){return`${n?"https":"http"}://${t}:${e}`}async function Mp(t,e={}){let n=await G(),s;if(t!==void 0&&t.length>0)s=t;else{let c=await Qt(n),l=e.cwd?Ot.resolve(e.cwd):process.cwd(),f=await yn(c,{cwd:l,all:!0}),u=Ko(f,l);u||(process.stderr.write(`No sessions found for ${l}.
127
- `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=Vv(e.host,n),a=je(s),d=kl({host:r,port:i,sessionId:a});process.stdout.write(d+`
126
+ `))}async function Kv(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function Vv(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}function he(t,e,n){return`${n?"https":"http"}://${t}:${e}`}async function Op(t,e={}){let n=await G(),s;if(t!==void 0&&t.length>0)s=t;else{let c=await Xt(n),l=e.cwd?_t.resolve(e.cwd):process.cwd(),u=await vn(c,{cwd:l,all:!0}),f=Qo(u,l);f||(process.stderr.write(`No sessions found for ${l}.
127
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=Yv(e.host,n),a=qe(s),d=Cl({host:r,port:i,sessionId:a});process.stdout.write(d+`
128
128
  `),o&&process.stderr.write(`Note: this URL points at loopback (127.0.0.1) and only works from the same machine. Set daemon.publicHost in config.json or pass --host <name> to advertise an externally-reachable hostname.
129
- `)}function Vv(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=kp(t,443);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=kp(e.daemon.publicHost,443);return{host:n,port:s,isFallback:!1}}return pn(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function kp(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}var wn=V(()=>{"use strict";Oe();ft();js();Nr();en();oi();hs();Md();Qo()});import{spawn as Yv}from"child_process";import{Writable as Qv}from"stream";function Go(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=Gv(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??Yv,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
130
- `)});let d=new Qv({write(l,f,u){if(!a.writable){u();return}a.write(l,g=>{if(g&&g.code!=="EPIPE"){u(g);return}u()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});d.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
131
- `)});let c=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:d,flush:async()=>{a.writable&&await new Promise(l=>{d.end(()=>l())}),await c}}}function Gv(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var qd=V(()=>{"use strict"});import Xv from"chalk";import{highlight as Zv,supportsLanguage as eI}from"cli-highlight";import Zo from"string-width";function nn(t,e={}){switch(t.kind){case"user-text":{let n=Wd(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return Wd(t.text," ","agent");case"agent-thought":return Wd(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return vI(t,e.maxPlanItems??wI);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function di(t,e){let n=e?.codeOpen??"^C",s=e?.boldReset??"^:",r=e?.codeReset??"^:",i=t.replace(/\^/g,"^^");return i=i.replace(/\*\*(.+?)\*\*/g,`^+$1${s}`),i=i.replace(/`([^`]+)`/g,`${n}$1${r}`),i}function _p(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function Op(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,d=[],c=t.replace(/^\s+/,"").split(`
132
- `),l=!1,f="",u=[],p=i!==" ",g=(v,b,x=" ")=>{let C={prefix:x,body:v,bodyStyle:b};r!==void 0&&(C.prefixStyle=r),d.push(C)},h=()=>p?(p=!1,i):" ",y=()=>{if(u.length!==0){if(s){let v=lI(f,u);for(let b of v){let x={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(x.prefixStyle=r),b.ansi&&(x.ansi=!0),d.push(x)}}else for(let v of u)g(v.replace(/\^/g,"^^"),n);u=[],f=""}};for(let v=0;v<c.length;v++){let b=c[v],x=b.match(/^\s*```\s*(\w*)\s*$/);if(x){l?(y(),l=!1):(l=!0,f=x[1]??"");continue}if(l){u.push(b);continue}let C=b.match(/^(#{1,6})\s+(.*)$/);if(C){let D=C[1].length,$=C[2]??"",W=s?D===1?"heading-1":D===2?"heading-2":"heading-3":n,K=s?_p(W):o;g(di($,K),W,h());continue}let F=c[v+1];if(b.includes("|")&&F!==void 0&&tI(F)&&ci(b).length===ci(F).length){let D=ci(b),$=[],W=v+2;for(;W<c.length&&c[W].includes("|");)$.push(ci(c[W])),W++;let K=dI(D,$,a);for(let ee of K)r!==void 0&&(ee.prefixStyle=r),d.push(ee);v=W-1;continue}let z=b.match(/^(\s*)[-*+]\s+(.*)$/);if(z){let D=z[1]??"",$=z[2]??"";g(`${D}\u2022 ${di($,o)}`,n,h());continue}let J=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(J){let D=J[1]??"",$=J[2]??"",W=J[3]??"";g(`${D}${$}. ${di(W,o)}`,n,h());continue}let X=b.trim()==="";g(di(b,o),n,X?" ":h())}for(l&&y();d.length>0&&d[d.length-1].body==="";)d.pop();return d}function gr(t,e){return Op(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function zd(t){return Op(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function ci(t){let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())}function tI(t){if(!t.includes("|"))return!1;let e=ci(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Xo(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Zo(e)}function rI(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:Zo(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:Xo(r)}),n=i}return e}function iI(t,e){let n=[],s="",r=0;for(let i of t){let o=Zo(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function oI(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let d=iI(o.text,e);for(let l=0;l<d.length-1;l++)n.push(d[l]);let c=d[d.length-1]??"";s=c,r=Zo(c)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function aI(t,e){let n=t.length;if(t.reduce((l,f)=>l+f,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,Fp)),i=r.reduce((l,f)=>l+f,0);if(i>=e)return r;let o=e-i,a=t.map((l,f)=>({i:f,slack:Math.max(0,l-r[f])})).filter(l=>l.slack>0),d=a.reduce((l,f)=>l+f.slack,0);if(d===0)return r;for(let l of a){let f=Math.floor(o*l.slack/d);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let c=e-i;for(;c>0;){let l=-1,f=0;for(let u=0;u<n;u++){let p=t[u]-r[u];p>f&&(f=p,l=u)}if(l<0)break;r[l]=r[l]+1,c--}return r}function dI(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let c=0;c<s;c++)r[c]=Xo(t[c]??"");for(let c of e)for(let l=0;l<s;l++){let f=c[l]??"",u=Xo(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let c=Math.max(s*Fp,n-nI-(s-1)*sI);i=aI(r,c)}let o=(c,l,f)=>{let u=[],p=1;for(let h=0;h<s;h++){let y=c[h]??"",v=i[h],b=oI(rI(y),v);u.push(b),b.length>p&&(p=b.length)}let g=[];for(let h=0;h<p;h++){let y=[];for(let v=0;v<s;v++){let b=u[v][h]??"",x=i[v],C=Xo(b),F=di(b,f);y.push(F+" ".repeat(Math.max(0,x-C)))}g.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return g},a=[];a.push(...o(t,"heading-3",_p("heading-3")));let d=[];for(let c=0;c<s;c++)d.push("\u2500".repeat(i[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let c of e)a.push(...o(c,"agent"));return a}function lI(t,e){if(t.length===0||!eI(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=Zv(e.join(`
133
- `),{language:t,theme:cI,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
134
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function Wd(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
135
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let d of o){let c={prefix:e,prefixStyle:s??n,body:d,bodyStyle:n};i&&(c.fillRow=!0),a.push(c)}return a}function uI(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function sn(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function li(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;if(s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`,t.detail){let d=t.detail,c=o.toLowerCase(),l=d.toLowerCase();(l.startsWith(`${c} `)||l.startsWith(`${c} `))&&(d=d.slice(o.length).trimStart()),d.length>0&&!o.includes(d)&&(o=`${o} \xB7 ${d}`)}if(t.startedAt!==void 0){let d=t.endedAt??e;o=`${o} \xB7 ${sn(d-t.startedAt)}`}let a=[{prefix:` ${hI(t.status)} `,prefixStyle:gI(t.status),body:o,bodyStyle:II(t.status)}];return t.status==="failed"&&t.errorText&&a.push({prefix:" ",body:Ce(t.errorText),bodyStyle:"tool-status-fail"}),a}function Bp(t){Lp=t>=0?t:0}function Jd(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let c=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${uI(c)})`}else{let c=pI(t),l=[];c.added>0&&l.push(`+${c.added}`),c.removed>0&&l.push(`-${c.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=c=>({prefix:" ",body:`${c?"\u25BE":"\u25B8"} Edited ${Ce(Be(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=Kd(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let d="```diff\n"+a+"\n```";return s.push(...gr(d)),s.length>0&&s.unshift({body:""}),s}function Np(t){let e=mt(t.oldText).split(`
136
- `),n=mt(t.newText).split(`
137
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function pI(t){let{oldLines:e,newLines:n}=Np(t),s=0,r=0;for(let i of Dp(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function $p(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Kd(t,e={}){let n=e.maxLines??fI,s=e.contextLines??Lp,{oldLines:r,newLines:i}=Np(t),o=Dp(r,i),a=[];if(Number.isFinite(s)){if(!o.some(u=>u.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let u=0;u<o.length;u++)if(o[u].op!=="="){let p=Math.max(0,u-s),g=Math.min(o.length-1,u+s);for(let h=p;h<=g;h++)l[h]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push($p(o[f])),f++;continue}let u=f;for(;u<o.length&&!l[u];)u++;let p=u-f;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),f=u}}else for(let c of o)a.push($p(c));let d=[];for(let c=0;c<a.length;c++){if(d.length>=n-1&&c<a.length-1){let f=a.length-c;d.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}d.push(a[c])}return d.join(`
138
- `)}function Dp(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...mI(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function mI(t,e){let n=t.length,s=e.length;if(n===0||s===0){let d=[];for(let c of t)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let d=n-1;d>=0;d--)for(let c=s-1;c>=0;c--)t[d]===e[c]?r[d][c]=r[d+1][c+1]+1:r[d][c]=Math.max(r[d+1][c],r[d][c+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Hp(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function hI(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function gI(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function Up(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...gr(t.plan));let n=t.status;if(n!==void 0){let s=yI(n);s!==null&&e.push(s)}return e}function yI(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function bI(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(c=>(c.status??"pending")==="in_progress"),r=t.findIndex(c=>(c.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),d=Math.min(n,a+e);return d-a<e&&(a=Math.max(0,d-e)),{start:a,end:d}}function vI(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:d,end:c}=bI(t.entries,e),l=c-d<a,f="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let g=a-p;f=g===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${g} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=d;p<c;p++){let g=t.entries[p];if(!g)continue;let h=g.status??"pending",y=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",v=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=g.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,"");u.push({prefix:" ",body:`${y} ${b}`,bodyStyle:v})}return u}function II(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var Fp,nI,sI,Le,cI,fI,Lp,wI,yr=V(()=>{"use strict";ue();Un();Fp=6,nI=2,sI=3;Le=new Xv.Instance({level:3}),cI={keyword:Le.blueBright,built_in:Le.cyan,type:Le.cyanBright,literal:Le.blue,number:Le.greenBright,string:Le.yellow,regexp:Le.red,comment:Le.gray,function:Le.yellow,title:Le.yellow,class:Le.yellowBright,attr:Le.cyan,attribute:Le.cyan,variable:Le.white,params:Le.white,meta:Le.magenta,symbol:Le.magenta,addition:Le.greenBright,deletion:Le.redBright,section:Le.cyan,tag:Le.cyan,name:Le.cyanBright};fI=40,Lp=Number.POSITIVE_INFINITY;wI=5});import{highlight as SI,supportsLanguage as kI}from"cli-highlight";async function qp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
139
- `),process.exit(2));let n=await G(),s=await de(),r=fe(n.daemon.host,n.daemon.port,!!n.daemon.tls),i=new URL(`${r}/v1/sessions/${encodeURIComponent(t)}/diff`);e.fold===!0&&i.searchParams.set("fold","true");let o=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s}`}}),a;if(o.ok)a=await o.json();else if(o.status===404){let f=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export`,{headers:{Authorization:`Bearer ${s}`}});if(!f.ok){let h=await f.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${f.status}: ${h}
140
- `),process.exit(1)}let u=await f.json(),p;try{p=Ut(u)}catch(h){process.stderr.write(`Failed to decode session bundle: ${h.message}
141
- `),process.exit(1)}let g=sr(p.history);a=e.fold===!0?g.map(h=>({...h,hunks:rr(h.hunks)})):g}else{let f=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${f}
129
+ `)}function Yv(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Cp(t,443);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Cp(e.daemon.publicHost,443);return{host:n,port:s,isFallback:!1}}return gn(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function Cp(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}var In=V(()=>{"use strict";Oe();mt();Ks();Wr();nn();ui();bs();Od();Zo()});import{spawn as Qv}from"child_process";import{Writable as Gv}from"stream";function ea(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=Xv(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??Qv,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
130
+ `)});let d=new Gv({write(l,u,f){if(!a.writable){f();return}a.write(l,g=>{if(g&&g.code!=="EPIPE"){f(g);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});d.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
131
+ `)});let c=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:d,flush:async()=>{a.writable&&await new Promise(l=>{d.end(()=>l())}),await c}}}function Xv(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var Jd=V(()=>{"use strict"});import Zv from"chalk";import{highlight as eI,supportsLanguage as tI}from"cli-highlight";import na from"string-width";function on(t,e={}){switch(t.kind){case"user-text":{let n=Kd(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return Kd(t.text," ","agent");case"agent-thought":return Kd(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return II(t,e.maxPlanItems??bI);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function pi(t,e){let n=e?.codeOpen??"^C",s=e?.boldReset??"^:",r=e?.codeReset??"^:",i=t.replace(/\^/g,"^^");return i=i.replace(/\*\*(.+?)\*\*/g,`^+$1${s}`),i=i.replace(/`([^`]+)`/g,`${n}$1${r}`),i}function Lp(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function Bp(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,d=[],c=t.replace(/^\s+/,"").split(`
132
+ `),l=!1,u="",f=[],p=i!==" ",g=(I,b,x=" ")=>{let M={prefix:x,body:I,bodyStyle:b};r!==void 0&&(M.prefixStyle=r),d.push(M)},h=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let I=uI(u,f);for(let b of I){let x={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(x.prefixStyle=r),b.ansi&&(x.ansi=!0),d.push(x)}}else for(let I of f)g(I.replace(/\^/g,"^^"),n);f=[],u=""}};for(let I=0;I<c.length;I++){let b=c[I],x=b.match(/^\s*```\s*(\w*)\s*$/);if(x){l?(y(),l=!1):(l=!0,u=x[1]??"");continue}if(l){f.push(b);continue}let M=b.match(/^(#{1,6})\s+(.*)$/);if(M){let $=M[1].length,D=M[2]??"",j=s?$===1?"heading-1":$===2?"heading-2":"heading-3":n,Z=s?Lp(j):o;g(pi(D,Z),j,h());continue}let _=c[I+1];if(b.includes("|")&&_!==void 0&&nI(_)&&mi(b).length===mi(_).length){let $=mi(b),D=[],j=I+2;for(;j<c.length&&c[j].includes("|");)D.push(mi(c[j])),j++;let Z=cI($,D,a);for(let ie of Z)r!==void 0&&(ie.prefixStyle=r),d.push(ie);I=j-1;continue}let Q=b.match(/^(\s*)[-*+]\s+(.*)$/);if(Q){let $=Q[1]??"",D=Q[2]??"";g(`${$}\u2022 ${pi(D,o)}`,n,h());continue}let W=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(W){let $=W[1]??"",D=W[2]??"",j=W[3]??"";g(`${$}${D}. ${pi(j,o)}`,n,h());continue}let z=b.trim()==="";g(pi(b,o),n,z?" ":h())}for(l&&y();d.length>0&&d[d.length-1].body==="";)d.pop();return d}function Ir(t,e){return Bp(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Vd(t){return Bp(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function mi(t){let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())}function nI(t){if(!t.includes("|"))return!1;let e=mi(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function ta(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return na(e)}function iI(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:na(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:ta(r)}),n=i}return e}function oI(t,e){let n=[],s="",r=0;for(let i of t){let o=na(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function aI(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let d=oI(o.text,e);for(let l=0;l<d.length-1;l++)n.push(d[l]);let c=d[d.length-1]??"";s=c,r=na(c)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function dI(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,Np)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),d=a.reduce((l,u)=>l+u.slack,0);if(d===0)return r;for(let l of a){let u=Math.floor(o*l.slack/d);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let c=e-i;for(;c>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,c--}return r}function cI(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let c=0;c<s;c++)r[c]=ta(t[c]??"");for(let c of e)for(let l=0;l<s;l++){let u=c[l]??"",f=ta(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let c=Math.max(s*Np,n-sI-(s-1)*rI);i=dI(r,c)}let o=(c,l,u)=>{let f=[],p=1;for(let h=0;h<s;h++){let y=c[h]??"",I=i[h],b=aI(iI(y),I);f.push(b),b.length>p&&(p=b.length)}let g=[];for(let h=0;h<p;h++){let y=[];for(let I=0;I<s;I++){let b=f[I][h]??"",x=i[I],M=ta(b),_=pi(b,u);y.push(_+" ".repeat(Math.max(0,x-M)))}g.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return g},a=[];a.push(...o(t,"heading-3",Lp("heading-3")));let d=[];for(let c=0;c<s;c++)d.push("\u2500".repeat(i[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let c of e)a.push(...o(c,"agent"));return a}function uI(t,e){if(t.length===0||!tI(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=eI(e.join(`
133
+ `),{language:t,theme:lI,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
134
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function Kd(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
135
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let d of o){let c={prefix:e,prefixStyle:s??n,body:d,bodyStyle:n};i&&(c.fillRow=!0),a.push(c)}return a}function fI(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function an(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function hi(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;if(s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`,t.detail){let d=t.detail,c=o.toLowerCase(),l=d.toLowerCase();(l.startsWith(`${c} `)||l.startsWith(`${c} `))&&(d=d.slice(o.length).trimStart()),d.length>0&&!o.includes(d)&&(o=`${o} \xB7 ${d}`)}if(t.startedAt!==void 0){let d=t.endedAt??e;o=`${o} \xB7 ${an(d-t.startedAt)}`}let a=[{prefix:` ${gI(t.status)} `,prefixStyle:yI(t.status),body:o,bodyStyle:SI(t.status)}];return t.status==="failed"&&t.errorText&&a.push({prefix:" ",body:Ae(t.errorText),bodyStyle:"tool-status-fail"}),a}function Hp(t){Dp=t>=0?t:0}function Yd(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let c=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${fI(c)})`}else{let c=mI(t),l=[];c.added>0&&l.push(`+${c.added}`),c.removed>0&&l.push(`-${c.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=c=>({prefix:" ",body:`${c?"\u25BE":"\u25B8"} Edited ${Ae(Ne(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=Qd(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let d="```diff\n"+a+"\n```";return s.push(...Ir(d)),s.length>0&&s.unshift({body:""}),s}function Up(t){let e=gt(t.oldText).split(`
136
+ `),n=gt(t.newText).split(`
137
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function mI(t){let{oldLines:e,newLines:n}=Up(t),s=0,r=0;for(let i of jp(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Fp(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Qd(t,e={}){let n=e.maxLines??pI,s=e.contextLines??Dp,{oldLines:r,newLines:i}=Up(t),o=jp(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),g=Math.min(o.length-1,f+s);for(let h=p;h<=g;h++)l[h]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(Fp(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let c of o)a.push(Fp(c));let d=[];for(let c=0;c<a.length;c++){if(d.length>=n-1&&c<a.length-1){let u=a.length-c;d.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}d.push(a[c])}return d.join(`
138
+ `)}function jp(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...hI(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function hI(t,e){let n=t.length,s=e.length;if(n===0||s===0){let d=[];for(let c of t)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let d=n-1;d>=0;d--)for(let c=s-1;c>=0;c--)t[d]===e[c]?r[d][c]=r[d+1][c+1]+1:r[d][c]=Math.max(r[d+1][c],r[d][c+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function qp(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function gI(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function yI(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function Wp(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ir(t.plan));let n=t.status;if(n!==void 0){let s=wI(n);s!==null&&e.push(s)}return e}function wI(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function vI(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(c=>(c.status??"pending")==="in_progress"),r=t.findIndex(c=>(c.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),d=Math.min(n,a+e);return d-a<e&&(a=Math.max(0,d-e)),{start:a,end:d}}function II(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:d,end:c}=vI(t.entries,e),l=c-d<a,u="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let g=a-p;u=g===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${g} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=d;p<c;p++){let g=t.entries[p];if(!g)continue;let h=g.status??"pending",y=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",I=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=g.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,"");f.push({prefix:" ",body:`${y} ${b}`,bodyStyle:I})}return f}function SI(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var Np,sI,rI,Le,lI,pI,Dp,bI,Sr=V(()=>{"use strict";me();zn();Np=6,sI=2,rI=3;Le=new Zv.Instance({level:3}),lI={keyword:Le.blueBright,built_in:Le.cyan,type:Le.cyanBright,literal:Le.blue,number:Le.greenBright,string:Le.yellow,regexp:Le.red,comment:Le.gray,function:Le.yellow,title:Le.yellow,class:Le.yellowBright,attr:Le.cyan,attribute:Le.cyan,variable:Le.white,params:Le.white,meta:Le.magenta,symbol:Le.magenta,addition:Le.greenBright,deletion:Le.redBright,section:Le.cyan,tag:Le.cyan,name:Le.cyanBright};pI=40,Dp=Number.POSITIVE_INFINITY;bI=5});import{highlight as kI,supportsLanguage as xI}from"cli-highlight";async function Jp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
139
+ `),process.exit(2));let n=await G(),s=await fe(),r=he(n.daemon.host,n.daemon.port,!!n.daemon.tls),i=new URL(`${r}/v1/sessions/${encodeURIComponent(t)}/diff`);e.fold===!0&&i.searchParams.set("fold","true");let o=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s}`}}),a;if(o.ok)a=await o.json();else if(o.status===404){let u=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export`,{headers:{Authorization:`Bearer ${s}`}});if(!u.ok){let h=await u.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${u.status}: ${h}
140
+ `),process.exit(1)}let f=await u.json(),p;try{p=qt(f)}catch(h){process.stderr.write(`Failed to decode session bundle: ${h.message}
141
+ `),process.exit(1)}let g=dr(p.history);a=e.fold===!0?g.map(h=>({...h,hunks:cr(h.hunks)})):g}else{let u=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${u}
142
142
  `),process.exit(1)}if(e.json){process.stdout.write(JSON.stringify(a,null,2)+`
143
- `);return}let d=Go({disabled:e.noPager===!0}),c=process.stdout.isTTY===!0,l=!e.noColor&&c;d.stream.write(Vd(a,l)),await d.flush()}function Vd(t,e){if(t.length===0)return`No file edits found in this session.
144
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=CI(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
145
- `:n.join("")}function xI(t){let e=[];for(let n of t.hunks){let s=Kd(n,{maxLines:1/0});AI(s)&&e.push({body:s,oldCount:jp(n.oldText),newCount:jp(n.newText)})}return e}function AI(t){if(t.length===0)return!1;for(let e of t.split(`
146
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function CI(t,e){let n=xI(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let d=o.oldCount===0?0:1,c=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${d},${o.oldCount} +${c},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
143
+ `);return}let d=ea({disabled:e.noPager===!0}),c=process.stdout.isTTY===!0,l=!e.noColor&&c;d.stream.write(Gd(a,l)),await d.flush()}function Gd(t,e){if(t.length===0)return`No file edits found in this session.
144
+ `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=RI(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
145
+ `:n.join("")}function AI(t){let e=[];for(let n of t.hunks){let s=Qd(n,{maxLines:1/0});CI(s)&&e.push({body:s,oldCount:zp(n.oldText),newCount:zp(n.newText)})}return e}function CI(t){if(t.length===0)return!1;for(let e of t.split(`
146
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function RI(t,e){let n=AI(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let d=o.oldCount===0?0:1,c=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${d},${o.oldCount} +${c},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
147
147
  `)+`
148
148
 
149
- `;return!e||!kI("diff")?i:SI(i,{language:"diff"})}function jp(t){if(t.length===0)return 0;let e=t.split(`
150
- `);return e[e.length-1]===""&&e.pop(),e.length}var Yd=V(()=>{"use strict";Oe();ft();hs();_o();yr();qd();wn()});import*as NE from"fs/promises";async function Wp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
151
- `),process.exit(2));let n=await G(),s=await de(),r=fe(n.daemon.host,n.daemon.port,!!n.daemon.tls),i=await fetch(`${r}/v1/sessions`,{headers:{Authorization:`Bearer ${s}`}});i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
149
+ `;return!e||!xI("diff")?i:kI(i,{language:"diff"})}function zp(t){if(t.length===0)return 0;let e=t.split(`
150
+ `);return e[e.length-1]===""&&e.pop(),e.length}var Xd=V(()=>{"use strict";Oe();mt();bs();Lo();Sr();Jd();In()});import*as DE from"fs/promises";async function Kp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
151
+ `),process.exit(2));let n=await G(),s=await fe(),r=he(n.daemon.host,n.daemon.port,!!n.daemon.tls),i=await fetch(`${r}/v1/sessions`,{headers:{Authorization:`Bearer ${s}`}});i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
152
152
  `),process.exit(1));let a=(await i.json()).sessions.find(y=>y.sessionId===t)?.status,d=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export`,{headers:{Authorization:`Bearer ${s}`}});if(!d.ok){let y=await d.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${d.status}: ${y}
153
- `),process.exit(1)}let c=await d.json(),l;try{l=Ut(c)}catch(y){process.stderr.write(`Failed to decode session bundle: ${y.message}
154
- `),process.exit(1)}let f=Xd(l,a??"cold"),u=e.diff===!0,p=null;if(u){let y=sr(l.history);p=e.fold===!0?y.map(v=>({...v,hunks:rr(v.hunks)})):y}if(e.json){let y={...f};p!==null&&(y.diff=p),process.stdout.write(JSON.stringify(y,null,2)+`
155
- `);return}let g=process.stdout.isTTY===!0,h=!e.noColor&&g;if(u){let y=Go({disabled:e.noPager===!0});y.stream.write(ea(f,e.verbose===!0)),y.stream.write(`
156
- `),y.stream.write(Vd(p??[],h)),await y.flush();return}process.stdout.write(ea(f,e.verbose===!0))}function Xd(t,e){let n=t.session,s=t.history,r=Hu(s),i=md(s),o=hd(s),a=n.currentUsage,d=Date.parse(n.createdAt),c=Date.parse(n.updatedAt),l=Number.isFinite(d)&&Number.isFinite(c)?c-d:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function ea(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${TI(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",d=c=>c.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${d("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${d("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${d("Rejected approaches:")}`);for(let c of t.synopsis.rejected_approaches)n.push(`${a} - ${c}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${d("Open threads:")}`);for(let c of t.synopsis.open_threads)n.push(`${a} - ${c}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,f)=>l+f.count,0);n.push(`Tools (${a} calls):`);let d=e?t.tools:t.tools.slice(0,Qd),c=Math.max(...d.map(l=>l.name.length),4);for(let l of d)n.push(` ${l.name.padEnd(c)} ${l.count}`);!e&&t.tools.length>Qd&&n.push(` ... ${t.tools.length-Qd} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let d=a.byTool.filter(l=>RI.has(l.name)),c=d.reduce((l,f)=>l+f.count,0);return{path:a.path,count:c,byTool:d}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let d=e?o:o.slice(0,Gd),c=Math.max(...d.map(l=>l.path.length),4);for(let l of d)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(c)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(c)} ${l.count}`);!e&&o.length>Gd&&n.push(` ... ${o.length-Gd} more (use --verbose to see all)`)}return n.join(`
153
+ `),process.exit(1)}let c=await d.json(),l;try{l=qt(c)}catch(y){process.stderr.write(`Failed to decode session bundle: ${y.message}
154
+ `),process.exit(1)}let u=tc(l,a??"cold"),f=e.diff===!0,p=null;if(f){let y=dr(l.history);p=e.fold===!0?y.map(I=>({...I,hunks:cr(I.hunks)})):y}if(e.json){let y={...u};p!==null&&(y.diff=p),process.stdout.write(JSON.stringify(y,null,2)+`
155
+ `);return}let g=process.stdout.isTTY===!0,h=!e.noColor&&g;if(f){let y=ea({disabled:e.noPager===!0});y.stream.write(sa(u,e.verbose===!0)),y.stream.write(`
156
+ `),y.stream.write(Gd(p??[],h)),await y.flush();return}process.stdout.write(sa(u,e.verbose===!0))}function tc(t,e){let n=t.session,s=t.history,r=qu(s),i=yd(s),o=wd(s),a=n.currentUsage,d=Date.parse(n.createdAt),c=Date.parse(n.updatedAt),l=Number.isFinite(d)&&Number.isFinite(c)?c-d:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function sa(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${EI(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",d=c=>c.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${d("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${d("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${d("Rejected approaches:")}`);for(let c of t.synopsis.rejected_approaches)n.push(`${a} - ${c}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${d("Open threads:")}`);for(let c of t.synopsis.open_threads)n.push(`${a} - ${c}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let d=e?t.tools:t.tools.slice(0,Zd),c=Math.max(...d.map(l=>l.name.length),4);for(let l of d)n.push(` ${l.name.padEnd(c)} ${l.count}`);!e&&t.tools.length>Zd&&n.push(` ... ${t.tools.length-Zd} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let d=a.byTool.filter(l=>TI.has(l.name)),c=d.reduce((l,u)=>l+u.count,0);return{path:a.path,count:c,byTool:d}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let d=e?o:o.slice(0,ec),c=Math.max(...d.map(l=>l.path.length),4);for(let l of d)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(c)} ${l.count} (${u})`)}else n.push(` ${l.path.padEnd(c)} ${l.count}`);!e&&o.length>ec&&n.push(` ... ${o.length-ec} more (use --verbose to see all)`)}return n.join(`
157
157
  `)+`
158
- `}function TI(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var Qd,Gd,RI,Zd=V(()=>{"use strict";Oe();ft();hs();gd();_o();qd();Yd();wn();Qd=10,Gd=15,RI=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});import{setTimeout as DI}from"timers/promises";import{WebSocket as HI}from"ws";function zI(t){return!("method"in t)&&"id"in t&&t.id!==void 0}async function JI(t,e){return new Promise((n,s)=>{let r=new HI(t,e),i=()=>{r.off("error",o),n(qn(r))},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}var UI,jI,qI,WI,vr,oc=V(()=>{"use strict";si();nt();UI=200,jI=5e3,qI=2,WI=60,vr=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current){this.outboundQueue.push(e);return}try{await this.current.send(e)}catch(n){this.outboundQueue.push(e),this.scheduleReconnect(n)}}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){this.destroyed=!0,this.current&&await this.current.close().catch(()=>{});for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=UI;for(;!this.destroyed;)try{let s=await JI(this.opts.url,this.opts.subprotocols);this.bindStream(s);let r=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(i=>{this.releaseConnectGate=i});try{if(this.opts.onConnect)try{await this.opts.onConnect(r)}catch(i){this.log(`hydra-acp: post-connect handler failed: ${i.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=WI)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await DI(n),n=Math.min(n*qI,jI)}}bindStream(e){this.current=e,e.onMessage(n=>{if(zI(n)){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}async flushQueue(){if(!this.current)return;let e=this.outboundQueue;this.outboundQueue=[];for(let n of e)try{await this.current.send(n)}catch(s){this.outboundQueue.unshift(n),this.scheduleReconnect(s);return}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
159
- `)}}});function Am(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let r of e){let i=n.find(o=>typeof o=="object"&&o!==null&&o.kind===r&&typeof o.optionId=="string");if(i?.optionId!==void 0)return i.optionId}let s=n.find(r=>typeof r=="object"&&r!==null&&typeof r.optionId=="string");if(s?.optionId!==void 0)return s.optionId}return e[0]??"allow"}function ws(t){return{outcome:{outcome:"selected",optionId:Am(t,["allow_once","allow_always"])}}}function Cm(t){return{outcome:{outcome:"selected",optionId:Am(t,["reject_once","reject_always"])}}}function ia(t){return t&&typeof t=="object"?t:void 0}function ui(t){return typeof t=="string"&&t.length>0?t:void 0}function Rm(t){let e=ia(t),n=ia(e?.toolCall),s={paths:[]};if(!n)return s;let r=ui(n.kind);r&&(s.kind=r);let i=new Set,o=c=>{let l=ui(c);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let c of a)o(ia(c)?.path);let d=ia(n.rawInput);if(d){o(d.file_path),o(d.filePath),o(d.path);let c=ui(d.command);c&&(s.command=c);let l=ui(d.url);l&&(s.url=l);let f=ui(d.description);f&&(s.description=f)}return s}function Tm(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var oa=V(()=>{"use strict"});function JS(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Hm(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function KS(t,e){let n=Hm(t),s=Hm(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function fi(){if(Vn!==void 0)return Vn;if(JS())return Vn=null,Vn;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Um,version:ce}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&KS(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Vn={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Vn=null}}catch{Vn=null}return Vn}function pi(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Um}`}var Um,Vn,cc=V(()=>{"use strict";$t();Um="@hydra-acp/cli"});import*as mi from"fs/promises";import*as lc from"path";async function hi(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=lc.resolve(Dt(e)),s;try{s=await mi.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function jm(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await mi.stat(r)).isDirectory())return r}catch{}return null}async function qm(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=lc.resolve(Dt(r)),o;try{o=(await mi.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),d=o.filter(c=>c.name.startsWith(s)).filter(c=>a||!c.name.startsWith(".")).map(c=>c.isDir?`${c.name}/`:c.name).sort();return{prefix:n,basePrefix:s,matches:d}}var uc=V(()=>{"use strict";Oe()});import{EventEmitter as VS}from"events";import{WebSocket as YS}from"ws";function QS(t,e){return new Promise((n,s)=>{let r=new YS(t,e),i=()=>{r.off("error",o),n(qn(r))},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}function Wm(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??QS,d=["acp.v1",`hydra-acp-token.${t.token}`],c=await a(t.wsUrl,d),l=new Mt(c),f;try{try{await l.request("initialize",{protocolVersion:tt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}let h=n.replace(/\s+/g," ").trim().slice(0,60);f=(await Jo(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}catch(h){throw c.close().catch(()=>{}),h}let u=new fc(l,c,f,t,o),p=!1,g=h=>{p||(p=!0,u.emit("event",h),c.close().catch(()=>{}))};l.onNotification("session/update",h=>{let y=h?.update;y!==void 0&&u.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||g({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw c.close().catch(()=>{}),ii(t,f,o).catch(()=>{}),h}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[pt]:{ancillary:!0}}}).then(h=>{let y=h&&typeof h=="object"?h.stopReason:void 0;g(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{g({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var fc,zm=V(()=>{"use strict";oi();Ks();si();nt();fc=class extends VS{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),ii(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var pc,la,Jm=V(()=>{"use strict";yr();Un();pc=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},la=class extends pc{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_emitChanged;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0}append(e){let n=gn(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=nn({kind:"agent-text",text:this._pendingAgentText});return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=nn(n),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=li(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=li(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=nn(n);return this._pushLines(s),s.length}}}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0)for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function XS(t,e){return`[pasted #${t} +${e} lines]`}var GS,ua,mc,vn,hc=V(()=>{"use strict";GS=/\[pasted #(\d+) \+\d+ lines\]/g,ua=/\[pasted #(\d+) \+\d+ lines\]$/,mc=/^\[pasted #(\d+) \+\d+ lines\]/;vn=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:[...this.attachments],historySearchQuery:this.historySearch?.query??null}}addAttachment(e){this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||this.attachments.splice(e,1)}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n]}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.insertChar(e.ch),[];if(e.type==="paste"){let n=e.text.split(`
160
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(XS(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.insertNewline(),[];case"shift-tab":return this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.moveLeft(),[];case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"backspace":return this.backspace(),[];case"delete":return this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.yank(),[];case"escape":return this.turnRunning?[{type:"cancel",prefill:!0}]:[]}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
161
- `)}expandPastes(e){return e.replace(GS,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[]}insertChar(e){if(e.length===0)return;if(e.includes(`
158
+ `}function EI(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var Zd,ec,TI,nc=V(()=>{"use strict";Oe();mt();bs();bd();Lo();Jd();Xd();In();Zd=10,ec=15,TI=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});import{setTimeout as HI}from"timers/promises";import{WebSocket as UI}from"ws";function JI(t){return!("method"in t)&&"id"in t&&t.id!==void 0}async function KI(t,e){return new Promise((n,s)=>{let r=new UI(t,e),i=()=>{r.off("error",o),n(Kn(r))},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}var jI,qI,WI,zI,Ar,cc=V(()=>{"use strict";ci();st();jI=200,qI=5e3,WI=2,zI=60,Ar=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current){this.outboundQueue.push(e);return}try{await this.current.send(e)}catch(n){this.outboundQueue.push(e),this.scheduleReconnect(n)}}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){this.destroyed=!0,this.current&&await this.current.close().catch(()=>{});for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=jI;for(;!this.destroyed;)try{let s=await KI(this.opts.url,this.opts.subprotocols);this.bindStream(s);let r=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(i=>{this.releaseConnectGate=i});try{if(this.opts.onConnect)try{await this.opts.onConnect(r)}catch(i){this.log(`hydra-acp: post-connect handler failed: ${i.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=zI)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await HI(n),n=Math.min(n*WI,qI)}}bindStream(e){this.current=e,e.onMessage(n=>{if(JI(n)){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}async flushQueue(){if(!this.current)return;let e=this.outboundQueue;this.outboundQueue=[];for(let n of e)try{await this.current.send(n)}catch(s){this.outboundQueue.unshift(n),this.scheduleReconnect(s);return}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
159
+ `)}}});function Tm(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let r of e){let i=n.find(o=>typeof o=="object"&&o!==null&&o.kind===r&&typeof o.optionId=="string");if(i?.optionId!==void 0)return i.optionId}let s=n.find(r=>typeof r=="object"&&r!==null&&typeof r.optionId=="string");if(s?.optionId!==void 0)return s.optionId}return e[0]??"allow"}function Ss(t){return{outcome:{outcome:"selected",optionId:Tm(t,["allow_once","allow_always"])}}}function Em(t){return{outcome:{outcome:"selected",optionId:Tm(t,["reject_once","reject_always"])}}}function da(t){return t&&typeof t=="object"?t:void 0}function gi(t){return typeof t=="string"&&t.length>0?t:void 0}function Pm(t){let e=da(t),n=da(e?.toolCall),s={paths:[]};if(!n)return s;let r=gi(n.kind);r&&(s.kind=r);let i=new Set,o=c=>{let l=gi(c);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let c of a)o(da(c)?.path);let d=da(n.rawInput);if(d){o(d.file_path),o(d.filePath),o(d.path);let c=gi(d.command);c&&(s.command=c);let l=gi(d.url);l&&(s.url=l);let u=gi(d.description);u&&(s.description=u)}return s}function Mm(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var ca=V(()=>{"use strict"});function KS(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function qm(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function VS(t,e){let n=qm(t),s=qm(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function yi(){if(Xn!==void 0)return Xn;if(KS())return Xn=null,Xn;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Wm,version:pe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&VS(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Xn={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Xn=null}}catch{Xn=null}return Xn}function wi(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Wm}`}var Wm,Xn,fc=V(()=>{"use strict";Mt();Wm="@hydra-acp/cli"});import*as bi from"fs/promises";import*as pc from"path";async function vi(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=pc.resolve(Ut(e)),s;try{s=await bi.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function zm(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await bi.stat(r)).isDirectory())return r}catch{}return null}async function Jm(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=pc.resolve(Ut(r)),o;try{o=(await bi.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),d=o.filter(c=>c.name.startsWith(s)).filter(c=>a||!c.name.startsWith(".")).map(c=>c.isDir?`${c.name}/`:c.name).sort();return{prefix:n,basePrefix:s,matches:d}}var mc=V(()=>{"use strict";Oe()});import{EventEmitter as YS}from"events";import{WebSocket as QS}from"ws";function GS(t,e){return new Promise((n,s)=>{let r=new QS(t,e),i=()=>{r.off("error",o),n(Kn(r))},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}function Km(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??GS,d=["acp.v1",`hydra-acp-token.${t.token}`],c=await a(t.wsUrl,d),l=new Pt(c),u;try{try{await l.request("initialize",{protocolVersion:nt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)u=s.reuseSessionId;else{let h=n.replace(/\s+/g," ").trim().slice(0,60);u=(await Yo(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}}catch(h){throw c.close().catch(()=>{}),h}let f=new hc(l,c,u,t,o),p=!1,g=h=>{p||(p=!0,f.emit("event",h),c.close().catch(()=>{}))};l.onNotification("session/update",h=>{let y=h?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||g({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw c.close().catch(()=>{}),rn(t,u,o).catch(()=>{}),h}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[ht]:{ancillary:!0}}}).then(h=>{let y=h&&typeof h=="object"?h.stopReason:void 0;g(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{g({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var hc,Vm=V(()=>{"use strict";ui();Xs();ci();st();hc=class extends YS{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),rn(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var gc,pa,Ym=V(()=>{"use strict";Sr();zn();gc=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},pa=class extends gc{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_emitChanged;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0}append(e){let n=bn(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=on({kind:"agent-text",text:this._pendingAgentText});return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=on(n),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=hi(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=hi(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=on(n);return this._pushLines(s),s.length}}}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0)for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function ZS(t,e){return`[pasted #${t} +${e} lines]`}var XS,ma,yc,kn,wc=V(()=>{"use strict";XS=/\[pasted #(\d+) \+\d+ lines\]/g,ma=/\[pasted #(\d+) \+\d+ lines\]$/,yc=/^\[pasted #(\d+) \+\d+ lines\]/;kn=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:[...this.attachments],historySearchQuery:this.historySearch?.query??null}}addAttachment(e){this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||this.attachments.splice(e,1)}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n]}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.insertChar(e.ch),[];if(e.type==="paste"){let n=e.text.split(`
160
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(ZS(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.insertNewline(),[];case"shift-tab":return this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.moveLeft(),[];case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"backspace":return this.backspace(),[];case"delete":return this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.yank(),[];case"escape":return this.turnRunning?[{type:"cancel",prefill:!0}]:[]}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
161
+ `)}expandPastes(e){return e.replace(XS,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[]}insertChar(e){if(e.length===0)return;if(e.includes(`
162
162
  `)){this.insertText(e);return}let n=this.currentLine();this.setCurrentLine(n.slice(0,this.col)+e+n.slice(this.col)),this.col+=e.length}insertText(e){let n=e.split(`
163
- `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",d=n.slice(1,-1);this.setCurrentLine(r+o);let c=[...d,a+i];this.buffer.splice(this.row+1,0,...c),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(ua);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(mc);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
163
+ `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",d=n.slice(1,-1);this.setCurrentLine(r+o);let c=[...d,a+i];this.buffer.splice(this.row+1,0,...c),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(ma);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(yc);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
164
164
  `,this.buffer.splice(this.row,1),this.row-=1,this.col=this.currentLine().length;return}let e=this.buffer[this.row-1]??"";this.killBuffer=e+`
165
165
  `,this.buffer.splice(this.row-1,1),this.row-=1}killToEnd(){let e=this.currentLine();if(this.col<e.length){this.killBuffer=e.slice(this.col),this.setCurrentLine(e.slice(0,this.col));return}if(this.row>=this.buffer.length-1)return;if(e.length===0){this.killBuffer=`
166
166
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
167
- `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(ua);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(ua);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(mc);if(s!==null){this.col+=s[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(ua);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(mc);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
168
- `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],d=n.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});import ZS from"path";function gi(t){return Km[ZS.extname(t).toLowerCase()]??null}function ek(t){return gi(t)!==null}function gc(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!tk.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function nk(t){return gc(t)!==null}function Ft(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Vm(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!nk(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!ek(o))return null;n.push(o)}return n.length>0?n:null}var rn,Km,tk,fa=V(()=>{"use strict";rn=10*1024*1024,Km={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};tk=new Set(Object.values(Km))});import sk from"string-width";function Ym(t,e){if(!t||e<=0)return 0;let n=0;for(let s of rk.segment(t)){let r=sk(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Qm(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var rk,Gm=V(()=>{"use strict";rk=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as ik}from"child_process";import yc from"fs/promises";import ok from"os";import ak from"path";async function eh(t={}){let e={...wc,...t};return e.platform==="darwin"?uk(e):e.platform==="linux"?fk(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function th(t={}){let e={...wc,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await kr(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await kr(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await yi(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:bc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function nh(t,e={}){let{target:n="both",...s}=e,r={...wc,...s},i=await dk(r,t,n);if(i.ok)return i;let o=ck(r,t,n);return o.ok||o.reason!==sh?o:i}async function dk(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await pa(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await kr(t,"wl-copy")?Zm(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await kr(t,"xclip")?Zm(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function Zm(t,e,n,s,r,i,o){let a=n;if(i){try{await pa(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await pa(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await pa(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function ck(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Xm)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Xm} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??lk)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:sh}}function lk(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function uk(t){let e=ak.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await rh(t.spawn,"osascript",s);let r=await yk(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await yc.unlink(e).catch(()=>{})}try{let r=await yi(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:bc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function fk(t){let e=await pk(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await gk(t,e),s=hk(n);if(s)try{let r=await yi(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>rn?{ok:!1,reason:`clipboard image is ${Ft(r.length)}, max ${Ft(rn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await yi(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:bc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function pk(t){return t.env.WAYLAND_DISPLAY&&await kr(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await kr(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function hk(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of mk)if(e.has(n))return n;return null}async function gk(t,e){try{return(await yi(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
169
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function bc(t){return t.replace(/\r\n?/g,`
170
- `)}async function kr(t,e){try{return await rh(t.spawn,"which",[e]),!0}catch{return!1}}async function yk(t,e){try{let n=await yc.readFile(t);return e&&await yc.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>rn?{ok:!1,reason:`clipboard image is ${Ft(n.length)}, max ${Ft(rn)}`}:{ok:!0,kind:"image",attachment:{mimeType:gi(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function rh(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function pa(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${e} exited ${d}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function yi(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${d}`)))};i.stdout?.on("data",f=>{o.push(typeof f=="string"?Buffer.from(f):f)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",f=>{c||(c=!0,r(f))}),i.on("close",f=>{d=f??0,l()})})}var wc,Xm,sh,mk,vc=V(()=>{"use strict";fa();wc={platform:process.platform,env:process.env,spawn:ik,tmpdir:ok.tmpdir};Xm=74994;sh="no TTY available for OSC 52 clipboard write";mk=["image/png","image/jpeg","image/gif","image/webp"]});function wk(){wi===0&&process.stdout.write("\x1B[?2026h"),wi++}function bk(){wi!==0&&(wi--,wi===0&&process.stdout.write("\x1B[?2026l"))}function $e(t){wk();try{t()}finally{bk()}}var wi,Ic=V(()=>{"use strict";wi=0});import bi from"string-width";import vk from"wrap-ansi";function Ek(t){let e=t.replace(/\r\n?$|\n$/,"");return Tk.test(e)?e:null}function Pk(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function oh(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let d=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${d}`}function Sn(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let d=r[a];if(d===" "||d===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function Qn(t,e,n){let s=0,r=0,i=-1;for(let d=0;d<t.length;d++){let c=t[d];if(!(!c||c.bufferIdx!==e.row)&&(i=d,e.col>=c.startCol&&e.col<c.endCol)){s=d,r=e.col-c.startCol,i=-1;break}}if(i!==-1){let d=t[i];d&&(s=i,r=e.col-d.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function ah(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){In(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let d=o.indexOf(s,a);if(d===-1){In(t,e.slice(a),n);return}d>a&&In(t,e.slice(a,d),n);let c=r!==null&&d===r;In(t,e.slice(d,d+s.length),c?"search-highlight-active":"search-highlight"),a=d+s.length}}function ma(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"}function In(t,e,n){if(e.length!==0)switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.green.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow.noFormat(e);return;case"plan-done":t.green.noFormat(e);return;case"plan-pending":t.dim.noFormat(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}function Mk(t,e){return e<=0?[t]:t.length===0?[""]:vk(t,e,{hard:!0,trim:!1}).split(`
171
- `)}function mh(t){ph=t}function Yn(t){return bi(t,{ambiguousIsNarrow:!ph})}function wa(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return $k.test(n)?{text:t.slice(e,e+2),width:0}:null}function _k(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=wa(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function hh(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(wa(t,e))return!0;return!1}function*Ec(t){let e=0;for(;e<t.length;){let n=wa(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(wa(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Tc.segment(t.slice(e,s)))yield{text:i,width:Yn(i)};e=s}}function Ok(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function Fk(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&hh(t);return!s&&!fh.test(t)?Lk(t,e):Bk(t,e,s)}function Lk(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function Bk(t,e,n){let s=[],r=n?[...Ec(t)]:Nk(t),i=0;for(;i<r.length;){let o="",a=0,d=-1,c="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(d=i,c=o);break}l.text===" "&&l.width===1&&(d=i,c=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}d>=0?(s.push(c),i=d+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function Nk(t){let e=[];for(let{segment:n}of Tc.segment(t))e.push({text:n,width:Yn(n)});return e}function rt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&hh(t);if(!s&&t.length<=e&&!fh.test(t))return t;if(!s)return Yn(t)<=e?t:e<=1?dh(t,e):dh(t,e-1)+"\u2026";let r=[...Ec(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?ch(r,e):ch(r,e-1)+"\u2026"}function dh(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Tc.segment(t)){let i=Yn(r);if(s+i>e)break;n+=r,s+=i}return n}function ch(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function Dk(t){let e=t.indexOf(`
172
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Hk(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${ha(t.used)}/${ha(t.size)}`):e.push(ha(t.used)):typeof t.size=="number"&&e.push(`/${ha(t.size)}`),typeof t.costAmount=="number"&&e.push(Hd(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function ha(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function ba(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function ga(){let t=["\x1B[?1000l","\x1B[?1002l","\x1B[?1003l","\x1B[?1006l","\x1B[?1015l","\x1B[=0;0w","\x1B[?2004l","\x1B[>4;0m","\x1B[>5;0m","\x1B[<u","\x1B[?1l","\x1B>","\x1B[?7h","\x1B[?25h","\x1B]9;4;0\x07","\x1B[?1049l"].join("");try{process.stdout.write(t)}catch{}}function gh(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function uh(t,e){let n={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":null:null}var Ik,ih,Sc,Sk,Ne,Ke,De,kc,xc,kk,xk,Ak,Ac,Cc,Rc,Ck,Rk,Tk,ya,fh,Tc,ph,$k,lh,Pc=V(()=>{"use strict";Ud();ue();en();fa();yr();Gm();vc();Ic();Ik=500,ih=1,Sc=/[A-Za-z0-9_]/,Sk=/\x1b\[[0-9;]*[A-Za-z]/g,Ne=1,Ke=1,De=1,kc=8,xc=5,kk=12,xk=12,Ak=30,Ac=6,Cc=4,Rc=2,Ck=1e3,Rk=1e4,Tk=/^(https?|ftp):\/\/\S+$/;ya=class{term;dispatcher;onKey;onBlockClick;onMouse;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;lastRepaintAt=0;throttledRepaintTimer=null;contentRepaintThrottleMs;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;pasteBuffer="";rawStdinHandler;mouseEnabled;inAppSelectionEnabled;selectionClipboard;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let n=e.onKey;this.onKey=s=>{this.selection!==null&&s.length>0&&this.clearSelection(),n(s)},this.onBlockClick=e.onBlockClick,this.onMouse=e.onMouse,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??Ck,this.maxScrollbackLines=e.maxScrollbackLines??Rk,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both",this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(s,r,i)=>this.handleKey(s,i),this.mouseHandler=(s,r)=>this.handleMouse(s,r),this.rawStdinHandler=s=>this.handleRawStdin(s)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,process.stdout.write("\x1B[?7l"),this.mouseEnabled?this.term.grabInput({mouse:"drag"}):this.term.grabInput(!0),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),this.term.hideCursor(!1),e.keepFullscreen||process.stdout.write("\x1B[?7h"),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(ga(),this.term.fullscreen(!1),this.term(`
173
- `)))}installBracketedPaste(){process.stdout.write("\x1B[?2004h"),process.stdout.write("\x1B[>4;2m"),process.stdout.write("\x1B[>5;1m"),process.stdout.write("\x1B[>1u");let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write("\x1B[?w"),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write("\x1B[=0;0w"),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>ga(),this.onProcessSignal=e=>{ga(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{ga(),process.stderr.write(`
167
+ `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(ma);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(ma);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(yc);if(s!==null){this.col+=s[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(ma);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(yc);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
168
+ `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],d=n.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});import ek from"path";function Ii(t){return Qm[ek.extname(t).toLowerCase()]??null}function tk(t){return Ii(t)!==null}function bc(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!nk.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function sk(t){return bc(t)!==null}function Ot(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Gm(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!sk(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!tk(o))return null;n.push(o)}return n.length>0?n:null}var dn,Qm,nk,ha=V(()=>{"use strict";dn=10*1024*1024,Qm={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};nk=new Set(Object.values(Qm))});import rk from"string-width";function Xm(t,e){if(!t||e<=0)return 0;let n=0;for(let s of ik.segment(t)){let r=rk(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Zm(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var ik,eh=V(()=>{"use strict";ik=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as ok}from"child_process";import vc from"fs/promises";import ak from"os";import dk from"path";async function sh(t={}){let e={...Ic,...t};return e.platform==="darwin"?fk(e):e.platform==="linux"?pk(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function rh(t={}){let e={...Ic,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Tr(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Tr(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await Si(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Sc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function ih(t,e={}){let{target:n="both",...s}=e,r={...Ic,...s},i=await ck(r,t,n);if(i.ok)return i;let o=lk(r,t,n);return o.ok||o.reason!==oh?o:i}async function ck(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await ga(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await Tr(t,"wl-copy")?nh(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Tr(t,"xclip")?nh(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function nh(t,e,n,s,r,i,o){let a=n;if(i){try{await ga(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await ga(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await ga(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function lk(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>th)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${th} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??uk)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:oh}}function uk(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function fk(t){let e=dk.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await ah(t.spawn,"osascript",s);let r=await wk(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await vc.unlink(e).catch(()=>{})}try{let r=await Si(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Sc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function pk(t){let e=await mk(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await yk(t,e),s=gk(n);if(s)try{let r=await Si(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>dn?{ok:!1,reason:`clipboard image is ${Ot(r.length)}, max ${Ot(dn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Si(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Sc(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function mk(t){return t.env.WAYLAND_DISPLAY&&await Tr(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Tr(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function gk(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of hk)if(e.has(n))return n;return null}async function yk(t,e){try{return(await Si(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
169
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Sc(t){return t.replace(/\r\n?/g,`
170
+ `)}async function Tr(t,e){try{return await ah(t.spawn,"which",[e]),!0}catch{return!1}}async function wk(t,e){try{let n=await vc.readFile(t);return e&&await vc.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>dn?{ok:!1,reason:`clipboard image is ${Ot(n.length)}, max ${Ot(dn)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ii(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function ah(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function ga(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${e} exited ${d}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function Si(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${d}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{c||(c=!0,r(u))}),i.on("close",u=>{d=u??0,l()})})}var Ic,th,oh,hk,kc=V(()=>{"use strict";ha();Ic={platform:process.platform,env:process.env,spawn:ok,tmpdir:ak.tmpdir};th=74994;oh="no TTY available for OSC 52 clipboard write";hk=["image/png","image/jpeg","image/gif","image/webp"]});function bk(){ki===0&&process.stdout.write("\x1B[?2026h"),ki++}function vk(){ki!==0&&(ki--,ki===0&&process.stdout.write("\x1B[?2026l"))}function $e(t){bk();try{t()}finally{vk()}}var ki,xc=V(()=>{"use strict";ki=0});import xi from"string-width";import Ik from"wrap-ansi";function Pk(t){let e=t.replace(/\r\n?$|\n$/,"");return Ek.test(e)?e:null}function Mk(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function ch(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let d=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${d}`}function An(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let d=r[a];if(d===" "||d===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function es(t,e,n){let s=0,r=0,i=-1;for(let d=0;d<t.length;d++){let c=t[d];if(!(!c||c.bufferIdx!==e.row)&&(i=d,e.col>=c.startCol&&e.col<c.endCol)){s=d,r=e.col-c.startCol,i=-1;break}}if(i!==-1){let d=t[i];d&&(s=i,r=e.col-d.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function lh(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){xn(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let d=o.indexOf(s,a);if(d===-1){xn(t,e.slice(a),n);return}d>a&&xn(t,e.slice(a,d),n);let c=r!==null&&d===r;xn(t,e.slice(d,d+s.length),c?"search-highlight-active":"search-highlight"),a=d+s.length}}function ya(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"}function xn(t,e,n){if(e.length!==0)switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.green.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow.noFormat(e);return;case"plan-done":t.green.noFormat(e);return;case"plan-pending":t.dim.noFormat(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}function $k(t,e){return e<=0?[t]:t.length===0?[""]:Ik(t,e,{hard:!0,trim:!1}).split(`
171
+ `)}function yh(t){gh=t}function Zn(t){return xi(t,{ambiguousIsNarrow:!gh})}function Ia(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return _k.test(n)?{text:t.slice(e,e+2),width:0}:null}function Ok(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=Ia(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function wh(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(Ia(t,e))return!0;return!1}function*$c(t){let e=0;for(;e<t.length;){let n=Ia(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(Ia(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Mc.segment(t.slice(e,s)))yield{text:i,width:Zn(i)};e=s}}function Fk(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function Lk(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&wh(t);return!s&&!hh.test(t)?Bk(t,e):Nk(t,e,s)}function Bk(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function Nk(t,e,n){let s=[],r=n?[...$c(t)]:Dk(t),i=0;for(;i<r.length;){let o="",a=0,d=-1,c="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(d=i,c=o);break}l.text===" "&&l.width===1&&(d=i,c=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}d>=0?(s.push(c),i=d+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function Dk(t){let e=[];for(let{segment:n}of Mc.segment(t))e.push({text:n,width:Zn(n)});return e}function it(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&wh(t);if(!s&&t.length<=e&&!hh.test(t))return t;if(!s)return Zn(t)<=e?t:e<=1?uh(t,e):uh(t,e-1)+"\u2026";let r=[...$c(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?fh(r,e):fh(r,e-1)+"\u2026"}function uh(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Mc.segment(t)){let i=Zn(r);if(s+i>e)break;n+=r,s+=i}return n}function fh(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function Hk(t){let e=t.indexOf(`
172
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Uk(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${wa(t.used)}/${wa(t.size)}`):e.push(wa(t.used)):typeof t.size=="number"&&e.push(`/${wa(t.size)}`),typeof t.costAmount=="number"&&e.push(qd(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function wa(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Sa(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function ba(){let t=["\x1B[?1000l","\x1B[?1002l","\x1B[?1003l","\x1B[?1006l","\x1B[?1015l","\x1B[=0;0w","\x1B[?2004l","\x1B[>4;0m","\x1B[>5;0m","\x1B[<u","\x1B[?1l","\x1B>","\x1B[?7h","\x1B[?25h","\x1B]9;4;0\x07","\x1B[?1049l"].join("");try{process.stdout.write(t)}catch{}}function bh(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function mh(t,e){let n={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":null:null}var Sk,dh,Ac,kk,De,Ke,He,Cc,Rc,xk,Ak,Ck,Tc,Ec,Pc,Rk,Tk,Ek,va,hh,Mc,gh,_k,ph,_c=V(()=>{"use strict";Wd();me();nn();ha();Sr();eh();kc();xc();Sk=500,dh=1,Ac=/[A-Za-z0-9_]/,kk=/\x1b\[[0-9;]*[A-Za-z]/g,De=1,Ke=1,He=1,Cc=8,Rc=5,xk=12,Ak=12,Ck=30,Tc=6,Ec=4,Pc=2,Rk=1e3,Tk=1e4,Ek=/^(https?|ftp):\/\/\S+$/;va=class{term;dispatcher;onKey;onBlockClick;onMouse;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;lastRepaintAt=0;throttledRepaintTimer=null;contentRepaintThrottleMs;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;pasteBuffer="";rawStdinHandler;mouseEnabled;inAppSelectionEnabled;selectionClipboard;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let n=e.onKey;this.onKey=s=>{this.selection!==null&&s.length>0&&this.clearSelection(),n(s)},this.onBlockClick=e.onBlockClick,this.onMouse=e.onMouse,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??Rk,this.maxScrollbackLines=e.maxScrollbackLines??Tk,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both",this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(s,r,i)=>this.handleKey(s,i),this.mouseHandler=(s,r)=>this.handleMouse(s,r),this.rawStdinHandler=s=>this.handleRawStdin(s)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,process.stdout.write("\x1B[?7l"),this.mouseEnabled?this.term.grabInput({mouse:"drag"}):this.term.grabInput(!0),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),this.term.hideCursor(!1),e.keepFullscreen||process.stdout.write("\x1B[?7h"),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(ba(),this.term.fullscreen(!1),this.term(`
173
+ `)))}installBracketedPaste(){process.stdout.write("\x1B[?2004h"),process.stdout.write("\x1B[>4;2m"),process.stdout.write("\x1B[>5;1m"),process.stdout.write("\x1B[>1u");let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write("\x1B[?w"),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write("\x1B[=0;0w"),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>ba(),this.onProcessSignal=e=>{ba(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{ba(),process.stderr.write(`
174
174
  uncaught: ${e.stack??e.message}
175
175
  `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write("\x1B[=24;1w"),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes("\x1B[200~")){this.handleRawStdinSegment(n);return}if(n.includes(`
176
176
  `)){let s=n.split(`
177
- `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=uh(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=uh(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n="\x1B[200~",s="\x1B[201~";for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
178
- `);this.pasteBuffer="";let a=Vm(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=Ek(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),d=n.length-s.count,c=this.lines.splice(s.start,s.count,...n);for(let l of c)this.forgetLine(l);if(this.trackLines(n),this.invalidateSelectionIfTouches(c),s.count=n.length,d!==0)for(let[l,f]of this.keyedBlocks)l!==e&&f.start>s.start&&(f.start+=d);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
179
- `),[o,...a]=i,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",d+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(n.length);for(let l of a){let f={prefix:c,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),d+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=lh(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&$e(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let d={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",d;r.ansi?d=s===e.loIdx||s===e.hiIdx?"":a.replace(Sk,""):(d=a.slice(o.start,o.end),ma(r.bodyStyle)&&(d=_k(d))),n.push(d)}return n.join(`
180
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=c===r?Math.max(0,Math.min(u,o)):0,g=c===i?Math.max(0,Math.min(u,a)):u;d.set(f,{start:p,end:g,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}selectionRangeForChunk(e){if(this.selection===null||e.ansi)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),d=Math.min(r.end,o);return d<=a?null:{start:a-i,end:d-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=d&&f.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write("\x1B[?7l"),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&this.clearSelection(),this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayLines=[],this.focusedPane="main",this.scheduleRepaint())}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=ba(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n),r=Pk(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),e==="MOUSE_LEFT_BUTTON_PRESSED"){this.pressCell=s,this.handleSelectionPress(s);return}if(e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let d=this.keyAtRow(s.y);d!==null&&this.onBlockClick(d)}this.handleSelectionRelease(s)}}handleSelectionPress(e){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let n=this.resolveCellToSource(e.x,e.y);if(n===null){this.lastLeftClick=null;return}this.selectionAnchor=n;let s=Date.now(),r=this.lastLeftClick;if(r!==null&&s-r.t<=Ik&&Math.abs(e.x-r.x)<=ih&&Math.abs(e.y-r.y)<=ih){let o=this.wordBoundsAt(n);o!==null&&(this.setSelection({sourceLineId:n.sourceLineId,offset:o.start},{sourceLineId:n.sourceLineId,offset:o.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}handleSelectionRelease(e){let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let r=Math.max(0,Math.min(s.length-1,e.offset));if(e.offset>=s.length&&(r=s.length-1),!Sc.test(s[r]))return null;let i=r;for(;i>0&&Sc.test(s[i-1]);)i--;let o=r+1;for(;o<s.length&&Sc.test(s[o]);)o++;return{start:i,end:o}}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&nh(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let g=this.wrapOrigin.get(p);if(!g)return null;let h=Yn(p.prefix??""),y=e-1-h;if(y<0)return{sourceLineId:g.sourceLineId,offset:g.sourceColOffset};let v=ma(p.bodyStyle)?Qm(Ec(p.body),y):Ym(p.body,y);return{sourceLineId:g.sourceLineId,offset:g.sourceColOffset+v}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],d=0;for(;d<o.length;){let c=o.indexOf(n,d);if(c===-1)break;a.push(c),d=c+n.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let g=p.body.length;if(e.col<f+g){o=l.length-1-u;break}f+=g}}let a=r+o,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Ne-De-Ke-De-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}if(this.contentRepaintThrottleMs<=0){this.repaint();return}let n=Date.now()-this.lastRepaintAt;if(n>=this.contentRepaintThrottleMs){this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.repaint();return}this.throttledRepaintTimer===null&&(this.throttledRepaintTimer=setTimeout(()=>{this.throttledRepaintTimer=null,this.repaint()},this.contentRepaintThrottleMs-n))}paintRow(e,n,s){this.started&&(e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter()))}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.lastRepaintAt=Date.now(),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null);let e=this.term.width,n=this.term.height;e<20||n<8||((e!==this.lastFrameW||n!==this.lastFrameH)&&(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n),$e(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Ke-De-Ne;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Ne),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=lh(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=bp(this.sessionbar.agent,this.sessionbar.model),o=Be(this.sessionbar.cwd),a=Hk(this.sessionbar.usage),d=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,d,()=>{let c=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+c,f=Math.max(8,e-l),u,p;if(r){let g=Math.min(r.length,8);u=Math.min(o.length,Math.max(8,f-g)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(rt(o,u)),r&&this.term(" \xB7 ").bold.noFormat(rt(r,p)),this.term.eraseLineAfter(),a){let g=bi(a),h=Math.max(1,e-g);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,r=`${this.focusedPane==="btw"?"\u25B6 ":" "}btw [${this.btwOverlayLabel}] `,i="\u2500\u2500 ",o="\u2500".repeat(Math.max(0,e-bi(r)-i.length)),a=`${e}|${this.btwOverlayLabel}|${this.btwOverlayStatus}|${this.focusedPane}`;return{left:i,label:r,right:o,signature:a}}paintBtwHeader(e){if(this.term.dim(e.left),!(this.focusedPane==="btw"))this.term.dim(e.label);else switch(this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term.green(e.label);break;case"cancelled":this.term.dim(e.label);break;case"errored":this.term.brightRed(e.label);break;default:this.term.brightYellow(e.label)}this.term.dim(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),d=r.slice(a,o),c=Math.max(0,s-d.length),l=this.currentMatchInfo(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let u=0;u<s;u++){let p=n+u,g=u-c,h=g>=0?d[g]:void 0,y=this.activeMatchCol(h,l),v=h?this.selectionRangeForChunk(h):null,b=oh("sb",e,h,this.scrollbackHighlight,y,v);this.paintRow(p,b,()=>{h&&this.writeFormattedLine(h,e,y,f,v)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let g of d)g.blockKey!==void 0&&u.add(g.blockKey);let p=[];for(let g of this.pendingVisibleKeys)u.has(g)&&p.push(g);for(let g of p)this.pendingVisibleKeys.delete(g),this.onBlockVisible(g)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(xc,this.queuedTexts.length)}chipRows(){return Math.min(Cc,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Ac,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ne-De-Ke,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>Ac,g=this.completions.length-Ac+1,h=u?p?`comp|${n}|overflow|${g}`:`comp|${n}|${c}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${g} more match(es)`);return}let y=u.name.padEnd(c),v=u.description??"",b=n-y.length-4,x=b>0?rt(v,b):"";this.term(" ").brightCyan(y),x.length>0&&this.term(" ").dim(x)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Ne-De-Ke-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>Cc,f=this.attachments.length-Cc,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${Ft(u.sizeBytes)}`:"",g=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,g,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(Ok(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ne-De-Ke,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>xc,p=this.queuedTexts.length-xc,g=f===void 0?"":u?`+ ${p+1} more queued`:rt(Dk(f),n-4),h=!u&&c===d,y=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${g}`;this.paintRow(l,y,()=>{if(f===void 0)return;let v=`\u23F3 ${g}`,b=v+" ".repeat(Math.max(0,n-1-v.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Sn(s.buffer,n),i=Qn(r,s,kc),o=this.term.height-i.rendered-Ke-De-Ne+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,f="wrap",u="";c&&(c.bufferIdx===0&&c.startCol===0?f="first":c.startCol===0&&(f="newline"),u=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(f==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):f==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(u):this.term.noFormat(u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Rc-Ke-De-Ne+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${rt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${rt(e.hint,n-2)}`)})}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Ke-De-Ne+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${rt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);o(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${rt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${rt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(Ak,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Ke-De-Ne+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${rt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${rt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. ${rt(c.label,n-8)}`;o(`perm|o|${n}|${d}|${l?"1":"0"}|${c.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Ne-De,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?sn(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let d=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${d} stalled`):this.term.brightYellow(`${d} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${d} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${d} ${this.banner.status}`):this.term.brightGreen(`${d} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let c=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(c),this.term.eraseLineAfter(),r){let l=bi(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Ke-De-Ne+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ke-De-Ne;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-Ke-De-Ne+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ke-De-Ne;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-Rc-Ke-De-Ne+1;this.term.moveTo(2,l);return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Ke-De-Ne+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Sn(s.buffer,n),i=Qn(r,s,kc),a=this.term.height-i.rendered-Ke-De-Ne+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-Ke-De-Ne;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return Rc;if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Sn(s.buffer,n);return Math.min(kc,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(kk,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(xk,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Ke-De-Ne+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${rt(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. `,p=c.label.padEnd(a),g=n-u.length-3,h=`${u}${rt(`${p} ${c.value}`,g)}`;o(`opts|o|${n}|${d}|${l?"1":"0"}|${c.value}|${c.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}o(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}btwOverlayRows(){return!this.btwOverlayOpen||this.btwOverlayLines.length===0?0:Math.min(this.btwOverlayMaxHeight,1+this.btwOverlayLines.length)}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Ke-De-Ne,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a,l=this.buildBtwHeaderSegments();this.paintRow(c,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});for(let f=0;f<d;f++){let u=c+1+f,p=this.btwOverlayLines.length-d+f,g=p>=0?this.btwOverlayLines[p]:void 0,h=oh(`btw|c${f}`,n,g);this.paintRow(u,h,()=>{g?this.writeFormattedLine(g,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=c=>c.collapsed===!0||this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let f of this.lines)s(f)||c.push(f);let l=Math.min(n,c.length);return{rows:c.slice(c.length-l),exhausted:n>=c.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),i+=f.length,o=c,i>=n)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",i=Yn(r),o=Math.max(1,n-i),a=ma(e.bodyStyle),d=e.ansi?Mk(e.body,o):Fk(e.body,o,{stripMarkup:a}),c=[],l=0;for(let f=0;f<d.length;f++){let u=d[f]??"",p={prefix:f===0?e.prefix:" ".repeat(i),body:u};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let g=e.body.indexOf(u,l),h=g===-1?l:g;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}c.push(p)}return s!==void 0&&this.wrapCache.set(s,c),c}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&In(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Yn(e.prefix??"")),a=ma(e.bodyStyle),d=e.ansi?e.body:rt(e.body,o,{stripMarkup:a}),c=(l,f)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let u=s!==null&&s>=f?s-f:null;ah(this.term,l,e.bodyStyle,this.scrollbackHighlight,u,r)}else In(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(d.length,i.start)),f=Math.max(l,Math.min(d.length,i.end));c(d.slice(0,l),0),f>l&&In(this.term,d.slice(l,f),"selection-highlight"),c(d.slice(f),f)}else this.scrollbackHighlight!==null&&!e.ansi?ah(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r):In(this.term,d,e.bodyStyle);if(e.fillRow){let l=e.ansi?bi(d):Yn(d),f=o-l;if(f>0){let u=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;In(this.term," ".repeat(f),u)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};fh=/[^\x20-\x7e]/,Tc=new Intl.Segmenter(void 0,{granularity:"grapheme"}),ph=!1;$k=/[a-zA-Z+\-:_!#/]/;lh=je});function xr(){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>")}function Mc(t){return t.width??80}function $c(t){return t.height??24}function vs(t,e){let n=Mc(t),s=$c(t),r=e.contentWidth??64,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,d=Math.max(1,Math.min(e.contentHeight,s-4)),c=d+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-c)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u="\u2500".repeat(a-2),p=Uk(u,e.title);t.moveTo(l,f),t.dim.noFormat("\u250C"),jk(t,p),t.dim.noFormat("\u2510");for(let g=1;g<=d;g++)t.moveTo(l,f+g),t.dim.noFormat("\u2502"),t.moveTo(l+a-1,f+g),t.dim.noFormat("\u2502");return t.moveTo(l,f+c-1),t.dim.noFormat("\u2514"+"\u2500".repeat(a-2)+"\u2518"),{x:l,y:f,w:a,h:c,contentX:l+1,contentY:f+1,contentW:o,contentH:d}}function Uk(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function jk(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}var va=V(()=>{"use strict"});function qk(t,e,n=vi){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function yh(t,e){xr();let n=je(e.sessionId),s=e.importedFromMachine??"another machine",r=Be(e.cwd),i=vi.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+vi.length*2+2,c=vs(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(_c(p.value,l-p.label.length-2)),u++;u++,t.moveTo(c.contentX,c.contentY+u),t.noFormat(" What do you want to do?"),u+=2;for(let p=0;p<vi.length;p++){let g=vi[p];if(!g)continue;let y=` ${p===i?"\u276F":" "} ${g.label}`;t.moveTo(c.contentX,c.contentY+u),p===i?t.brightWhite.bgBlue.noFormat(bh(y,l)):t.noFormat(y),u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${g.description}`),u++}return u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"),c};return o(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",u),t.off("resize",f),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=p=>{c(),a(p)},f=()=>{d||o()},u=(p,g,h)=>{let y=Wk(p,h);if(!y)return;let v=qk(i,y);if(v.kind==="cancel"){l("cancel");return}if(v.kind==="back"){l("back");return}if(v.kind==="resolve"){l(v.action);return}v.selected!==i&&(i=v.selected,o())};t.grabInput({}),t.on("key",u),t.on("resize",f)})}function Wk(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function wh(t,e,n){let s=je(e.sessionId),r=e.title??Be(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=vs(t,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" session: "),t.noFormat(_c(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" "+_c(r,c-2)),l++,l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" What do you want to do?"),l+=2;for(let f=0;f<o.length;f++){let u=o[f];if(!u)continue;let g=` ${f===i?"\u276F":" "} ${u.label}`;t.moveTo(d.contentX,d.contentY+l),f===i?t.brightWhite.bgBlue.noFormat(bh(g,c)):t.noFormat(g),l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(` ${u.description}`),l++}l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back")};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),n.pop(),d(p)},u=(p,g,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(h?.isCharacter){let y=p.toLowerCase();if(y==="l"){f("launch");return}if(y==="v"){f("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,g,h)=>{c||u(p,g,h)},onResize:()=>{c||a()}})})}function _c(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function bh(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var vi,Oc=V(()=>{"use strict";ue();en();va();vi=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Nc(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Dc(t,e){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let n=e.prefs??Nc();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(n.filters.hostFilter="__all");let s=Bc(e.sessions,e.cwd),r=k=>{let M=k;return n.filters.cwdOnly&&(M=M.filter(_=>_.cwd===e.cwd)),n.filters.includeNonInteractive||(M=M.filter(_=>_.interactive===!0)),M=Yk(M,n.filters.hostFilter),M},i=r(s),o={columns:e.config.tui.sessionColumns??fr,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},a=i.map(k=>mr(k,Date.now())),d=hr(a,o),c=1+i.length,l=0,f=0;if(e.currentSessionId!==void 0){let k=i.findIndex(M=>M.sessionId===e.currentSessionId);k>=0&&(l=k+1)}let u=!1,p="",g=120,h=!1,y=0,v="normal",b=null,x=!1,C="input",F=new vn({history:[],collapsePastes:!1}),z=[],J=!1,X=0,D=0,$=null,W=!1,K="",ee=null,he=!1,ke=new vn({history:[]});e.initialPrompt&&ke.setBuffer(e.initialPrompt);let te=e.config.tui.promptHistoryMaxEntries;zr(P.globalTuiHistoryFile()).then(k=>{let M=k.length>te?k.slice(k.length-te):k;ke.setHistory(M)}).catch(()=>{});let pe=Lc(t),H=Is(t),ge=0,Xn="",Lt=0,Bt=[],ht=1,Nt=0,Zn=0,Ss=0,on="",ki=[],es=1,ve=0,ks=[],it=1,an=0,xs=0,ts=0,Ar=()=>{pe=Lc(t),H=Is(t);let k=Math.max(10,H-Fc);Lt=Math.max(10,H-vh);let M=Math.max(10,H-8);Xn=Vk(e.cwd,M);let _=ke.state();Bt=Sn(_.buffer,Lt);let Y=Qn(Bt,_,Ia);ht=Y.rendered,Nt=Y.windowStart,Zn=Y.cursorVisualRow,Ss=Y.cursorVisualCol;let me=6+ht,Se=Math.max(3,pe-me);ge=Math.min(i.length,Se),on=Jn(pr,d,k,o).padEnd(k),ki=a.map(Me=>Jn(Me,d,k,o).padEnd(k))},Cr=()=>{a=i.map(k=>mr(k,Date.now())),d=hr(a,o),c=1+i.length,Ar()},gt=()=>{let k=r(s);u&&p.length>0?i=k.filter(M=>Gk(M,p)):i=k,Cr(),u?(f=0,l=i.length>0?1:0):l>c-1&&(l=Math.max(0,c-1)),f+ge>i.length&&(f=Math.max(0,i.length-ge)),Xe()},Pe=k=>{if(k!==void 0){let M=i.findIndex(_=>_.sessionId===k);if(M>=0){l=M+1,Xe();return}}l=i.length>0?1:0,f=0,Xe()},Xe=()=>{if(l===0)return;let k=l-1;k<f?f=k:k>=f+ge?f=k-ge+1:f+ge>i.length&&(f=Math.max(0,i.length-ge))},ot=()=>Math.max(2,H-2),As=()=>{let k=ot(),M=`\u2500 ${Xn} `,_=Math.max(1,k-M.length),Y="\u2500".repeat(_);l===0?t.brightBlue.noFormat(`\u256D${M}${Y}\u256E`):t.dim.noFormat(`\u256D${M}${Y}\u256E`)},kn=()=>{let k=ot(),M="\u2500".repeat(k);l===0?t.brightBlue.noFormat(`\u2570${M}\u256F`):t.dim.noFormat(`\u2570${M}\u256F`)},ns=k=>{let M=ot(),_=Bt[k],Y="";_&&(Y=(ke.state().buffer[_.bufferIdx]??"").slice(_.startCol,_.endCol));let me=Math.max(0,M-1-Y.length),Se=" ".repeat(me);l===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${Y}${Se}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${Y}${Se}`),t.dim.noFormat("\u2502"))},dn=k=>{let M=ki[k]??"",_=i[k],Y=_&&_.priority&&_.priority>0?"* ":" ";l===k+1?t.brightWhite.bgBlue.noFormat(`${Y}${M}`):t.noFormat(`${Y}${M}`)},Rr=()=>{let k=f,M=Math.max(0,i.length-f-ge),_=[];return n.filters.cwdOnly&&_.push("cwd-only"),n.filters.hostFilter!=="__all"&&_.push(n.filters.hostFilter==="__local"?"host: local":`host: ${n.filters.hostFilter}`),n.filters.includeNonInteractive&&_.push("+non-interactive"),k>0&&_.push(`\u2191 ${k} above`),M>0&&_.push(`\u2193 ${M} below`),_.length===0?"":` ${_.join(" \xB7 ")}`},xn=k=>je(k),Ie=()=>{$e(()=>{if(t.moveTo(1,Er()),v==="confirm-kill"&&b)t.brightYellow.noFormat(` kill ${xn(b.sessionId)}? [y/N]`);else if(v==="confirm-delete"&&b)b.status==="live"?t.brightRed.noFormat(` kill + delete ${xn(b.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${xn(b.sessionId)}? [y/N]`);else if(v==="busy"&&b)t.dim.noFormat(` working on ${xn(b.sessionId)}\u2026`);else if(v==="rename"&&b)t.brightYellow.noFormat(` title: ${K}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(ee!==null)t.dim.noFormat(` ${ee}`);else if(u){t.brightYellow.noFormat(` /${p}`),t.bgBrightYellow(" ");let k=i.length===0?" no matches":` ${i.length} match${i.length===1?"":"es"}`;t.dim.noFormat(`${k} \xB7 ^c clears`)}else t.dim.noFormat(Rr());t.styleReset(),t.eraseLineAfter()})},cn=k=>es+1+k,Tr=()=>es+ht+1,yt=()=>es+ht+3,ss=k=>yt()+1+(k-f),Er=()=>yt()+1+ge,He=()=>{let k=Zn-Nt;if(k<0||k>=ht)return;let M=3+Ss;t.moveTo(M,cn(k))},Re=()=>{$e(()=>{t.hideCursor(),Ar(),Xe(),es=1,t.moveTo(1,1).eraseDisplayBelow(),As(),t(`
181
- `);for(let k=0;k<ht;k++)ns(Nt+k),t(`
182
- `);kn(),t(`
177
+ `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=mh(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=mh(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n="\x1B[200~",s="\x1B[201~";for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
178
+ `);this.pasteBuffer="";let a=Gm(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=Pk(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),d=n.length-s.count,c=this.lines.splice(s.start,s.count,...n);for(let l of c)this.forgetLine(l);if(this.trackLines(n),this.invalidateSelectionIfTouches(c),s.count=n.length,d!==0)for(let[l,u]of this.keyedBlocks)l!==e&&u.start>s.start&&(u.start+=d);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
179
+ `),[o,...a]=i,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",d+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(n.length);for(let l of a){let u={prefix:c,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),d+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=ph(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&$e(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let d={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",d;r.ansi?d=s===e.loIdx||s===e.hiIdx?"":a.replace(kk,""):(d=a.slice(o.start,o.end),ya(r.bodyStyle)&&(d=Ok(d))),n.push(d)}return n.join(`
180
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=c===r?Math.max(0,Math.min(f,o)):0,g=c===i?Math.max(0,Math.min(f,a)):f;d.set(u,{start:p,end:g,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}selectionRangeForChunk(e){if(this.selection===null||e.ansi)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),d=Math.min(r.end,o);return d<=a?null:{start:a-i,end:d-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=d&&u.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write("\x1B[?7l"),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&this.clearSelection(),this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayLines=[],this.focusedPane="main",this.scheduleRepaint())}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=Sa(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n),r=Mk(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),e==="MOUSE_LEFT_BUTTON_PRESSED"){this.pressCell=s,this.handleSelectionPress(s);return}if(e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let d=this.keyAtRow(s.y);d!==null&&this.onBlockClick(d)}this.handleSelectionRelease(s)}}handleSelectionPress(e){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let n=this.resolveCellToSource(e.x,e.y);if(n===null){this.lastLeftClick=null;return}this.selectionAnchor=n;let s=Date.now(),r=this.lastLeftClick;if(r!==null&&s-r.t<=Sk&&Math.abs(e.x-r.x)<=dh&&Math.abs(e.y-r.y)<=dh){let o=this.wordBoundsAt(n);o!==null&&(this.setSelection({sourceLineId:n.sourceLineId,offset:o.start},{sourceLineId:n.sourceLineId,offset:o.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}handleSelectionRelease(e){let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let r=Math.max(0,Math.min(s.length-1,e.offset));if(e.offset>=s.length&&(r=s.length-1),!Ac.test(s[r]))return null;let i=r;for(;i>0&&Ac.test(s[i-1]);)i--;let o=r+1;for(;o<s.length&&Ac.test(s[o]);)o++;return{start:i,end:o}}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&ih(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),u=i-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let g=this.wrapOrigin.get(p);if(!g)return null;let h=Zn(p.prefix??""),y=e-1-h;if(y<0)return{sourceLineId:g.sourceLineId,offset:g.sourceColOffset};let I=ya(p.bodyStyle)?Zm($c(p.body),y):Xm(p.body,y);return{sourceLineId:g.sourceLineId,offset:g.sourceColOffset+I}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],d=0;for(;d<o.length;){let c=o.indexOf(n,d);if(c===-1)break;a.push(c),d=c+n.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let g=p.body.length;if(e.col<u+g){o=l.length-1-f;break}u+=g}}let a=r+o,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-De-He-Ke-He-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}if(this.contentRepaintThrottleMs<=0){this.repaint();return}let n=Date.now()-this.lastRepaintAt;if(n>=this.contentRepaintThrottleMs){this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.repaint();return}this.throttledRepaintTimer===null&&(this.throttledRepaintTimer=setTimeout(()=>{this.throttledRepaintTimer=null,this.repaint()},this.contentRepaintThrottleMs-n))}paintRow(e,n,s){this.started&&(e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter()))}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.lastRepaintAt=Date.now(),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null);let e=this.term.width,n=this.term.height;e<20||n<8||((e!==this.lastFrameW||n!==this.lastFrameH)&&(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n),$e(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Ke-He-De;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-De),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=ph(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=Sp(this.sessionbar.agent,this.sessionbar.model),o=Ne(this.sessionbar.cwd),a=Uk(this.sessionbar.usage),d=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,d,()=>{let c=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+c,u=Math.max(8,e-l),f,p;if(r){let g=Math.min(r.length,8);f=Math.min(o.length,Math.max(8,u-g)),p=Math.max(0,u-f)}else p=0,f=u;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(it(o,f)),r&&this.term(" \xB7 ").bold.noFormat(it(r,p)),this.term.eraseLineAfter(),a){let g=xi(a),h=Math.max(1,e-g);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,r=`${this.focusedPane==="btw"?"\u25B6 ":" "}btw [${this.btwOverlayLabel}] `,i="\u2500\u2500 ",o="\u2500".repeat(Math.max(0,e-xi(r)-i.length)),a=`${e}|${this.btwOverlayLabel}|${this.btwOverlayStatus}|${this.focusedPane}`;return{left:i,label:r,right:o,signature:a}}paintBtwHeader(e){if(this.term.dim(e.left),!(this.focusedPane==="btw"))this.term.dim(e.label);else switch(this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term.green(e.label);break;case"cancelled":this.term.dim(e.label);break;case"errored":this.term.brightRed(e.label);break;default:this.term.brightYellow(e.label)}this.term.dim(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let f=Math.max(0,r.length-s);this.scrollOffset>f&&(this.scrollOffset=f)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),d=r.slice(a,o),c=Math.max(0,s-d.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let f=0;f<s;f++){let p=n+f,g=f-c,h=g>=0?d[g]:void 0,y=this.activeMatchCol(h,l),I=h?this.selectionRangeForChunk(h):null,b=ch("sb",e,h,this.scrollbackHighlight,y,I);this.paintRow(p,b,()=>{h&&this.writeFormattedLine(h,e,y,u,I)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let f=new Set;for(let g of d)g.blockKey!==void 0&&f.add(g.blockKey);let p=[];for(let g of this.pendingVisibleKeys)f.has(g)&&p.push(g);for(let g of p)this.pendingVisibleKeys.delete(g),this.onBlockVisible(g)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Rc,this.queuedTexts.length)}chipRows(){return Math.min(Ec,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Tc,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-De-He-Ke,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let u=d+l,f=this.completions[l],p=l===e-1&&this.completions.length>Tc,g=this.completions.length-Tc+1,h=f?p?`comp|${n}|overflow|${g}`:`comp|${n}|${c}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,h,()=>{if(!f)return;if(p){this.term.dim(` + ${g} more match(es)`);return}let y=f.name.padEnd(c),I=f.description??"",b=n-y.length-4,x=b>0?it(I,b):"";this.term(" ").brightCyan(y),x.length>0&&this.term(" ").dim(x)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-De-He-Ke-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>Ec,u=this.attachments.length-Ec,f=this.attachments[d],p=f?`${f.name??"image"} \xB7 ${Ot(f.sizeBytes)}`:"",g=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,g,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(Fk(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-De-He-Ke,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,u=this.queuedTexts[c],f=c===e-1&&this.queuedTexts.length>Rc,p=this.queuedTexts.length-Rc,g=u===void 0?"":f?`+ ${p+1} more queued`:it(Hk(u),n-4),h=!f&&c===d,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":f?"ovf":"row"}|${g}`;this.paintRow(l,y,()=>{if(u===void 0)return;let I=`\u23F3 ${g}`,b=I+" ".repeat(Math.max(0,n-1-I.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=An(s.buffer,n),i=es(r,s,Cc),o=this.term.height-i.rendered-Ke-He-De+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Pc-Ke-He-De+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${it(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Ke-He-De+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${it(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);o(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${it(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(Ck,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Ke-He-De+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${it(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${it(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,f=` ${l?"\u276F":" "} ${d+1}. ${it(c.label,n-8)}`;o(`perm|o|${n}|${d}|${l?"1":"0"}|${c.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-De-He,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?an(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let d=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${d} stalled`):this.term.brightYellow(`${d} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${d} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${d} ${this.banner.status}`):this.term.brightGreen(`${d} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let c=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(c),this.term.eraseLineAfter(),r){let l=xi(r.text),u=Math.max(1,n-l);this.term.moveTo(u,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Ke-He-De+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ke-He-De;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Ke-He-De+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ke-He-De;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Pc-Ke-He-De+1;this.term.moveTo(2,l);return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Ke-He-De+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=An(s.buffer,n),i=es(r,s,Cc),a=this.term.height-i.rendered-Ke-He-De+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-Ke-He-De;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return Pc;if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=An(s.buffer,n);return Math.min(Cc,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(xk,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(Ak,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Ke-He-De+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${it(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,f=` ${l?"\u276F":" "} ${d+1}. `,p=c.label.padEnd(a),g=n-f.length-3,h=`${f}${it(`${p} ${c.value}`,g)}`;o(`opts|o|${n}|${d}|${l?"1":"0"}|${c.value}|${c.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}o(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}btwOverlayRows(){return!this.btwOverlayOpen||this.btwOverlayLines.length===0?0:Math.min(this.btwOverlayMaxHeight,1+this.btwOverlayLines.length)}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Ke-He-De,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a,l=this.buildBtwHeaderSegments();this.paintRow(c,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});for(let u=0;u<d;u++){let f=c+1+u,p=this.btwOverlayLines.length-d+u,g=p>=0?this.btwOverlayLines[p]:void 0,h=ch(`btw|c${u}`,n,g);this.paintRow(f,h,()=>{g?this.writeFormattedLine(g,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=c=>c.collapsed===!0||this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let u of this.lines)s(u)||c.push(u);let l=Math.min(n,c.length);return{rows:c.slice(c.length-l),exhausted:n>=c.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=c,i>=n)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=Zn(r),o=Math.max(1,n-i),a=ya(e.bodyStyle),d=e.ansi?$k(e.body,o):Lk(e.body,o,{stripMarkup:a}),c=[],l=0;for(let u=0;u<d.length;u++){let f=d[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let g=e.body.indexOf(f,l),h=g===-1?l:g;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+f.length}c.push(p)}return s!==void 0&&this.wrapCache.set(s,c),c}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&xn(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Zn(e.prefix??"")),a=ya(e.bodyStyle),d=e.ansi?e.body:it(e.body,o,{stripMarkup:a}),c=(l,u)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let f=s!==null&&s>=u?s-u:null;lh(this.term,l,e.bodyStyle,this.scrollbackHighlight,f,r)}else xn(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(d.length,i.start)),u=Math.max(l,Math.min(d.length,i.end));c(d.slice(0,l),0),u>l&&xn(this.term,d.slice(l,u),"selection-highlight"),c(d.slice(u),u)}else this.scrollbackHighlight!==null&&!e.ansi?lh(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r):xn(this.term,d,e.bodyStyle);if(e.fillRow){let l=e.ansi?xi(d):Zn(d),u=o-l;if(u>0){let f=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;xn(this.term," ".repeat(u),f)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};hh=/[^\x20-\x7e]/,Mc=new Intl.Segmenter(void 0,{granularity:"grapheme"}),gh=!1;_k=/[a-zA-Z+\-:_!#/]/;ph=qe});function Er(){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>")}function Oc(t){return t.width??80}function Fc(t){return t.height??24}function xs(t,e){let n=Oc(t),s=Fc(t),r=e.contentWidth??64,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,d=Math.max(1,Math.min(e.contentHeight,s-4)),c=d+2,l=Math.max(1,Math.floor((n-a)/2)+1),u=Math.max(1,Math.floor((s-c)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f="\u2500".repeat(a-2),p=jk(f,e.title);t.moveTo(l,u),t.dim.noFormat("\u250C"),qk(t,p),t.dim.noFormat("\u2510");for(let g=1;g<=d;g++)t.moveTo(l,u+g),t.dim.noFormat("\u2502"),t.moveTo(l+a-1,u+g),t.dim.noFormat("\u2502");return t.moveTo(l,u+c-1),t.dim.noFormat("\u2514"+"\u2500".repeat(a-2)+"\u2518"),{x:l,y:u,w:a,h:c,contentX:l+1,contentY:u+1,contentW:o,contentH:d}}function jk(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function qk(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}var ka=V(()=>{"use strict"});function Wk(t,e,n=Ai){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function vh(t,e){Er();let n=qe(e.sessionId),s=e.importedFromMachine??"another machine",r=Ne(e.cwd),i=Ai.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+Ai.length*2+2,c=xs(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(c.contentX,c.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(Lc(p.value,l-p.label.length-2)),f++;f++,t.moveTo(c.contentX,c.contentY+f),t.noFormat(" What do you want to do?"),f+=2;for(let p=0;p<Ai.length;p++){let g=Ai[p];if(!g)continue;let y=` ${p===i?"\u276F":" "} ${g.label}`;t.moveTo(c.contentX,c.contentY+f),p===i?t.brightWhite.bgBlue.noFormat(Sh(y,l)):t.noFormat(y),f++,t.moveTo(c.contentX,c.contentY+f),t.dim.noFormat(` ${g.description}`),f++}return f++,t.moveTo(c.contentX,c.contentY+f),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"),c};return o(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",f),t.off("resize",u),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=p=>{c(),a(p)},u=()=>{d||o()},f=(p,g,h)=>{let y=zk(p,h);if(!y)return;let I=Wk(i,y);if(I.kind==="cancel"){l("cancel");return}if(I.kind==="back"){l("back");return}if(I.kind==="resolve"){l(I.action);return}I.selected!==i&&(i=I.selected,o())};t.grabInput({}),t.on("key",f),t.on("resize",u)})}function zk(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function Ih(t,e,n){let s=qe(e.sessionId),r=e.title??Ne(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=xs(t,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Lc(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" "+Lc(r,c-2)),l++,l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" What do you want to do?"),l+=2;for(let u=0;u<o.length;u++){let f=o[u];if(!f)continue;let g=` ${u===i?"\u276F":" "} ${f.label}`;t.moveTo(d.contentX,d.contentY+l),u===i?t.brightWhite.bgBlue.noFormat(Sh(g,c)):t.noFormat(g),l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(` ${f.description}`),l++}l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back")};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},u=p=>{l(),n.pop(),d(p)},f=(p,g,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(h?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,g,h)=>{c||f(p,g,h)},onResize:()=>{c||a()}})})}function Lc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Sh(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var Ai,Bc=V(()=>{"use strict";me();nn();ka();Ai=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Ci(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function kh(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=Ci(e);return o.length<=r.length?null:o+i}var xa=V(()=>{"use strict"});import*as xh from"os";async function As(t,e,n={}){let s=n.defaultCwd??(e?await zm(e.cwd):void 0)??xh.homedir();Er();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:qe(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ne(e.cwd)}]:[],a=s,d=null,c=!1,l=null,u=()=>{let h=o.length+6;l=xs(t,{contentHeight:h,title:r});let y=l.contentW,I=0;for(let b of o)t.moveTo(l.contentX,l.contentY+I),t.dim.noFormat(` ${b.label}`),t.noFormat(Nc(b.value,y-b.label.length-2)),I++;I++,t.moveTo(l.contentX,l.contentY+I),t.noFormat(` ${i}`),I+=2,p(I),I+=2,d!==null?(t.moveTo(l.contentX,l.contentY+I),t.red.noFormat(` ${Nc(d,y-2)}`)):(t.moveTo(l.contentX,l.contentY+I),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},f=()=>o.length+3,p=h=>{if(!l)return;let y=h??f();t.moveTo(l.contentX,l.contentY+y).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+y),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+y),t.bold.noFormat(" cwd: ");let I=l.contentW-6-2;t.noFormat(Jk(a,I)),c||t.bgWhite(" ")},g=()=>{if(p(),!l)return;let h=f()+2;t.moveTo(l.contentX,l.contentY+h).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+h),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+h),d!==null?t.red.noFormat(` ${Nc(d,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return u(),await new Promise(h=>{let y=!1,I=()=>{y||(y=!0,t.off("key",M),t.off("resize",x),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},b=_=>{I(),h(_)},x=()=>{y||u()},M=(_,Q,W)=>{if(!c){if(_==="ENTER"||_==="KP_ENTER"){let z=a;c=!0,d=null,g(),vi(z).then($=>{if(c=!1,$.ok){b({kind:"ok",path:$.path});return}d=$.reason,g()});return}if(_==="ESCAPE"){b({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){b({kind:"cancel"});return}if(_==="TAB"){c=!0,Jm(a).then(z=>{if(c=!1,z.matches.length===0)return;let $;if(z.matches.length===1)$=z.prefix+z.matches[0];else{let D=Ci(z.matches);if(D.length<=z.basePrefix.length)return;$=z.prefix+D}$!==a&&(a=$,d=null,g())});return}if(_==="BACKSPACE"){a.length>0&&(a=a.slice(0,-1),d=null,g());return}if(_==="CTRL_U"){a="",d=null,g();return}if(_==="CTRL_W"){let z=a.replace(/[/\s]+$/,""),$=Math.max(z.lastIndexOf("/"),z.lastIndexOf(" "));a=$>=0?z.slice(0,$+1):"",d=null,g();return}if(W?.isCharacter){a+=_,d=null,g();return}}};t.grabInput({}),t.on("key",M),t.on("resize",x)})}function Nc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Jk(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Dc=V(()=>{"use strict";me();nn();mc();xa();ka()});function jc(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function qc(t,e){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let n=e.prefs??jc();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(n.filters.hostFilter="__all");let s=e.cwd,r=Ca(e.sessions,s),i=k=>{let P=k;return n.filters.cwdOnly&&(P=P.filter(O=>O.cwd===s)),n.filters.includeNonInteractive||(P=P.filter(O=>O.interactive===!0)),P=Gk(P,n.filters.hostFilter),P},o=i(r),a={columns:e.config.tui.sessionColumns??yr,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=o.map(k=>br(k,Date.now())),c=vr(d,a),l=1+o.length,u=0,f=0;if(e.currentSessionId!==void 0){let k=o.findIndex(P=>P.sessionId===e.currentSessionId);k>=0&&(u=k+1)}let p=!1,g="",h=120,y=!1,I=0,b="normal",x=null,M=!1,_="input",Q=new kn({history:[],collapsePastes:!1}),W=[],z=!1,$=0,D=0,j=null,Z=!1,ie="",se=null,Ee=!1,K=new kn({history:[]});e.initialPrompt&&K.setBuffer(e.initialPrompt);let Ce=e.config.tui.promptHistoryMaxEntries;Gr(E.globalTuiHistoryFile()).then(k=>{let P=k.length>Ce?k.slice(k.length-Ce):k;K.setHistory(P)}).catch(()=>{});let X=Uc(t),ee=Cs(t),Re=0,Rs="",Ft=0,Lt=[],yt=1,Bt=0,ns=0,Ts=0,cn="",Ri=[],ss=1,be=0,Es=[],ot=1,ln=0,Ps=0,rs=0,Pr=()=>{X=Uc(t),ee=Cs(t);let k=Math.max(10,ee-Hc);Ft=Math.max(10,ee-Ah);let P=Math.max(10,ee-8);Rs=Qk(s,P);let O=K.state();Lt=An(O.buffer,Ft);let Y=es(Lt,O,Aa);yt=Y.rendered,Bt=Y.windowStart,ns=Y.cursorVisualRow,Ts=Y.cursorVisualCol;let ge=6+yt,Ie=Math.max(3,X-ge);Re=Math.min(o.length,Ie),cn=Qn(wr,c,k,a).padEnd(k),Ri=d.map(Me=>Qn(Me,c,k,a).padEnd(k))},Mr=()=>{d=o.map(k=>br(k,Date.now())),c=vr(d,a),l=1+o.length,Pr()},at=()=>{let k=i(r);p&&g.length>0?o=k.filter(P=>Zk(P,g)):o=k,Mr(),p?(f=0,u=o.length>0?1:0):u>l-1&&(u=Math.max(0,l-1)),f+Re>o.length&&(f=Math.max(0,o.length-Re)),Xe()},Te=k=>{if(k!==void 0){let P=o.findIndex(O=>O.sessionId===k);if(P>=0){u=P+1,Xe();return}}u=o.length>0?1:0,f=0,Xe()},Xe=()=>{if(u===0)return;let k=u-1;k<f?f=k:k>=f+Re?f=k-Re+1:f+Re>o.length&&(f=Math.max(0,o.length-Re))},dt=()=>Math.max(2,ee-2),Ms=()=>{let k=dt(),P=`\u2500 ${Rs} `,O=Math.max(1,k-P.length),Y="\u2500".repeat(O);u===0?t.brightBlue.noFormat(`\u256D${P}${Y}\u256E`):t.dim.noFormat(`\u256D${P}${Y}\u256E`)},Cn=()=>{let k=dt(),P="\u2500".repeat(k);u===0?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},is=k=>{let P=dt(),O=Lt[k],Y="";O&&(Y=(K.state().buffer[O.bufferIdx]??"").slice(O.startCol,O.endCol));let ge=Math.max(0,P-1-Y.length),Ie=" ".repeat(ge);u===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${Y}${Ie}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${Y}${Ie}`),t.dim.noFormat("\u2502"))},un=k=>{let P=Ri[k]??"",O=o[k],Y=O&&O.priority&&O.priority>0?"* ":" ";u===k+1?t.brightWhite.bgBlue.noFormat(`${Y}${P}`):t.noFormat(`${Y}${P}`)},$r=()=>{let k=f,P=Math.max(0,o.length-f-Re),O=[];return n.filters.cwdOnly&&O.push("cwd-only"),n.filters.hostFilter!=="__all"&&O.push(n.filters.hostFilter==="__local"?"host: local":`host: ${n.filters.hostFilter}`),n.filters.includeNonInteractive&&O.push("+non-interactive"),k>0&&O.push(`\u2191 ${k} above`),P>0&&O.push(`\u2193 ${P} below`),O.length===0?"":` ${O.join(" \xB7 ")}`},Rn=k=>qe(k),ve=()=>{$e(()=>{if(t.moveTo(1,Or()),b==="confirm-kill"&&x)t.brightYellow.noFormat(` kill ${Rn(x.sessionId)}? [y/N]`);else if(b==="confirm-delete"&&x)x.status==="live"?t.brightRed.noFormat(` kill + delete ${Rn(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Rn(x.sessionId)}? [y/N]`);else if(b==="busy"&&x)t.dim.noFormat(` working on ${Rn(x.sessionId)}\u2026`);else if(b==="rename"&&x)t.brightYellow.noFormat(` title: ${ie}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(se!==null)t.dim.noFormat(` ${se}`);else if(p){t.brightYellow.noFormat(` /${g}`),t.bgBrightYellow(" ");let k=o.length===0?" no matches":` ${o.length} match${o.length===1?"":"es"}`;t.dim.noFormat(`${k} \xB7 ^c clears`)}else t.dim.noFormat($r());t.styleReset(),t.eraseLineAfter()})},fn=k=>ss+1+k,_r=()=>ss+yt+1,wt=()=>ss+yt+3,os=k=>wt()+1+(k-f),Or=()=>wt()+1+Re,Ue=()=>{let k=ns-Bt;if(k<0||k>=yt)return;let P=3+Ts;t.moveTo(P,fn(k))},ke=()=>{$e(()=>{t.hideCursor(),Pr(),Xe(),ss=1,t.moveTo(1,1).eraseDisplayBelow(),Ms(),t(`
181
+ `);for(let k=0;k<yt;k++)is(Bt+k),t(`
182
+ `);Cn(),t(`
183
183
 
184
- `),t.dim.noFormat(` ${on}`)(`
185
- `);for(let k=0;k<ge;k++)dn(f+k),t(`
186
- `);Ie(),t(`
187
- `),l===0&&(He(),t.hideCursor(!1))})},jt=()=>{$e(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
184
+ `),t.dim.noFormat(` ${cn}`)(`
185
+ `);for(let k=0;k<Re;k++)un(f+k),t(`
186
+ `);ve(),t(`
187
+ `),u===0&&(Ue(),t.hideCursor(!1))})},Wt=()=>{$e(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
188
188
 
189
- `);for(let k of Kk){if(k===null){t(`
190
- `);continue}let[M,_]=k;t.brightCyan.noFormat(` ${M.padEnd(Jk)}`),t.noFormat(_)(`
189
+ `);for(let k of Yk){if(k===null){t(`
190
+ `);continue}let[P,O]=k;t.brightCyan.noFormat(` ${P.padEnd(Vk)}`),t.noFormat(O)(`
191
191
  `)}t(`
192
192
  `),t.dim.noFormat(" press any key to dismiss")(`
193
- `)})},oe=()=>it+4,xi=2,_e=0,We=()=>{pe=Lc(t);let k=Math.max(2,pe-(it+3)-xi);return Math.max(1,Math.floor(k/2))},rs=()=>{let k=We();X<_e?_e=X:X>=_e+k&&(_e=X-k+1),_e+k>z.length&&(_e=Math.max(0,z.length-k)),_e<0&&(_e=0)},is=k=>{H=Is(t);let M=Math.max(2,H-2),_="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,M-_.length));k?t.brightBlue.noFormat(`\u256D${_}${Y}\u256E`):t.dim.noFormat(`\u256D${_}${Y}\u256E`),t.styleReset()},S=()=>{H=Is(t),ve=Math.max(10,H-vh);let k=F.state();ks=Sn(k.buffer,ve);let M=Qn(ks,k,zk);it=M.rendered,an=M.windowStart,xs=M.cursorVisualRow,ts=M.cursorVisualCol},Cs=(k,M)=>{H=Is(t);let _=Math.max(2,H-2),Y=ks[k],me="";Y&&(me=(F.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let Se=Math.max(0,_-1-me.length),Me=" ".repeat(Se);M?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${me}${Me}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${me}${Me}`),t.dim.noFormat("\u2502")),t.styleReset()},Ai=k=>{H=Is(t);let M=Math.max(2,H-2),_="\u2500".repeat(M);k?t.brightBlue.noFormat(`\u2570${_}\u256F`):t.dim.noFormat(`\u2570${_}\u256F`),t.styleReset()},An=()=>3+ts,qt=()=>2+(xs-an),Wt=()=>{let k=C==="input";$e(()=>{k&&t.hideCursor(),t.moveTo(1,1),is(k);for(let M=0;M<it;M++)t.moveTo(1,2+M),Cs(an+M,k);t.moveTo(1,2+it),Ai(k),k&&(t.moveTo(An(),qt()),t.hideCursor(!1))})},Pr=()=>{$e(()=>{t.hideCursor();for(let k=0;k<it;k++)t.moveTo(1,2+k),Cs(an+k,!0);t.moveTo(An(),qt()),t.hideCursor(!1)})},xa={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Ci=(k,M)=>{let _=z[k];if(!_)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Is(t),me=Math.max(20,Y-Fc),Se=je(_.sessionId),Me=_.title??Be(_.cwd),bt=M&&_.snippets.length>1?` [${D+1}/${_.snippets.length}]`:M&&_.totalMatches>_.snippets.length?` [${_.snippets.length} of ${_.totalMatches}]`:"",Pn=`${Se} ${_.status==="live"?"live":"cold"}`,as=Math.max(5,me-Pn.length-bt.length-2),fn=ai(Me,as),dt=`${Pn} ${fn}${bt}`.padEnd(me),vt=_.snippets[M?D:0],Ps=vt?xa[vt.kind]??vt.kind:"",Rt=vt?.toolName?`${Ps} \xB7 ${vt.toolName}`:Ps,Ye=Math.max(10,me-Rt.length-6),Ze=vt?ai(vt.text,Ye):"",Jt=vt?` ${Rt} ${Ze}`:" (no snippet)";return{rowBudget:me,line1:dt,line2:Jt.padEnd(me+Fc),focusedRow:M}},Rs=(k,M)=>{let{line1:_,focusedRow:Y}=Ci(k,M);Y?t.brightWhite.bgBlue.noFormat(`\u276F ${_}`):t.noFormat(` ${_}`),t.styleReset()},zt=(k,M)=>{let{line2:_}=Ci(k,M);t.dim.noFormat(_),t.styleReset()},os=()=>{if(W)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if($!==null)t.brightRed.noFormat(` ${$}`),t.styleReset(),t.eraseLineAfter();else if(C==="input")z.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let k=z.length,M=J?" \xB7 truncated":"",_=k>0?` ${k} ${k===1?"session":"sessions"} match${M} \xB7 `:" ";t.dim.noFormat(`${_}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},ln=()=>{S();let k=C==="input",M=F.state().buffer.join(`
194
- `);$e(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),is(k);for(let Y=0;Y<it;Y++)t.moveTo(1,2+Y),Cs(an+Y,k);t.moveTo(1,2+it),Ai(k);let _=z.length;if(_===0)t.moveTo(1,oe()),W||($===null&&M.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):$===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,oe()+1),os();else{rs();let Y=We(),me=C!=="input";for(let Se=0;Se<Y;Se++){let Me=_e+Se;t.moveTo(1,oe()+Se*2),Me<_?Rs(Me,me&&Me===X):t.eraseLineAfter(),t.moveTo(1,oe()+Se*2+1),Me<_?zt(Me,me&&Me===X):t.eraseLineAfter()}t.moveTo(1,oe()+Y*2),os()}k&&(t.moveTo(An(),qt()),t.hideCursor(!1))})},Cn=(k,M)=>{let _=k-_e;_<0||_>=We()||$e(()=>{t.moveTo(1,oe()+_*2),Rs(k,M),t.moveTo(1,oe()+_*2+1),zt(k,M)})},Ts=()=>{$e(()=>{t.moveTo(1,oe()+We()*2),os()})},Ri=()=>{$e(()=>{let k=We(),M=z.length,_=C!=="input";for(let Y=0;Y<k;Y++){let me=_e+Y;t.moveTo(1,oe()+Y*2),me<M?Rs(me,_&&me===X):t.eraseLineAfter(),t.moveTo(1,oe()+Y*2+1),me<M?zt(me,_&&me===X):t.eraseLineAfter()}t.moveTo(1,oe()+k*2),os()})},Ti=()=>F.state().buffer.join(`
195
- `),Aa=k=>{let M=it;F.feed({type:"paste",text:k}),S(),it!==M?ln():Pr()},At=async()=>{let k=Ti().trim();if(k.length!==0){if(i.length===0){$="no sessions in view to search",ln();return}W=!0,$=null,ln();try{let M=await yp(e.target,k,{sessionIds:i.map(_=>_.sessionId)});z=M.results,J=M.truncated,X=0,D=0,_e=0,C=M.results.length>0?"results":"input",S()}catch(M){$=`search failed: ${M.message}`}finally{W=!1,ln()}}},at=()=>{},Ca=()=>{$e(()=>{let k=l===0;k&&t.hideCursor(),t.moveTo(1,es),As(),t.moveTo(1,Tr()),kn();for(let M=0;M<ht;M++)t.moveTo(1,cn(M)),ns(Nt+M);k&&(He(),t.hideCursor(!1))})},Mr=()=>{$e(()=>{let k=ke.state();Bt=Sn(k.buffer,Lt);let M=Qn(Bt,k,Ia);Nt=M.windowStart,Zn=M.cursorVisualRow,Ss=M.cursorVisualCol;let _=l===0;_&&t.hideCursor();for(let Y=0;Y<ht;Y++)t.moveTo(1,cn(Y)),ns(Nt+Y);_&&(He(),t.hideCursor(!1))})},Ei=k=>{k<f||k>=f+ge||$e(()=>{t.moveTo(1,ss(k)),dn(k)})},Es=()=>{$e(()=>{for(let k=0;k<ge;k++){let M=yt()+1+k,_=f+k;_<i.length?(t.moveTo(1,M),dn(_)):t.moveTo(1,M).eraseLineAfter()}Ie()})},$r=()=>{$e(()=>{t.moveTo(1,yt()),t.dim.noFormat(` ${on}`);for(let k=0;k<ge;k++){let M=yt()+1+k,_=f+k;_<i.length?(t.moveTo(1,M),dn(_)):t.moveTo(1,M).eraseLineAfter()}Ie(),l===0&&(He(),t.hideCursor(!1))})},Rn=!1,Tn="",wt=null,un=null,Ct="\x1B[200~",_r="\x1B[201~",En=k=>{let M=k.toString("binary");if(!Rn&&M===""&&un){un();return}if(Rn){let Y=M.indexOf(_r);if(Y===-1){Tn+=M;return}Tn+=M.slice(0,Y),Rn=!1;let me=Buffer.from(Tn,"binary").toString("utf-8").replace(/\r\n?/g,`
196
- `);Tn="";let Se=M.slice(Y+_r.length);if(x)C==="input"&&!W&&Aa(me);else if(l===0&&!u){ke.feed({type:"paste",text:me});let Me=ke.state(),bt=Sn(Me.buffer,Lt);Qn(bt,Me,Ia).rendered!==ht?Re():Mr()}Se.length>0&&wt&&wt(Buffer.from(Se,"binary"));return}let _=M.indexOf(Ct);if(_===-1){wt?.(k);return}_>0&&wt?.(Buffer.from(M.slice(0,_),"binary")),M=M.slice(_+Ct.length),Rn=!0,M.length>0&&En(Buffer.from(M,"binary"))};return Re(),await new Promise(k=>{let M=!1,_=null,Y=!1,me=!1,Se=[],Me=T=>{Se.push(T)},bt=()=>{Se.pop(),M||Se[Se.length-1]?.onResize()},Pn={push:Me,pop:bt};at=()=>{F=new vn({history:[],collapsePastes:!1}),z=[],J=!1,X=0,D=0,_e=0,$=null,W=!1,C="input",x=!1,bt()};let as=(T,j,ie)=>{Ps(),Se[Se.length-1]?.onKey(T,j,ie)},fn=()=>{M||Se[Se.length-1]?.onResize()},dt=()=>{if(M)return;M=!0,Se.length=0,_&&(clearInterval(_),_=null),t.off("key",as),t.off("resize",fn),process.stdout.write("\x1B[?2004l");let T=t;T.stdin&&wt&&(T.stdin.removeListener("data",En),T.stdin.on("data",wt),wt=null),Rn=!1,Tn="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,Er()+1),t(`
197
- `)},vt=()=>{if(M||Se.length>1||v!=="normal"||u||Y||me)return;let T=l>0?i[l-1]?.sessionId:void 0;Y=!0,Ze(T,{silent:!0}).finally(()=>{Y=!1})},Ps=()=>{M||(_&&clearInterval(_),_=setInterval(vt,3e3))},Rt=()=>(dt(),k({kind:he?"exit":"abort"}),!0),Ye=()=>{let T=a.map(j=>`${j.session}|${j.upstream}|${j.host}|${j.state}|${j.agent}|${j.model}|${j.age}|${j.title}|${j.cwd}|${j.cost}`).join(`
198
- `);return`${l}:${f}:${ee??""}
199
- ${T}`},Ze=async(T,j={})=>{try{let ie=j.silent?Ye():"",O=c,se=await yn(e.target,{includeNonInteractive:!0}),Z=T??(l>0?i[l-1]?.sessionId:void 0);if(s=Bc(se,e.cwd),gt(),Z!==void 0){let be=i.findIndex(Te=>Te.sessionId===Z);be>=0?l=be+1:l=0}if(l>c-1&&(l=Math.max(0,c-1)),f+ge>i.length&&(f=Math.max(0,i.length-ge)),Xe(),j.silent&&Ye()===ie)return;c===O?$r():Re()}catch(ie){if(j.silent)return;ee=`refresh failed: ${ie.message}`,Re()}},Jt=async T=>{if(!b)return;let j=b;v="busy",Ie();try{await mp(e.target,j.sessionId,T),v="normal",b=null,K="",await Ze(j.sessionId)}catch(ie){v="normal",b=null,K="",ee=`rename failed: ${ie.message}`,Ie()}},Ms=async T=>{try{await gp(e.target,T.sessionId),ee="title regen queued (press r to refresh)",Ie()}catch(j){ee=`regen failed: ${j.message}`,Ie()}},Kt=async T=>{let ie=(T.priority&&T.priority>0?T.priority:0)>0?null:1,O=ie??0;for(let Z of s)Z.sessionId===T.sessionId&&(Z.priority=O>0?O:void 0);let se=T.sessionId;s=Bc(s,e.cwd),gt(),Pe(se),Re(),ee=O>0?"priority: high":"priority: normal",Ie();try{await hp(e.target,T.sessionId,ie)}catch(Z){ee=`priority failed: ${Z.message}`,Ie()}},ds=async()=>{if(me)return;me=!0;let T=l>0?i[l-1]?.sessionId:void 0;ee="syncing agents\u2026",Ie();try{let{synced:j,skipped:ie,agents:O}=await fp(e.target);await Ze(T),ee=`synced ${j} new (${ie} known) from ${O} agent${O===1?"":"s"}`,Ie()}catch(j){ee=`sync failed: ${j.message}`,Ie()}finally{me=!1}},Pi=async T=>{if(!b)return;let j=b;v="busy",Ie();try{T==="kill"?await ii(e.target,j.sessionId):await wp(e.target,j.sessionId),v="normal",b=null,j.sessionId===e.currentSessionId&&(he=!0);let ie;if(T==="kill")ie=j.sessionId;else{let O=i.findIndex(se=>se.sessionId===j.sessionId);O>=0&&(ie=i[O+1]?.sessionId??i[O-1]?.sessionId)}await Ze(ie)}catch(ie){v="normal",b=null,ee=`${T} failed: ${ie.message}`,Ie()}},Or=(T,j)=>{T===0!=(j===0)&&(Ca(),j===0?(t.hideCursor(!1),He()):t.hideCursor())},ct=T=>{let j=Math.min(c-1,Math.max(0,l+T));if(j===l)return;let ie=l;l=j,Xe(),$e(()=>{Es(),Or(ie,l)})},Ra=()=>ee===null?!1:(ee=null,Ie(),!0),Mi=()=>{jt(),Me({onKey:T=>{if(T==="CTRL_C"){dt(),k({kind:"abort"});return}bt()},onResize:()=>jt()})},Fr=T=>{let j=null,ie=null,O=!0,se=()=>{$e(()=>{if(t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${je(T.sessionId)}`)(`
193
+ `)})},de=()=>ot+4,Ti=2,_e=0,ze=()=>{X=Uc(t);let k=Math.max(2,X-(ot+3)-Ti);return Math.max(1,Math.floor(k/2))},as=()=>{let k=ze();$<_e?_e=$:$>=_e+k&&(_e=$-k+1),_e+k>W.length&&(_e=Math.max(0,W.length-k)),_e<0&&(_e=0)},ds=k=>{ee=Cs(t);let P=Math.max(2,ee-2),O="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,P-O.length));k?t.brightBlue.noFormat(`\u256D${O}${Y}\u256E`):t.dim.noFormat(`\u256D${O}${Y}\u256E`),t.styleReset()},S=()=>{ee=Cs(t),be=Math.max(10,ee-Ah);let k=Q.state();Es=An(k.buffer,be);let P=es(Es,k,Kk);ot=P.rendered,ln=P.windowStart,Ps=P.cursorVisualRow,rs=P.cursorVisualCol},$s=(k,P)=>{ee=Cs(t);let O=Math.max(2,ee-2),Y=Es[k],ge="";Y&&(ge=(Q.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let Ie=Math.max(0,O-1-ge.length),Me=" ".repeat(Ie);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${ge}${Me}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${ge}${Me}`),t.dim.noFormat("\u2502")),t.styleReset()},Ei=k=>{ee=Cs(t);let P=Math.max(2,ee-2),O="\u2500".repeat(P);k?t.brightBlue.noFormat(`\u2570${O}\u256F`):t.dim.noFormat(`\u2570${O}\u256F`),t.styleReset()},Tn=()=>3+rs,zt=()=>2+(Ps-ln),Jt=()=>{let k=_==="input";$e(()=>{k&&t.hideCursor(),t.moveTo(1,1),ds(k);for(let P=0;P<ot;P++)t.moveTo(1,2+P),$s(ln+P,k);t.moveTo(1,2+ot),Ei(k),k&&(t.moveTo(Tn(),zt()),t.hideCursor(!1))})},Fr=()=>{$e(()=>{t.hideCursor();for(let k=0;k<ot;k++)t.moveTo(1,2+k),$s(ln+k,!0);t.moveTo(Tn(),zt()),t.hideCursor(!1)})},Ta={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Pi=(k,P)=>{let O=W[k];if(!O)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Cs(t),ge=Math.max(20,Y-Hc),Ie=qe(O.sessionId),Me=O.title??Ne(O.cwd),vt=P&&O.snippets.length>1?` [${D+1}/${O.snippets.length}]`:P&&O.totalMatches>O.snippets.length?` [${O.snippets.length} of ${O.totalMatches}]`:"",_n=`${Ie} ${O.status==="live"?"live":"cold"}`,Ls=Math.max(5,ge-_n.length-vt.length-2),ls=fi(Me,Ls),us=`${_n} ${ls}${vt}`.padEnd(ge),lt=O.snippets[P?D:0],Ze=lt?Ta[lt.kind]??lt.kind:"",Vt=lt?.toolName?`${Ze} \xB7 ${lt.toolName}`:Ze,et=Math.max(10,ge-Vt.length-6),ut=lt?fi(lt.text,et):"",Nt=lt?` ${Vt} ${ut}`:" (no snippet)";return{rowBudget:ge,line1:us,line2:Nt.padEnd(ge+Hc),focusedRow:P}},_s=(k,P)=>{let{line1:O,focusedRow:Y}=Pi(k,P);Y?t.brightWhite.bgBlue.noFormat(`\u276F ${O}`):t.noFormat(` ${O}`),t.styleReset()},Kt=(k,P)=>{let{line2:O}=Pi(k,P);t.dim.noFormat(O),t.styleReset()},cs=()=>{if(Z)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(j!==null)t.brightRed.noFormat(` ${j}`),t.styleReset(),t.eraseLineAfter();else if(_==="input")W.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let k=W.length,P=z?" \xB7 truncated":"",O=k>0?` ${k} ${k===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${O}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},pn=()=>{S();let k=_==="input",P=Q.state().buffer.join(`
194
+ `);$e(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),ds(k);for(let Y=0;Y<ot;Y++)t.moveTo(1,2+Y),$s(ln+Y,k);t.moveTo(1,2+ot),Ei(k);let O=W.length;if(O===0)t.moveTo(1,de()),Z||(j===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):j===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,de()+1),cs();else{as();let Y=ze(),ge=_!=="input";for(let Ie=0;Ie<Y;Ie++){let Me=_e+Ie;t.moveTo(1,de()+Ie*2),Me<O?_s(Me,ge&&Me===$):t.eraseLineAfter(),t.moveTo(1,de()+Ie*2+1),Me<O?Kt(Me,ge&&Me===$):t.eraseLineAfter()}t.moveTo(1,de()+Y*2),cs()}k&&(t.moveTo(Tn(),zt()),t.hideCursor(!1))})},En=(k,P)=>{let O=k-_e;O<0||O>=ze()||$e(()=>{t.moveTo(1,de()+O*2),_s(k,P),t.moveTo(1,de()+O*2+1),Kt(k,P)})},Os=()=>{$e(()=>{t.moveTo(1,de()+ze()*2),cs()})},Mi=()=>{$e(()=>{let k=ze(),P=W.length,O=_!=="input";for(let Y=0;Y<k;Y++){let ge=_e+Y;t.moveTo(1,de()+Y*2),ge<P?_s(ge,O&&ge===$):t.eraseLineAfter(),t.moveTo(1,de()+Y*2+1),ge<P?Kt(ge,O&&ge===$):t.eraseLineAfter()}t.moveTo(1,de()+k*2),cs()})},$i=()=>Q.state().buffer.join(`
195
+ `),Ea=k=>{let P=ot;Q.feed({type:"paste",text:k}),S(),ot!==P?pn():Fr()},Ct=async()=>{let k=$i().trim();if(k.length!==0){if(o.length===0){j="no sessions in view to search",pn();return}Z=!0,j=null,pn();try{let P=await vp(e.target,k,{sessionIds:o.map(O=>O.sessionId)});W=P.results,z=P.truncated,$=0,D=0,_e=0,_=P.results.length>0?"results":"input",S()}catch(P){j=`search failed: ${P.message}`}finally{Z=!1,pn()}}},ct=()=>{},Pa=()=>{$e(()=>{let k=u===0;k&&t.hideCursor(),t.moveTo(1,ss),Ms(),t.moveTo(1,_r()),Cn();for(let P=0;P<yt;P++)t.moveTo(1,fn(P)),is(Bt+P);k&&(Ue(),t.hideCursor(!1))})},Lr=()=>{$e(()=>{let k=K.state();Lt=An(k.buffer,Ft);let P=es(Lt,k,Aa);Bt=P.windowStart,ns=P.cursorVisualRow,Ts=P.cursorVisualCol;let O=u===0;O&&t.hideCursor();for(let Y=0;Y<yt;Y++)t.moveTo(1,fn(Y)),is(Bt+Y);O&&(Ue(),t.hideCursor(!1))})},_i=k=>{k<f||k>=f+Re||$e(()=>{t.moveTo(1,os(k)),un(k)})},Fs=()=>{$e(()=>{for(let k=0;k<Re;k++){let P=wt()+1+k,O=f+k;O<o.length?(t.moveTo(1,P),un(O)):t.moveTo(1,P).eraseLineAfter()}ve()})},Br=()=>{$e(()=>{t.moveTo(1,wt()),t.dim.noFormat(` ${cn}`);for(let k=0;k<Re;k++){let P=wt()+1+k,O=f+k;O<o.length?(t.moveTo(1,P),un(O)):t.moveTo(1,P).eraseLineAfter()}ve(),u===0&&(Ue(),t.hideCursor(!1))})},Pn=!1,Mn="",bt=null,mn=null,Rt="\x1B[200~",Nr="\x1B[201~",$n=k=>{let P=k.toString("binary");if(!Pn&&P===""&&mn){mn();return}if(Pn){let Y=P.indexOf(Nr);if(Y===-1){Mn+=P;return}Mn+=P.slice(0,Y),Pn=!1;let ge=Buffer.from(Mn,"binary").toString("utf-8").replace(/\r\n?/g,`
196
+ `);Mn="";let Ie=P.slice(Y+Nr.length);if(M)_==="input"&&!Z&&Ea(ge);else if(u===0&&!p){K.feed({type:"paste",text:ge});let Me=K.state(),vt=An(Me.buffer,Ft);es(vt,Me,Aa).rendered!==yt?ke():Lr()}Ie.length>0&&bt&&bt(Buffer.from(Ie,"binary"));return}let O=P.indexOf(Rt);if(O===-1){bt?.(k);return}O>0&&bt?.(Buffer.from(P.slice(0,O),"binary")),P=P.slice(O+Rt.length),Pn=!0,P.length>0&&$n(Buffer.from(P,"binary"))};return ke(),await new Promise(k=>{let P=!1,O=null,Y=!1,ge=!1,Ie=[],Me=C=>{Ie.push(C)},vt=()=>{Ie.pop(),P||Ie[Ie.length-1]?.onResize()},_n={push:Me,pop:vt},Ls=()=>{let C={kind:"new"};return s!==e.cwd&&(C.cwd=s),C},ls=async()=>{Ln(),t.moveTo(1,1).eraseDisplayBelow();let C=await As(t,void 0,{defaultCwd:s,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"});Dt(),C.kind==="ok"&&C.path!==s&&(s=C.path,r=Ca(r,s),at()),P||ke()};ct=()=>{Q=new kn({history:[],collapsePastes:!1}),W=[],z=!1,$=0,D=0,_e=0,j=null,Z=!1,_="input",M=!1,vt()};let us=(C,U,ae)=>{et(),Ie[Ie.length-1]?.onKey(C,U,ae)},lt=()=>{P||Ie[Ie.length-1]?.onResize()},Ze=()=>{if(P)return;P=!0,Ie.length=0,O&&(clearInterval(O),O=null),t.off("key",us),t.off("resize",lt),process.stdout.write("\x1B[?2004l");let C=t;C.stdin&&bt&&(C.stdin.removeListener("data",$n),C.stdin.on("data",bt),bt=null),Pn=!1,Mn="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,Or()+1),t(`
197
+ `)},Vt=()=>{if(P||Ie.length>1||b!=="normal"||p||Y||ge)return;let C=u>0?o[u-1]?.sessionId:void 0;Y=!0,Yt(C,{silent:!0}).finally(()=>{Y=!1})},et=()=>{P||(O&&clearInterval(O),O=setInterval(Vt,3e3))},ut=()=>(Ze(),k({kind:Ee?"exit":"abort"}),!0),Nt=()=>{let C=d.map(U=>`${U.session}|${U.upstream}|${U.host}|${U.state}|${U.agent}|${U.model}|${U.age}|${U.title}|${U.cwd}|${U.cost}`).join(`
198
+ `);return`${u}:${f}:${se??""}
199
+ ${C}`},Yt=async(C,U={})=>{try{let ae=U.silent?Nt():"",F=l,re=await vn(e.target,{includeNonInteractive:!0}),J=C??(u>0?o[u-1]?.sessionId:void 0);if(r=Ca(re,s),at(),J!==void 0){let le=o.findIndex(Je=>Je.sessionId===J);le>=0?u=le+1:u=0}if(u>l-1&&(u=Math.max(0,l-1)),f+Re>o.length&&(f=Math.max(0,o.length-Re)),Xe(),U.silent&&Nt()===ae)return;l===F?Br():ke()}catch(ae){if(U.silent)return;se=`refresh failed: ${ae.message}`,ke()}},Qt=async C=>{if(!x)return;let U=x;b="busy",ve();try{await yp(e.target,U.sessionId,C),b="normal",x=null,ie="",await Yt(U.sessionId)}catch(ae){b="normal",x=null,ie="",se=`rename failed: ${ae.message}`,ve()}},fs=async C=>{try{await bp(e.target,C.sessionId),se="title regen queued (press r to refresh)",ve()}catch(U){se=`regen failed: ${U.message}`,ve()}},Oi=async C=>{let ae=(C.priority&&C.priority>0?C.priority:0)>0?null:1,F=ae??0;for(let J of r)J.sessionId===C.sessionId&&(J.priority=F>0?F:void 0);let re=C.sessionId;r=Ca(r,s),at(),Te(re),ke(),se=F>0?"priority: high":"priority: normal",ve();try{await wp(e.target,C.sessionId,ae)}catch(J){se=`priority failed: ${J.message}`,ve()}},Dr=async()=>{if(ge)return;ge=!0;let C=u>0?o[u-1]?.sessionId:void 0;se="syncing agents\u2026",ve();try{let{synced:U,skipped:ae,agents:F}=await hp(e.target);await Yt(C),se=`synced ${U} new (${ae} known) from ${F} agent${F===1?"":"s"}`,ve()}catch(U){se=`sync failed: ${U.message}`,ve()}finally{ge=!1}},Fi=async C=>{if(!x)return;let U=x;b="busy",ve();try{C==="kill"?await rn(e.target,U.sessionId):await Ip(e.target,U.sessionId),b="normal",x=null,U.sessionId===e.currentSessionId&&(Ee=!0);let ae;if(C==="kill")ae=U.sessionId;else{let F=o.findIndex(re=>re.sessionId===U.sessionId);F>=0&&(ae=o[F+1]?.sessionId??o[F-1]?.sessionId)}await Yt(ae)}catch(ae){b="normal",x=null,se=`${C} failed: ${ae.message}`,ve()}},Ma=(C,U)=>{C===0!=(U===0)&&(Pa(),U===0?(t.hideCursor(!1),Ue()):t.hideCursor())},It=C=>{let U=Math.min(l-1,Math.max(0,u+C));if(U===u)return;let ae=u;u=U,Xe(),$e(()=>{Fs(),Ma(ae,u)})},Hr=()=>se===null?!1:(se=null,ve(),!0),ft=()=>{Wt(),Me({onKey:C=>{if(C==="CTRL_C"){Ze(),k({kind:"abort"});return}vt()},onResize:()=>Wt()})},On=C=>{let U=null,ae=null,F=!0,re=()=>{$e(()=>{if(t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${qe(C.sessionId)}`)(`
200
200
 
201
- `),O)t.dim.noFormat(" loading\u2026")(`
202
- `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
203
- `);else if(j!==null)for(let Z of j)t.noFormat(` ${Z}`)(`
201
+ `),F)t.dim.noFormat(" loading\u2026")(`
202
+ `);else if(ae!==null)t.brightRed.noFormat(` ${ae}`)(`
203
+ `);else if(U!==null)for(let J of U)t.noFormat(` ${J}`)(`
204
204
  `);t(`
205
205
  `),t.dim.noFormat(" Esc / ^C to return")(`
206
- `)})};se(),Me({onKey:Z=>{if(Z==="ESCAPE"||Z==="CTRL_C"){bt();return}},onResize:()=>se()}),(async()=>{try{let Z=await fetch(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(T.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`}});if(!Z.ok)throw new Error(`daemon returned HTTP ${Z.status}`);let be=await Z.json(),Te=Ut(be),xe=Xd(Te,T.status);j=ea(xe,!1).replace(/\n$/,"").split(`
207
- `)}catch(Z){ie=`failed to load info: ${Z.message}`}finally{O=!1,se()}})()},lt=()=>{if(i.length===0){ee="no sessions to search",Ie();return}F=new vn({history:[],collapsePastes:!1}),z=[],J=!1,X=0,D=0,_e=0,$=null,W=!1,C="input",x=!0,S(),ln(),Me({onKey:(j,ie,O)=>{if(C==="input"){if(W)return;if(j==="ESCAPE"||j==="CTRL_C"){at();return}if(j==="ENTER"||j==="KP_ENTER"){if(Ti().trim().length===0)return;At();return}if((j==="DOWN"||j==="TAB"||j==="CTRL_N")&&z.length>0){C="results",X=0,D=0,$e(()=>{Wt(),Cn(0,!0),Ts(),t.hideCursor()});return}let se=F.state(),Z=null;if(O?.isCharacter)Z={type:"char",ch:j};else{let ze=ba(j);ze!==null&&(Z={type:"key",name:ze})}if(Z===null){t.moveTo(An(),qt());return}F.feed(Z);let be=F.state();if(se.buffer.length===be.buffer.length&&se.buffer.every((ze,Ee)=>ze===be.buffer[Ee])&&se.row===be.row&&se.col===be.col){t.moveTo(An(),qt());return}let xe=it;S(),it!==xe?ln():Pr();return}if(C==="results"){if(j==="ESCAPE"||j==="CTRL_C"){at();return}if(j==="CTRL_F"){C="input",Ri(),Ts(),Wt();return}if(j==="ENTER"||j==="KP_ENTER"){let Z=z[X];if(!Z)return;let be=i.find(xe=>xe.sessionId===Z.sessionId);if(!!be?.importedFromMachine&&!be.upstreamSessionId){dt();let xe={kind:"attach",sessionId:Z.sessionId};be.agentId!==void 0&&(xe.agentId=be.agentId),k(xe);return}(async()=>{let xe=await wh(t,{sessionId:Z.sessionId,title:Z.title,cwd:Z.cwd},Pn);if(xe==="cancel"){dt(),k({kind:"abort"});return}if(xe==="back")return;dt();let ze={kind:"attach",sessionId:Z.sessionId,readonly:xe==="view"};be?.agentId!==void 0&&(ze.agentId=be.agentId),k(ze)})();return}if(O?.isCharacter&&(j==="n"||j==="N")){let Z=z[X];if(!Z||Z.snippets.length<=1)return;D=(D+1)%Z.snippets.length,Cn(X,!0);return}if(O?.isCharacter&&(j==="p"||j==="P")){let Z=z[X];if(!Z||Z.snippets.length<=1)return;D=(D-1+Z.snippets.length)%Z.snippets.length,Cn(X,!0);return}let se=Z=>{if(Z<0&&X===0){C="input",$e(()=>{Cn(0,!1),Ts(),Wt()});return}let be=Math.min(z.length-1,Math.max(0,X+Z));if(be===X)return;let Te=X,xe=_e;X=be,D=0,rs(),_e!==xe?Ri():($e(()=>{Cn(Te,!1),Cn(X,!0)}),Ts())};switch(j){case"UP":case"SHIFT_TAB":case"CTRL_P":se(-1);return;case"DOWN":case"TAB":case"CTRL_N":se(1);return;case"PAGE_UP":se(-We());return;case"PAGE_DOWN":se(We());return;case"HOME":se(-X);return;case"END":se(z.length);return}return}},onResize:()=>ln()})},Mn=(T,j,ie)=>{if(v!=="busy"){if(v==="rename"){if(T==="ENTER"||T==="KP_ENTER"){let O=K.trim();if(O.length===0){v="normal",b=null,K="",Ie();return}Jt(O);return}if(T==="ESCAPE"||T==="CTRL_C"){v="normal",b=null,K="",Ie();return}if(T==="BACKSPACE"){K.length>0&&(K=K.slice(0,-1),Ie());return}if(T==="CTRL_U"){K="",Ie();return}if(T==="CTRL_W"){let O=K.replace(/\s+$/,""),se=O.lastIndexOf(" ");K=se>=0?O.slice(0,se):"",Ie();return}if(ie?.isCharacter){K+=T,Ie();return}return}if(v==="confirm-kill"||v==="confirm-delete"){if(ie?.isCharacter&&(T==="y"||T==="Y")){Pi(v==="confirm-kill"?"kill":"delete");return}if(T==="ESCAPE"||T==="CTRL_C"||T==="ENTER"||T==="KP_ENTER"||ie?.isCharacter&&(T==="n"||T==="N")){v="normal",b=null,Ie();return}return}if(Ra(),T==="CTRL_F"){lt();return}if(l===0&&!u){if(T==="ESCAPE"){Rt();return}if(T==="ENTER"||T==="KP_ENTER"){dt();let Ee=ke.expandedText();Ee.trim().length===0?k({kind:"new"}):k({kind:"new",prompt:Ee});return}if(T==="UP"&&h){let Ee=Date.now(),Tt=Ee-y;if(y=Ee,Tt<g){He();return}h=!1}if(T==="DOWN"){let Ee=ke.state(),Tt=Ee.historyIndex!==-1||Ee.queueIndex!==-1,$i=Bt.length===0||Zn===Bt.length-1;if(!Tt&&$i&&i.length>0){ct(1);return}}if(T==="PAGE_DOWN"&&(Bt.length===0||Zn===Bt.length-1)&&i.length>0){ct(1);return}if(T==="CTRL_P"){i.length>0&&ct(1);return}h=!1;let O=ke.state(),se=null;if(ie?.isCharacter)se={type:"char",ch:T};else{let Ee=ba(T);Ee!==null&&(se={type:"key",name:Ee})}if(se===null){He();return}let Z=ke.feed(se),be=ke.state(),Te=O.buffer.length===be.buffer.length&&O.buffer.every((Ee,Tt)=>Ee===be.buffer[Tt])&&O.row===be.row&&O.col===be.col;if(Z.some(Ee=>Ee.type==="exit")){Rt();return}if(Te){He();return}let xe=Sn(be.buffer,Lt);if(Qn(xe,be,Ia).rendered!==ht){Re();return}Mr();return}if(!u&&ie?.isCharacter&&T==="?"){Mi();return}if(u){if(ie?.isCharacter){p+=T,gt(),Re();return}if(T==="BACKSPACE"){p.length>0?(p=p.slice(0,-1),gt(),Re()):(u=!1,gt(),Re());return}if(T==="ESCAPE"||T==="CTRL_C"){u=!1,p="",gt(),Re();return}}if(ie?.isCharacter){if(T==="/"){u=!0,p="",gt(),Re();return}if(T==="n"||T==="N"){ct(1);return}if(T==="p"||T==="P"){ct(-1);return}if(T==="c"||T==="C"){dt(),k({kind:"new"});return}if(T==="q"||T==="Q"){Rt();return}if(T==="o"||T==="O"){let O=l>0?i[l-1]?.sessionId:void 0;n.filters.cwdOnly=!n.filters.cwdOnly,gt(),Pe(O),Re();return}if(T==="h"||T==="H"){let O=l>0?i[l-1]?.sessionId:void 0;n.filters.hostFilter=Qk(n.filters.hostFilter,s),gt(),Pe(O),Re();return}if(T==="i"&&l>0){let O=i[l-1];if(!O)return;Fr(O);return}if(T==="I"){let O=l>0?i[l-1]?.sessionId:void 0;n.filters.includeNonInteractive=!n.filters.includeNonInteractive,gt(),Pe(O),Re();return}if(T==="r"||T==="R"){let O=l>0?i[l-1]?.sessionId:void 0;Ze(O);return}if(T==="s"||T==="S"){ds();return}if((T==="v"||T==="V")&&l>0){let O=i[l-1];if(!O)return;dt();let se={kind:"attach",sessionId:O.sessionId,readonly:!0};O.agentId!==void 0&&(se.agentId=O.agentId),k(se);return}if((T==="f"||T==="F")&&l>0){let O=i[l-1];if(!O)return;dt();let se={kind:"fork",sourceSessionId:O.sessionId,sourceCwd:O.cwd};O.agentId!==void 0&&(se.sourceAgentId=O.agentId),O.importedFromMachine!==void 0&&(se.sourceImportedFromMachine=O.importedFromMachine),O.upstreamSessionId!==void 0&&(se.sourceUpstreamSessionId=O.upstreamSessionId),k(se);return}if((T==="k"||T==="K")&&l>0){let O=i[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},v="confirm-kill",Ie();return}if(T==="t"&&l>0){let O=i[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},K=O.title??"",v="rename",Ie();return}if(T==="T"&&l>0){let O=i[l-1];if(!O||O.status!=="live")return;Ms({sessionId:O.sessionId});return}if(T==="*"&&l>0){let O=i[l-1];if(!O)return;Kt(O);return}if((T==="d"||T==="D")&&l>0){let O=i[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},v="confirm-delete",Ie();return}return}switch(T){case"UP":case"SHIFT_TAB":case"CTRL_P":T==="UP"&&(l===1&&(h=!0),y=Date.now()),ct(-1);return;case"DOWN":case"TAB":case"CTRL_N":ct(1);return;case"PAGE_UP":ct(-ge);return;case"PAGE_DOWN":ct(ge);return;case"HOME":ct(1-l);return;case"END":ct(c);return;case"ENTER":case"KP_ENTER":{if(dt(),l===0){k({kind:"new"});return}let O=i[l-1];if(!O){k({kind:"abort"});return}let se={kind:"attach",sessionId:O.sessionId};O.agentId!==void 0&&(se.agentId=O.agentId),k(se);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Rt();return}}};Me({onKey:(T,j,ie)=>Mn(T,j,ie),onResize:()=>{M||Re()}});let Vt=()=>{t.grabInput({});let T=t;T.stdin&&typeof T.onStdin=="function"&&(wt=T.onStdin,T.stdin.removeListener("data",T.onStdin),T.stdin.on("data",En),process.stdout.write("\x1B[?2004h")),t.on("key",as),t.on("resize",fn)},$n=()=>{process.stdout.write("\x1B[?2004l");let T=t;T.stdin&&wt&&(T.stdin.removeListener("data",En),T.stdin.on("data",wt),wt=null),Rn=!1,Tn="",t.off("key",as),t.off("resize",fn),t.grabInput(!1),t.hideCursor(!1)};if(Vt(),process.platform!=="win32"){let T=!1,j=()=>{T&&(T=!1,process.stdout.write("\x1B[?1049h"),Vt(),M||Re())};un=()=>{T||M||(T=!0,$n(),process.stdout.write(`\x1B[?1049l\x1B[?7h\x1B[?25h
208
- `),process.once("SIGCONT",j),process.kill(process.pid,"SIGTSTP"))}}_=setInterval(vt,3e3)})}function Lc(t){let e=t.height;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:24}function Is(t){let e=t.width;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:80}function Vk(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+ai(Be(t),s)}function Bc(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="live",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function Yk(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Qk(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function Gk(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[je(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Be(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Fc,Ia,zk,vh,Jk,Kk,Ih=V(()=>{"use strict";Qo();ue();en();oi();po();hc();Pc();Oc();Ic();hs();Zd();Fc=2,Ia=4,zk=4,vh=4,Jk=20,Kk=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected live session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent (live session)"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});function Ii(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function Sh(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=Ii(e);return o.length<=r.length?null:o+i}var Sa=V(()=>{"use strict"});import*as kh from"os";async function Si(t,e,n={}){let s=n.defaultCwd??await jm(e.cwd)??kh.homedir();xr();let r=je(e.sessionId),i=Be(e.cwd),o=n.title??"Fork locally \u2014 choose cwd",a=n.intro??"Pick a local cwd for this session:",d=[{label:"session: ",value:r},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:i}],c=s,l=null,f=!1,u=null,p=()=>{let v=d.length+6;u=vs(t,{contentHeight:v,title:o});let b=u.contentW,x=0;for(let C of d)t.moveTo(u.contentX,u.contentY+x),t.dim.noFormat(` ${C.label}`),t.noFormat(Hc(C.value,b-C.label.length-2)),x++;x++,t.moveTo(u.contentX,u.contentY+x),t.noFormat(` ${a}`),x+=2,h(x),x+=2,l!==null?(t.moveTo(u.contentX,u.contentY+x),t.red.noFormat(` ${Hc(l,b-2)}`)):(t.moveTo(u.contentX,u.contentY+x),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},g=()=>d.length+3,h=v=>{if(!u)return;let b=v??g();t.moveTo(u.contentX,u.contentY+b).eraseLineAfter(),t.moveTo(u.x+u.w-1,u.contentY+b),t.dim.noFormat("\u2502"),t.moveTo(u.contentX,u.contentY+b),t.bold.noFormat(" cwd: ");let x=u.contentW-6-2;t.noFormat(Xk(c,x)),f||t.bgWhite(" ")},y=()=>{if(h(),!u)return;let v=g()+2;t.moveTo(u.contentX,u.contentY+v).eraseLineAfter(),t.moveTo(u.x+u.w-1,u.contentY+v),t.dim.noFormat("\u2502"),t.moveTo(u.contentX,u.contentY+v),l!==null?t.red.noFormat(` ${Hc(l,u.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return p(),await new Promise(v=>{let b=!1,x=()=>{b||(b=!0,t.off("key",z),t.off("resize",F),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},C=J=>{x(),v(J)},F=()=>{b||p()},z=(J,X,D)=>{if(!f){if(J==="ENTER"||J==="KP_ENTER"){let $=c;f=!0,l=null,y(),hi($).then(W=>{if(f=!1,W.ok){C({kind:"ok",path:W.path});return}l=W.reason,y()});return}if(J==="ESCAPE"){C({kind:"back"});return}if(J==="CTRL_C"||J==="CTRL_D"){C({kind:"cancel"});return}if(J==="TAB"){f=!0,qm(c).then($=>{if(f=!1,$.matches.length===0)return;let W;if($.matches.length===1)W=$.prefix+$.matches[0];else{let K=Ii($.matches);if(K.length<=$.basePrefix.length)return;W=$.prefix+K}W!==c&&(c=W,l=null,y())});return}if(J==="BACKSPACE"){c.length>0&&(c=c.slice(0,-1),l=null,y());return}if(J==="CTRL_U"){c="",l=null,y();return}if(J==="CTRL_W"){let $=c.replace(/[/\s]+$/,""),W=Math.max($.lastIndexOf("/"),$.lastIndexOf(" "));c=W>=0?$.slice(0,W+1):"",l=null,y();return}if(D?.isCharacter){c+=J,l=null,y();return}}};t.grabInput({}),t.on("key",z),t.on("resize",F)})}function Hc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Xk(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var xh=V(()=>{"use strict";ue();en();uc();Sa();va()});function nx(t){let e=t.findIndex(n=>n.id===Zk);return e===-1?0:e}async function Ch(t,e){xr();let n=nx(e),s=0,r=()=>{let a=$c(t)-8;return Math.max(1,Math.min(ex,e.length,a))},i=()=>{let a=r();n<s?s=n:n>=s+a&&(s=n-a+1);let d=Math.max(0,e.length-a);s>d&&(s=d),s<0&&(s=0)},o=()=>{i();let a=r(),d=a+4,c=Math.min(tx,Math.max(40,Mc(t)-8)),l=vs(t,{contentHeight:d,contentWidth:c,title:"Select agent"}),f=l.contentW,u=0;t.moveTo(l.contentX,l.contentY+u),t.noFormat(" Which agent should this session use?"),u+=2;let p=Math.min(e.length,s+a);for(let h=s;h<p;h++){let y=e[h];if(!y)continue;let v=h===n?"\u276F":" ",b=y.description??y.name,x=` ${v} ${y.id}`;if(t.moveTo(l.contentX,l.contentY+u),h===n){let C=`${x} ${b}`;t.brightWhite.bgBlue.noFormat(sx(Ah(C,f),f))}else{t.noFormat(x);let C=f-x.length-2;C>1&&t.dim.noFormat(` ${Ah(b,C)}`)}u++}u++,t.moveTo(l.contentX,l.contentY+u);let g=e.length>a?` (${n+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${g}`),l};return o(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",g),t.off("resize",f),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=h=>{c(),a(h)},f=()=>{d||o()},u=()=>{n<e.length-1&&(n++,o())},p=()=>{n>0&&(n--,o())},g=(h,y,v)=>{if(h==="CTRL_C"||h==="CTRL_D"){l({kind:"cancel"});return}if(h==="ESCAPE"){l({kind:"back"});return}if(h==="ENTER"||h==="KP_ENTER"){let b=e[n];b&&l({kind:"select",agentId:b.id,persist:!1});return}if(h==="UP"||h==="SHIFT_TAB"){p();return}if(h==="DOWN"||h==="TAB"){u();return}if(v?.isCharacter){let b=h.toLowerCase();if(b==="s"){let x=e[n];x&&l({kind:"select",agentId:x.id,persist:!0});return}if(b==="j"){u();return}if(b==="k"){p();return}}};t.grabInput({}),t.on("key",g),t.on("resize",f)})}function Ah(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function sx(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var Zk,ex,tx,Rh=V(()=>{"use strict";va();Zk="opencode",ex=20,tx=88});import*as Eh from"fs";import*as Ph from"os";import*as ka from"path";function Mh(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function rx(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function ix(t){return t.replace(/\\ /g," ")}function Th(t){return t.replace(/ /g,"\\ ")}function ox(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function ax(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Ph.homedir()+n.slice(1)),ka.isAbsolute(n)?n:ka.resolve(e,n)}function dx(t){let e;try{e=Eh.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function $h(t,e,n=dx){if(!rx(t))return null;let s=ix(t),{dirPrefix:r,base:i}=ox(s),o=ax(r,e),a=n(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(u=>u.name.startsWith(i)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:Th(r+p),candidates:l}}let f=Ii(c.map(u=>u.name));return{replacement:Th(r+f),candidates:l}}var _h=V(()=>{"use strict";Sa()});function Oh(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Fh(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Lh(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var Bh=V(()=>{"use strict"});import{appendFileSync as cx,statSync as lx,renameSync as ux}from"fs";import{nanoid as Nh}from"nanoid";import fx from"terminal-kit";import px from"fs/promises";import Uc from"path";function Dh(t){if(!Array.isArray(t))return;let e=gn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Hh(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}async function qh(t){let e=await G(),n=t.target??await Qt(e);Jh=e.tui.logMaxBytes,n.isLocal&&!t.target&&await or(e);let s=fx.terminal;gh(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:gl(e),defaultEnterAction:e.tui.defaultEnterAction},o=Nc(),a=!1,d=()=>{a||(s.fullscreen(!0),a=!0)},c=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
209
- `))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await gx(s,e,n,f,r,i,o)}finally{c(),process.off("exit",l)}let u=await fi();if(u&&process.stderr.write(`\u2728 ${pi(u)}
210
- `),process.stdout.isTTY){let p=await ar(e);if(p?.version!==void 0){let g=p.version!==ce,h=nr(e),y=p.configDigest!==void 0&&p.configDigest!==h;if(g||y){let v=g?`daemon ${p.version} \u2260 cli ${ce}`:"config changed since daemon started",b=x=>`\x1B[33m${x}\x1B[0m`;process.stderr.write(b(`! ${v} \u2014 run \`${Fn()} daemon restart\` to apply.`)+`
211
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=je(r.sessionId),g=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Fn()} --session ${p}${g}
212
- `)}}async function gx(t,e,n,s,r,i,o){let a=await yx(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let d=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",c=vx(t,d);c.write(d);let l=n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,g=new vr({url:l,subprotocols:f,onConnect:async m=>{m||u&&await u()},onDisconnect:m=>{p&&p(m)},log:()=>{}}),h=new Mt(g);await g.start(),h.onNotification(Zi,m=>{let w=fu.safeParse(m);w.success&&c.applyProgress(w.data)});let y=[],v=null,b=!1,x=!1,C=m=>{m&&(v?v(m):y.push(m))},F,z=m=>{m!==F&&(F=m,m!==void 0&&S.appendLines([{prefix:" ",body:`\u2500\u2500 T${m} \u2500\u2500`,bodyStyle:"dim"}]))},J=null,X=null,D=0,$=0,W=!1,K,ee=null,he=null,ke=null,te=!1,pe=m=>{let w=$;$=Math.max(0,$+m);let I=typeof H<"u"&&H!==null;w===0&&$>0?(W=!1,ee=Date.now(),ke=Date.now(),ge?.setTurnRunning(!0),I&&H.setBanner({status:"busy",elapsedMs:0,stalled:!1}),he===null&&I&&(he=setInterval(()=>{if(ee===null||H===null)return;let E=ke===null?0:Date.now()-ke;H.setBanner({elapsedMs:Date.now()-ee,stalled:E>=mx}),Et()},1e3))):w>0&&$===0?(W=!1,ee=null,ke=null,ge?.setTurnRunning(!1),he!==null&&(clearInterval(he),he=null),I&&H.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):$>0&&W&&(W=!1,I&&H.setBanner({status:"busy",stalled:!1}))},H=null,ge=null,Xn,Lt=null,Bt=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]),ht=m=>{let{update:w}=m??{},I=gn(w,{cwd:ot});wx(w,I),ke=Date.now();let E=w?.sessionUpdate;if(typeof E=="string"&&!Bt.has(E)){let R=w??{};typeof R.messageId=="string"&&(Xn=R.messageId)}if(E==="prompt_received"?pe(1):I?.kind==="turn-complete"&&pe(-1),E==="permission_resolved"){es(w);return}C(I),it(w)};h.onNotification("session/update",m=>{if(!b){if(Lt!==null){Lt.push(m);return}ht(m)}}),h.onNotification("hydra-acp/session/closed",()=>{if(b)return;$>0&&pe(-$),typeof H<"u"&&H!==null&&H.setBanner({status:"cold",elapsedMs:void 0})});let Nt=new Map,Zn=200,Ss=0,on=!1,ki=4e3;h.onNotification("hydra-acp/prompt_queue/added",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let E=w.messageId,R=w.prompt,U=setTimeout(()=>{Nt.delete(E),Ye.set(E,Rt(E,R)),H&&ge&&ds()},Zn);Nt.set(E,U)}else Ye.set(w.messageId,Rt(w.messageId,w.prompt)),H&&ge&&ds();if(kn!==void 0&&w.originator?.clientId===kn){let E=Ze.shift();E&&(E.messageId=w.messageId,Jt.set(w.messageId,E))}}),h.onNotification("hydra-acp/prompt_queue/updated",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string"||!Ye.has(w.messageId))return;Ye.set(w.messageId,Rt(w.messageId,w.prompt));let I=Jt.get(w.messageId);if(I){let E=Array.isArray(w.prompt)?w.prompt:[],R="",U=[];for(let q of E){if(!q||typeof q!="object")continue;let B=q;B.type==="text"&&typeof B.text=="string"?R+=B.text:B.type==="image"&&typeof B.data=="string"&&typeof B.mimeType=="string"&&U.push({data:B.data,mimeType:B.mimeType,sizeBytes:Math.floor(B.data.length*3/4)})}I.text=R,I.attachments=U}H&&ge&&ds()}),h.onNotification("hydra-acp/prompt_queue/removed",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(K=w.messageId);let I=Nt.get(w.messageId);I!==void 0&&(clearTimeout(I),Nt.delete(w.messageId)),Ye.delete(w.messageId)&&H&&ge&&ds();let R=Jt.get(w.messageId);R&&(Jt.delete(w.messageId),w.reason==="started"&&(R.flushed=!0,C({kind:"user-text",text:R.displayText,attachments:R.attachments}),Kt=R))}),h.onNotification("hydra-acp/cancel_failed",m=>{if(b)return;let w=m??{};if(!(typeof H<"u"&&H!==null))return;Ss=Date.now(),on=!0;let E=typeof w.code=="number"?` (${w.code})`:"",R=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";H.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${E}${R} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",m=>{if(b)return;let w=m??{};if(typeof w.cancelledMessageId!="string")return;let I=w.cancelledMessageId;Ms.add(I),Kt!==null&&Kt.messageId!==void 0&&Kt.messageId===I&&(C({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Kt=null,Ms.delete(I))});let es=m=>{let w=m??{},I=typeof w.toolCallId=="string"?w.toolCallId:void 0,E;w.outcome&&typeof w.outcome=="object"?E=w.outcome:typeof w.chosenOptionId=="string"&&(E={kind:"selected",optionId:w.chosenOptionId}),ks(I,E?{outcome:E}:void 0)},ve=null,ks=(m,w)=>{if(!ve||ve.toolCallId&&m&&ve.toolCallId!==m)return;let I=ve.resolve;ve=null,S.setPermissionPrompt(null),I(w??{outcome:{outcome:"cancelled"}})},it=m=>{if(!ve?.toolCallId)return;let w=m??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===ve.toolCallId&&(!w.status||w.status==="pending"||ks(w.toolCallId,void 0))},an=()=>{if(!ve){S.setPermissionPrompt(null);return}S.setPermissionPrompt({title:ve.title,detail:ve.detail,options:ve.options.map(m=>({label:m.name})),selectedIndex:ve.selectedIndex})},xs=m=>{if(!ve)return;let{options:w,resolve:I}=ve;if(ve=null,S.setPermissionPrompt(null),m===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:m}})};h.onRequest("session/request_permission",async m=>{if(b)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ws(m);let w=m??{},E=(Array.isArray(w.options)?w.options:[]).map(Q=>({optionId:Q.optionId,name:Ce(Q.name??""),...Q.kind!==void 0?{kind:Q.kind}:{}})),R=w.toolCall?.title??w.toolCall?.name??"tool",U=Ce(R),q=Ce(Tm(Rm(m))),B=w.toolCall?.toolCallId;return E.length===0?(S.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${U} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Q=>{ve={title:U,detail:q,options:E,selectedIndex:0,resolve:Q,toolCallId:B},an()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let ts,Ar,Cr=!0,gt=!1;try{let m=await h.request("initialize",{protocolVersion:tt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ce}});Ar=m?.agentInfo?.name,m?.agentCapabilities?.promptCapabilities?.image===!1&&(Cr=!1),gt=kt(m?._meta??void 0).prompt?.amending===!0}catch{}let Pe=a.sessionId,Xe=a.agentId,ot=a.cwd,As,kn,ns,dn,Rr,xn,Ie,cn,Tr,yt;if(a.sessionId==="__new__"){let m={};s.agentId&&(m.agentId=s.agentId),s.name&&(m.title=s.name),s.model&&(m.model=s.model);let w=await h.request("session/new",{cwd:a.cwd,...Object.keys(m).length>0?{_meta:{[pt]:m}}:{}});Pe=w.sessionId,r.sessionId=Pe,r.readonly=!1;let I=kt(w._meta??void 0);I.clientId&&(kn=I.clientId),ts=I.upstreamSessionId,I.agentId&&(Xe=I.agentId),I.cwd&&(ot=I.cwd),I.title&&(As=I.title),ns=I.currentModel,dn=I.currentMode,Tr=I.currentUsage,yt=I.turnStartedAt,I.availableCommands&&(Rr=Mo(I.availableCommands)),I.availableModes&&(xn=I.availableModes),Ie=Dh(w.configOptions),cn=I.queue}else{let m={};s.readonly===!0&&(m.readonly=!0),e.tui.toolContent==="references"&&(m.toolContent="references"),s.drip===!0&&(m.replayMode="drip",s.dripSpeed!==void 0&&(m.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(m.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let w=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:ce},...Object.keys(m).length>0?{_meta:{[pt]:m}}:{}});Pe=w.sessionId,w.clientId&&(kn=w.clientId),r.sessionId=Pe,r.readonly=s.readonly===!0;let I=kt(w._meta??void 0);ts=I.upstreamSessionId,I.agentId&&(Xe=I.agentId),I.cwd&&(ot=I.cwd),I.title&&(As=I.title),ns=I.currentModel,dn=I.currentMode,Tr=I.currentUsage,yt=I.turnStartedAt,I.availableCommands&&(Rr=Mo(I.availableCommands)),I.availableModes&&(xn=I.availableModes),Ie=Dh(w.configOptions),cn=I.queue}let ss=P.tuiHistoryFile(Pe),Er=P.globalTuiHistoryFile(),He=await zr(ss).catch(()=>[]),Re=await zr(Er).catch(()=>[]);Re.length>e.tui.promptHistoryMaxEntries&&(Re=Re.slice(Re.length-e.tui.promptHistoryMaxEntries));let jt=[...He],oe=new vn({history:fo(Re,jt)});ge=oe;let xi=!1,_e=(m,w)=>{let I=m.replace(/\n+$/,"");if(I.length===0)return;let E=(w??m).replace(/\n+$/,""),R=Jr(He,I),U=R!==He;He=R,jt=Jr(jt,E);let q=Jr(Re,I,e.tui.promptHistoryMaxEntries),B=q!==Re;Re=q,oe.setHistory(fo(Re,jt)),U&&ms(ss,He).catch(()=>{}),B&&Qu(Er,I).catch(()=>{})};$>0&&oe.setTurnRunning(!0);let We=null,rs=null;mh(e.tui.ambiguousWidth==="wide"),Bp(e.tui.diffContextLines);let is=!1,S,Cs=()=>{is&&(is=!1,S.start())},Ai=()=>{is||(is=!0,S.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Cs),S=new ya({term:t,dispatcher:oe,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?Ai:void 0,onBlockClick:m=>{pg(m)},onBlockVisible:m=>{ug(m)},onMouse:m=>{if(m.kind!=="press"||m.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&Hh(w)||fn(w)},onKey:m=>{for(let w of m){if(ve&&Ti(w)||wt(w)||Se(w)||Ri(w)||ln(w)||Ts(w))continue;if(w.type==="attachment-paths"){dt(w.paths);continue}let I=oe.feed(w);for(let E of I)s.readonly===!0&&Hh(E)||fn(E)}os(),S.setBannerSearchIndicator(oe.state().historySearchQuery),S.setAttachments(oe.state().attachments),S.refreshPrompt()}}),H=S,S.setStickyBottomKey("plan");let An=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/demo-plan",description:"Inject synthetic plan events (UI test)"},{name:"/demo-tool",description:"Inject a synthetic tool-call sequence (UI test)"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt>"}],qt=Rr??[],Wt=xn??[],Pr=Ie??[],xa=()=>Pr.find(m=>m.id==="agent"),Ci=()=>{let m=new Set,w=[];for(let I of[...An,...qt])m.has(I.name)||(m.add(I.name),w.push(I));return w},Rs=()=>{let m=oe.state().buffer,w=m[0]??"";if(!w.startsWith("/"))return[];if(m.length>1)return[];let I=w.indexOf(" "),E=I===-1?w:w.slice(0,I);if(E.lastIndexOf("/")>0)return[];let R=Ci().filter(U=>U.name.startsWith(E));return R.length===1&&R[0]?.name===E&&I===-1?[]:R},zt=[],os=()=>{let m=Rs();if(m.length>0){zt=[],S.setCompletions(m);return}S.setCompletions(zt)},ln=m=>{if(m.type!=="key"||m.name!=="tab")return zt.length>0&&(zt=[]),!1;let w=Rs();if(S.isOverlayOpen()&&w.length===0)return S.toggleFocusedPane(),!0;if(w.length>0){zt=[];let I=oe.state().buffer[0]??"",E=Sh({matches:w.map(R=>R.name),firstLine:I});return E===null||oe.replaceFirstLine(E),!0}return Cn()},Cn=()=>{let m=oe.state(),w=m.buffer[m.row]??"",I=Mh(w,m.col);if(I===null)return!1;let E=$h(I.token,ot);return E===null?!1:(E.replacement!==I.token&&oe.replaceRangeOnCurrentLine(I.start,m.col,E.replacement),zt=E.candidates.length>1?E.candidates.map(R=>({name:R})):[],!0)},Ts=m=>!S.isOverlayOpen()||m.type!=="key"||m.name!=="escape"&&m.name!=="ctrl-c"?!1:(J&&(J.cancel(),J=null),X=null,S.closeBtwOverlay(),!0),Ri=m=>{if(!S.isScrollbackSearchActive())return m.type==="key"&&m.name==="ctrl-r"&&S.isScrolledBack()?(S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(""),!0):!1;if(m.type==="char"){let w=S.scrollbackSearchTerm()+m.ch;return S.updateScrollbackSearchTerm(w),!0}if(m.type==="paste"){let w=S.scrollbackSearchTerm()+m.text.replace(/\n/g," ");return S.updateScrollbackSearchTerm(w),!0}if(m.type==="key")switch(m.name){case"ctrl-r":return S.advanceScrollbackSearch(),!0;case"ctrl-s":return S.retreatScrollbackSearch(),!0;case"backspace":{let w=S.scrollbackSearchTerm();return w.length===0?S.cancelScrollbackSearch():S.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return S.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return S.cancelScrollbackSearch(),!0;default:return!0}return!0},Ti=m=>{if(!ve)return!1;let w=ve.options;if(m.type==="key")switch(m.name){case"up":return ve.selectedIndex=Math.max(0,ve.selectedIndex-1),an(),!0;case"down":return ve.selectedIndex=Math.min(w.length-1,ve.selectedIndex+1),an(),!0;case"enter":{let I=w[ve.selectedIndex];return I&&xs(I.optionId),!0}case"escape":case"ctrl-c":return xs(null),!0;default:return!0}if(m.type==="char"&&/^[1-9]$/.test(m.ch)){let I=parseInt(m.ch,10)-1,E=w[I];return E&&xs(E.optionId),!0}return!0},Aa=Xe||Ar||"?",At={...Tr??{}};c.finalize(),S.start({skipFullscreen:!0}),S.setHideThoughts(!i.showThoughts),S.setSessionbar({agent:Aa,cwd:ot,sessionId:Pe,title:As,model:ns,usage:{...At}}),dn&&S.setBanner({currentMode:dn}),fi().then(m=>{m&&S.notify(`\u2728 ${pi(m)}`,3e4)});let at=null,Ca=new Promise(m=>{at=m}),Mr=()=>{h.notify("session/cancel",{sessionId:Pe}).catch(()=>{})},Ei=()=>{H!==null&&$===1&&(W=!0,H.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Es=()=>{if(We){We.cancel(),Ei();return}if($>0){Mr(),Ei();return}$r()},$r=()=>{bt(0)},Rn=()=>{let m="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",m]]:[["Enter",m],["Ctrl+Enter / Shift+Enter / ^S",w]],...hx]},Tn=()=>{if(S.isHelpPromptActive()){S.setHelpPrompt(null);return}S.setHelpPrompt({title:"Hotkeys",entries:Rn(),hint:"any key dismisses \xB7 /help lists commands"})},wt=m=>S.isHelpPromptActive()?(m.type==="key"&&m.name==="ctrl-g",S.setHelpPrompt(null),!0):!1,un=["tools","plan","thoughts","diffs","mouse","enter"],Ct=0,_r=m=>{switch(m){case"tools":return i.toolsExpanded?"expanded":"collapsed";case"plan":return i.planExpanded?"expanded":"collapsed";case"thoughts":return i.showThoughts?"shown":"hidden";case"diffs":return i.showFileUpdates;case"mouse":return i.mouseEnabled?"on":"off";case"enter":return i.defaultEnterAction}},En=m=>{switch(m){case"tools":return"Tools";case"plan":return"Plan";case"thoughts":return"Thoughts";case"diffs":return"File updates";case"mouse":return"Mouse capture";case"enter":return"Enter key"}},k=()=>({title:"Session options",options:un.map(m=>({label:En(m),value:_r(m)})),selectedIndex:Ct}),M=()=>{S.isOptionsPromptActive()&&S.setOptionsPrompt(k())},_=()=>{if(S.isOptionsPromptActive()){S.setOptionsPrompt(null);return}Ct=0,S.setOptionsPrompt(k())},Y=m=>{switch(m){case"tools":i.toolsExpanded=!i.toolsExpanded,se.clear(),cg();break;case"plan":i.planExpanded=!i.planExpanded,Tt=null,zc();break;case"thoughts":i.showThoughts=!i.showThoughts,S.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Vt.clear(),fg();break;case"mouse":{let w=!S.isMouseEnabled();S.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}M()},me=m=>{(async()=>{try{switch(m){case"tools":case"plan":S.notify(`${En(m)} is session-only \u2014 not saved`);return;case"thoughts":await Br("showThoughts",i.showThoughts);break;case"diffs":await Br("showFileUpdates",i.showFileUpdates);break;case"mouse":await Br("mouse",i.mouseEnabled);break;case"enter":await Br("defaultEnterAction",i.defaultEnterAction);break}S.notify(`saved default: ${En(m)} ${_r(m)}`)}catch(w){S.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Se=m=>{if(!S.isOptionsPromptActive())return!1;if(m.type==="key")switch(m.name){case"up":return Ct=Math.max(0,Ct-1),M(),!0;case"down":return Ct=Math.min(un.length-1,Ct+1),M(),!0;case"enter":{let w=un[Ct];return w&&Y(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return S.setOptionsPrompt(null),!0;case"ctrl-d":return S.setOptionsPrompt(null),!1;default:return!0}if(m.type==="char"){if(/^[1-9]$/.test(m.ch)){let w=parseInt(m.ch,10)-1,I=un[w];return I&&(Ct=w,Y(I)),!0}if(m.ch==="s"||m.ch==="S"){let w=un[Ct];return w&&me(w),!0}}return!0},Me=()=>{b=!0,J&&(J.cancel(),J=null),process.off("SIGINT",Es),process.platform!=="win32"&&process.off("SIGCONT",Cs),he!==null&&(clearInterval(he),he=null),S.clearWindowTitle(),S.stop({keepFullscreen:!0}),ms(ss,He).catch(()=>{}),g.close().catch(()=>{})},bt=(m=0)=>{Me(),at&&(at(null),at=null),m!==0&&process.exit(m)},Pn=async()=>{if(!at)return;J&&(J.cancel(),J=null);let m=oe.state().buffer.join(`
213
- `);m.replace(/\s+$/,"").length>0&&_e(m),S.pauseRepaint(),S.stop({keepFullscreen:!0}),ms(ss,He).catch(()=>{});let w=null,I=null;for(;w===null;){let q=await yn(n,{includeNonInteractive:!0}),B=await Dc(t,{cwd:ot,sessions:q,config:e,target:n,currentSessionId:Pe,prefs:o});if(B.kind==="abort"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(B.kind==="exit"){bt(0);return}if(B.kind==="new"){w={choice:B,sessions:q};break}if(B.kind==="fork"){let Je=await zh(t,n,B,q);if(Je.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(Je.kind==="back")continue;w={choice:{kind:"attach",sessionId:Je.ctx.sessionId,...Je.ctx.agentId?{agentId:Je.ctx.agentId}:{}},sessions:q},I={readonly:!1,cwd:Je.ctx.cwd},Je.ctx.resumeHint!==void 0&&(I.resumeHint=Je.ctx.resumeHint);break}let Q=q.find(Je=>Je.sessionId===B.sessionId);if(!(Q!==void 0&&!!Q.importedFromMachine&&!Q.upstreamSessionId&&B.readonly!==!0)){if(n.isLocal&&Q&&!Q.importedFromMachine&&B.readonly!==!0&&!(await hi(Q.cwd)).ok){let ut=await Si(t,Q,{defaultCwd:Dt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(ut.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(ut.kind==="back")continue;w={choice:B,sessions:q},I={readonly:!1,cwd:ut.path,resumeHint:{agentId:B.agentId??Q.agentId??"",cwd:ut.path,upstreamSessionId:""}};break}w={choice:B,sessions:q};break}let Ae={...s,readonly:!1},Ue=await Wh(t,Q,B,Ae);if(Ue.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}Ue.kind!=="back"&&(w={choice:B,sessions:q},I={readonly:Ae.readonly===!0,cwd:Ue.ctx.cwd},Ue.ctx.resumeHint!==void 0&&(I.resumeHint=Ue.ctx.resumeHint))}let{choice:E}=w,R=at;if(at=null,process.off("SIGINT",Es),g.close().catch(()=>{}),E.kind==="new"){let{sessionId:q,...B}=s,Q={...B,cwd:ot,forceNew:!0,readonly:!1};E.prompt!==void 0&&(Q.initialPrompt=E.prompt),R(Q);return}if(E.kind!=="attach")return;let U={...s,sessionId:E.sessionId,cwd:I?.cwd??ot,readonly:I?.readonly??E.readonly===!0};E.agentId!==void 0&&(U.agentId=E.agentId),I?.resumeHint!==void 0?U.resumeHint=I.resumeHint:delete U.resumeHint,R(U)},as=async()=>{if(!at)return;let w=(await yn(n)).filter(q=>q.status==="live");if(w.length<=1)return;let I=w.findIndex(q=>q.sessionId===Pe),E=w[(I+1)%w.length],R=at;at=null,process.off("SIGINT",Es),g.close().catch(()=>{});let U={...s,sessionId:E.sessionId,cwd:ot,readonly:!1};E.agentId!==void 0&&(U.agentId=E.agentId),R(U)},fn=m=>{switch(m.type){case"send":i.defaultEnterAction==="amend"?ct(m.text,m.attachments,m.displayText):Or(m.text,m.attachments,m.displayText);return;case"amend":i.defaultEnterAction==="amend"?Or(m.text,m.attachments,m.displayText):ct(m.text,m.attachments,m.displayText);return;case"queue-edit":{let w=Pi(m.index);if(!w)return;let I=[];m.text.length>0&&I.push({type:"text",text:m.text});for(let E of m.attachments)I.push({type:"image",data:E.data,mimeType:E.mimeType});h.request("hydra-acp/prompt/update",{sessionId:Pe,messageId:w,prompt:I}).then(E=>{let R=E;!R.updated&&R.reason!=="ok"&&S.notify(`queue edit skipped (${R.reason})`)}).catch(E=>{S.notify(`queue edit failed: ${E.message}`)});return}case"queue-remove":{let w=Pi(m.index);if(!w)return;h.request("hydra-acp/prompt/cancel",{sessionId:Pe,messageId:w}).then(I=>{let E=I;!E.cancelled&&E.reason!=="ok"&&S.notify(`queue cancel skipped (${E.reason})`)}).catch(I=>{S.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(S.isOverlayOpen()){J&&(J.cancel(),J=null),X=null,S.closeBtwOverlay();return}if(m.prefill&&We){let w=Ye.size===0,I=oe.state().buffer.every(E=>E==="");w&&I&&(rs={text:We.text,attachments:We.attachments})}We?We.cancel():$>0&&Mr(),Ei();return}case"exit":$r();return;case"plan-toggle":Ra(m.on);return;case"redraw-banner":S.setBanner({});return;case"redraw":S.fullRedraw();return;case"scroll-to-top":S.scrollToTop();return;case"scroll-to-bottom":S.scrollToBottom();return;case"switch-session":Pn();return;case"next-live-session":as();return;case"toggle-options":_();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,S.setHideThoughts(!i.showThoughts),S.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!S.isMouseEnabled();S.setMouseEnabled(w),i.mouseEnabled=w,S.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Tn();return;case"escalate-search":S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(m.query);return;case"attachment-request":vt(m.source);return}},dt=async m=>{if(!Cr){S.notify("agent does not accept image attachments");return}let w=0;for(let I of m){if(I.startsWith("data:")){let R=gc(I);if(!R){S.notify("unsupported data: URI");continue}if(R.sizeBytes>rn){S.notify(`image too large (${Ft(R.sizeBytes)}, max ${Ft(rn)})`);continue}oe.addAttachment({mimeType:R.mimeType,data:R.data,name:"pasted image",sizeBytes:R.sizeBytes}),w++;continue}let E=gi(I);if(!E){S.notify(`unsupported image type: ${Uc.basename(I)}`);continue}try{let R=await px.readFile(I);if(R.length>rn){S.notify(`image too large (${Ft(R.length)}, max ${Ft(rn)})`);continue}oe.addAttachment({mimeType:E,data:R.toString("base64"),name:Uc.basename(I),sizeBytes:R.length}),w++}catch(R){S.notify(`cannot read ${Uc.basename(I)}: ${R.message}`)}}w>0&&(S.setAttachments(oe.state().attachments),S.refreshPrompt())},vt=async(m="clipboard")=>{let w=m==="primary"?await th():await eh();if(!w.ok){S.notify(w.reason);return}if(w.kind==="image"){if(!Cr){S.notify("agent does not accept image attachments");return}oe.addAttachment(w.attachment),S.setAttachments(oe.state().attachments),S.refreshPrompt();return}let I=oe.feed({type:"paste",text:w.text});for(let E of I)fn(E);S.refreshPrompt()},Ps=m=>m.attachmentCount>0?`${m.text} \xB7 \u{1F4CE}\xD7${m.attachmentCount}`:m.text,Rt=(m,w)=>{let I=Array.isArray(w)?w:[],E="",R=0;for(let U of I){if(!U||typeof U!="object")continue;let q=U;q.type==="text"&&typeof q.text=="string"?E+=q.text:q.type==="image"&&(R+=1)}return{messageId:m,text:Ce(E),attachmentCount:R}},Ye=new Map,Ze=[],Jt=new Map,Ms=new Set,Kt=null,ds=()=>{let m=[...Ye.values()],w=m.map(Ps);S.setQueuedPrompts(w),S.setBanner({queued:m.length}),oe.setQueue(m.map(I=>I.text))},Pi=m=>[...Ye.values()][m]?.messageId;if(cn&&cn.length>0){for(let m of cn){if(m.position===0){K=m.messageId;continue}Ye.set(m.messageId,Rt(m.messageId,m.prompt))}Ye.size>0&&ds()}let Or=(m,w,I)=>{S.scrollToBottom(),!Mi(m)&&(_e(m,I),Fr(m,w,I))},ct=(m,w,I)=>{if(S.scrollToBottom(),Mi(m))return;if(_e(m,I),!gt||K===void 0){Fr(m,w,I);return}let E=K,R=[];m.length>0&&R.push({type:"text",text:m});for(let B of w)R.push({type:"image",data:B.data,mimeType:B.mimeType});let U={text:m,displayText:I??m,attachments:w,flushed:!1};Ze.push(U);let q=()=>{let B=Ze.indexOf(U);B>=0&&Ze.splice(B,1),U.messageId!==void 0&&Jt.delete(U.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Pe,targetMessageId:E,prompt:R}).then(B=>{let Q=B;if(Q.amended&&Q.reason==="ok"){pe(1);return}if(q(),Q.reason==="target_completed"){S.notify("previous response finished \u2014 press Enter to send as a new turn"),oe.setBuffer(m,w),S.refreshPrompt();return}if(Q.reason==="target_cancelled"){S.notify("amend skipped \u2014 previous turn was cancelled"),oe.setBuffer(m,w),S.refreshPrompt();return}if(Q.reason==="target_not_found"){S.notify("amend skipped \u2014 no matching prompt"),oe.setBuffer(m,w),S.refreshPrompt();return}}).catch(B=>{q(),S.notify(`amend failed: ${B.message}`),oe.setBuffer(m,w),S.refreshPrompt()})},Ra=async m=>{if(Wt.length===0){S.notify("no modes advertised by agent");return}let w=S.currentModeId(),I=Wt.findIndex(U=>U.id===w),E=I===-1?0:(I+1)%Wt.length,R=Wt[E]?.id;if(R){S.setBanner({currentMode:R});try{await h.request("session/set_mode",{sessionId:Pe,modeId:R})}catch(U){S.notify(`set_mode failed: ${U.message}`)}}},Mi=m=>{let w=m.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
214
- `))return!1;let I=w.indexOf(" ");switch(I===-1?w:w.slice(0,I)){case"/quit":case"/exit":return $r(),!0;case"/clear":return lt.clear(),$n.clear(),T.length=0,Te=null,xe=null,ze=null,Mn.clear(),Vt.clear(),O.clear(),se.clear(),Z.clear(),be.clear(),S.clearScrollback(),!0;case"/demo-plan":{S.clearKey("plan");let R=["Step 1","Step 2","Step 3","Step 4","Step 5"],U=[["pending","pending","pending","pending","pending"],["in_progress","pending","pending","pending","pending"],["completed","in_progress","pending","pending","pending"],["completed","completed","in_progress","pending","pending"],["completed","completed","completed","in_progress","pending"],["completed","completed","completed","completed","in_progress"],["completed","completed","completed","completed","completed"]],q=0,B=()=>{let Q=U[q];Q&&(C({kind:"plan",entries:R.map((le,Ae)=>({content:le,status:Q[Ae]??"pending"}))}),q+=1,setTimeout(B,600))};return B(),!0}case"/demo-tool":{let R=`demo-${Date.now()}`;return C({kind:"tool-call",toolCallId:R,title:"Terminal",status:"pending"}),setTimeout(()=>{C({kind:"tool-call-update",toolCallId:R,title:"echo hello world",status:"in_progress"})},500),setTimeout(()=>{C({kind:"tool-call-update",toolCallId:R,status:"completed"})},1500),!0}case"/help":{let R=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let U of An)R.push({prefix:" ",body:` ${U.name.padEnd(12)} ${U.description??""}`,bodyStyle:"info"});if(qt.length>0){R.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let U of qt)R.push({prefix:" ",body:` ${U.name.padEnd(12)} ${U.description??""}`,bodyStyle:"info"})}return S.appendLines(R),!0}case"/agent":{let R=I===-1?"":w.slice(I+1).trim(),U=xa();if(!U)return S.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!R){let q=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let B of U.options){let Q=B.value===U.currentValue?"* ":" ";q.push({prefix:" ",body:`${Q}${B.value.padEnd(16)} ${B.name}`,bodyStyle:"info"})}return S.appendLines(q),!0}return U.options.some(q=>q.value===R)?R===U.currentValue?(S.notify(`already on agent ${R}`),!0):(S.notify(`switching to ${R}\u2026`),h.request("session/set_config_option",{sessionId:Pe,configId:"agent",value:R}).catch(q=>{S.notify(`set_config_option failed: ${q.message}`)}),!0):(S.notify(`unknown agent: ${R}`),!0)}case"/sessions":return S.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return Pn(),!0;case"/rename":{let R=I===-1?"":w.slice(I+1).trim(),U=R.length>0?`/hydra title ${R}`:"/hydra title";return _e(w,w),Fr(U,[],w),!0}case"/btw":{let R=I===-1?"":w.slice(I+1).trim();if(!R)return S.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(Pe==="__new__")return S.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;D+=1;let U=D;J&&(J.cancel(),J=null),X=null,S.openBtwOverlay(),S.setBtwOverlayStatus({label:"busy",style:"busy"});let q=new la;q.on("changed",()=>{S.setBtwOverlayContent(q.getLines())}),q.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:R}]});let B=Q=>{q.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})};return Wm(n,Pe,R).then(Q=>{if(U!==D){Q.cancel();return}J=Q,X=Q.sessionId,Q.on("event",le=>{U===D&&(le.kind==="update"?q.append(le.update):le.kind==="completed"?(S.setBtwOverlayStatus({label:"done",style:"done"}),J=null):le.kind==="cancelled"?(S.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),J=null):le.kind==="errored"&&(S.setBtwOverlayStatus({label:"errored",style:"errored"}),B(`btw errored: ${le.error.message}`),J=null))})}).catch(Q=>{if(U!==D)return;let le=Q instanceof Error?Q.message:String(Q);S.setBtwOverlayStatus({label:"errored",style:"errored"}),B(`btw startup failed: ${le}`),S.appendLines([{prefix:" ",body:`btw startup failed: ${le}`,bodyStyle:"tool-status-fail"}])}),!0}default:return!1}},Fr=async(m,w,I)=>{let E=[];m.length>0&&E.push({type:"text",text:m});for(let Ae of w)E.push({type:"image",data:Ae.data,mimeType:Ae.mimeType});pe(1);let R={text:m,displayText:I??m,attachments:w,flushed:!1};Ze.push(R),on=!1;let U=!1,q=null,B=Ae=>{typeof H<"u"&&H!==null&&H.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Ae,bodyStyle:"tool-status-fail"}])},Q=!1;We={text:m,attachments:w,cancel:()=>{if(on){on=!1,Q=!0,B("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Pe}).catch(Ue=>{B(`force-stop failed: ${Ue.message}`)});return}if(U)return;U=!0,h.notify("session/cancel",{sessionId:Pe}).catch(()=>{});let Ae=Date.now();q=setTimeout(()=>{We!==null&&(Ss>=Ae||(on=!0,B("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},ki)}};let le;try{let Ae=await h.request("session/prompt",{sessionId:Pe,prompt:E});Ae&&typeof Ae.stopReason=="string"&&(le=Ae.stopReason)}catch(Ae){let Ue=Ze.indexOf(R);Ue>=0&&Ze.splice(Ue,1),R.messageId!==void 0&&Jt.delete(R.messageId),Q?S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):S.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Ae.message,bodyStyle:"tool-status-fail"}])}finally{if(We=null,q!==null&&(clearTimeout(q),q=null),pe(-1),R.flushed&&Kt===R){let Ae=R.messageId!==void 0&&Ms.has(R.messageId);Ae&&R.messageId!==void 0&&Ms.delete(R.messageId);let Ue={kind:"turn-complete"};le!==void 0&&(Ue.stopReason=le),Ae&&(Ue.amended=!0),C(Ue),Kt=null}if(rs!==null){let{text:Ae,attachments:Ue}=rs;rs=null,oe.state().buffer.every(ut=>ut==="")&&(oe.setBuffer(Ae,Ue),S.refreshPrompt())}}},lt=new Map,Mn=new Map,Vt=new Map,$n=new Map,T=[],j=0,ie=`tools:${j}`,O=new Map,se=new Map,Z=new Map,be=new Map,Te=null,xe=null,ze=null,Ee=null,Tt=null,$i=e.tui.maxToolItems,ng=e.tui.maxPlanItems,Ta=()=>({maxPlanItems:Tt??i.planExpanded?1/0:ng}),zc=()=>{if(Ee===null)return;let m=nn(Ee,Ta());m.length>0&&S.upsertLines("plan",[{body:""},...m])},_i="",$s=null,Jc=0,sg=()=>{if($s===null)return;let m=S.width(),w=gr(_i,m>0?{maxWidth:m}:void 0);w.length!==0&&S.upsertLines($s,w)},rg=m=>{m.length!==0&&($s===null&&(S.ensureSeparator(),$s=`agent:${Jc}`,Jc+=1,_i=""),_i+=m,sg())},_n=()=>{$s=null,_i=""},_s="",cs=null,Kc=0,ig=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),og=()=>{if(cs===null||_s.length===0)return;let m=zd(_s);m.length!==0&&S.upsertLines(cs,m)},ag=m=>{let w=Z.get(m);if(w===void 0)return[];let I=zd(w.text);return w.workerTaskId&&I.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),I},dg=(m,w)=>{m.length!==0&&(cs===null&&(S.ensureSeparator("thought"),cs=`thought:${Kc}`,Kc+=1,_s=""),_s+=m,Z.set(cs,{text:_s,workerTaskId:w}),og())},On=()=>{cs=null,_s=""},Vc=m=>{let{order:w,states:I,startedAt:E,endedAt:R,stopReason:U}=m,q=w.length,B=$i>0,Q=!B||m.expanded?w:w.slice(Math.max(0,q-$i)),le=q-Q.length,Ae=R===null,Ue=R??Date.now(),Je=Ue-E,ut=!Ae&&U!==null&&U!=="end_turn"?U:null,sl=ut==="amended",rl=sl?`amended \xB7 ${sn(Je)}`:`stopped (${ut}) \xB7 ${sn(Je)}`,Bi;if(q===0)ut!==null?Bi=rl:Bi=Ae?`thinking \xB7 ${sn(Je)}`:`thought \xB7 ${sn(Je)}`;else{let Pa=q===1?"tool":"tools",Ni=ut!==null?rl:Ae?sn(Je):`took ${sn(Je)}`,dl=[`${q} ${Pa}`,Ni];Ae&&B&&le>0&&dl.push(`${le} hidden`),Bi=dl.join(" \xB7 ")}let il=q===0&&Ae,ol=sl?"tool-status-cancelled":"tool-status-fail",al=[{prefix:"\u2699 ",prefixStyle:il?"tool-status-running":ut!==null?ol:"tool",body:Bi,bodyStyle:il?"tool-status-running":ut!==null?ol:"dim"}];for(let Pa of Q){let Ni=I.get(Pa);Ni&&al.push(...li(Ni,Ue))}return al},Yc=m=>se.get(m)??i.toolsExpanded,Et=()=>{if(Te===null)return;let m=Vc({order:T,states:lt,startedAt:Te,endedAt:xe,stopReason:ze,expanded:Yc(ie)});S.upsertLines(ie,m)},Qc=m=>{let w=O.get(m);if(!w)return;let I=Vc({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Yc(m)});S.upsertLines(m,I)},cg=()=>{Te!==null&&!O.has(ie)&&Et();for(let m of O.keys())Qc(m)},Ea=()=>{Te!==null&&O.set(ie,{order:[...T],states:new Map(lt),startedAt:Te,endedAt:xe??Date.now(),stopReason:ze})},Gc=()=>{j+=1,ie=`tools:${j}`,Te=Date.now(),xe=null,ze=null,Et()},Xc=(m,w,I,E,R,U,q)=>{let B=!lt.has(m),Q=lt.get(m),le=Q??{initialTitle:w??"tool",latestTitle:w??"tool",status:I??"pending",startedAt:Date.now()};!Q&&q!==void 0&&(le.workerTaskId=q),Q&&w!==void 0&&(le.latestTitle=w),U!==void 0&&le.detail===void 0&&(le.detail=U),Q&&I!==void 0&&(le.status=I),Q||(le.status=I??"pending"),le.endedAt===void 0&&Hp(le.status)&&(le.endedAt=Date.now()),E!==void 0&&(le.errorText=E),R!==void 0&&(le.editDiff=R),lt.set(m,le),B&&(Te===null&&(j+=1,ie=`tools:${j}`,Te=Date.now(),xe=null,ze=null),T.push(m))},Zc=async m=>{try{let w=await h.request("hydra-acp/session/tool_content",{sessionId:Pe,hash:m});return typeof w?.content=="string"?w.content:null}catch{return null}},Oi=new Set,lg=(m,w)=>{Oi.has(m)||w.oldRef===void 0&&w.newRef===void 0||(Oi.add(m),(async()=>{let[I,E]=await Promise.all([w.oldRef?Zc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Zc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&I===null||w.newRef!==void 0&&E===null){Oi.delete(m);let le=Jd(w,"diff",{deferredStatus:"error"});le.length>0&&(S.upsertLines(`editdiff:${m}`,le),S.repaintNow());return}let U={...w.path!==void 0?{path:w.path}:{},oldText:I??"",newText:E??""};Mn.set(m,U);let q=lt.get(m);q?.editDiff&&(q.editDiff=U),Oi.delete(m);let B=Vt.get(m),Q=B===void 0?i.showFileUpdates:B?"diff":"edit";Q!=="none"&&(Fi(m,U,Q==="diff"?"diff":"edit"),S.repaintNow())})())},Fi=(m,w,I)=>{let E=`editdiff:${m}`,R=Jd(w,I);if(R.length===0){S.removeKey(E);return}S.upsertLines(E,R),I==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&S.notifyWhenVisible(E)},ug=m=>{if(!m.startsWith("editdiff:"))return;let w=m.slice(9),I=Mn.get(w);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&lg(w,I)},el=m=>{let w=`editdiff:${m}`,I=i.showFileUpdates,E=lt.get(m),R;if(I==="none"||!E?.editDiff||E.status!=="completed")R=null;else{let q=Vt.get(m);R=q!==void 0?q?"diff":"edit":I==="diff"?"diff":"edit"}if(R===null){S.removeKey(w);return}let U=E.editDiff;Mn.set(m,U),Fi(m,U,R)},fg=()=>{let m=i.showFileUpdates;for(let[w,I]of Mn){let E=`editdiff:${w}`,R=Vt.get(w),U=R===void 0?m:R?"diff":"edit";if(U==="none"){S.removeKey(E);continue}Fi(w,I,U==="diff"?"diff":"edit")}},pg=m=>{if(m.startsWith("editdiff:")){let w=m.slice(9),I=Mn.get(w);if(!I)return;let E=Vt.get(w)??i.showFileUpdates==="diff";Vt.set(w,!E),Fi(w,I,E?"edit":"diff"),S.repaintNow();return}if(m==="plan"){if(Ee===null)return;Tt=!(Tt??i.planExpanded),zc(),S.repaintNow();return}if(m.startsWith("tools:")){let w=se.get(m)??i.toolsExpanded;se.set(m,!w),m===ie&&Te!==null?Et():Qc(m),S.repaintNow();return}if(m.startsWith("thought:")){if(!Z.has(m))return;let w=be.get(m);if(w!==void 0){be.delete(m),S.setRunCollapsed(w,!1,ag(m)),S.repaintNow();return}let I=S.contiguousRun(m,new Set(Z.keys()));if(I.length===0)return;let E=I[0];be.set(E,I),S.setRunCollapsed(I,!0,[ig()]),S.repaintNow();return}};v=m=>{if(m.kind==="available-commands"){qt=m.commands,os();return}if(m.kind==="available-modes"){Wt=m.modes;return}if(m.kind==="config-options"){Pr=m.options;let I=m.options.find(R=>R.id==="agent");I&&I.currentValue&&I.currentValue!==Xe&&(Xe=I.currentValue,S.setSessionbar({agent:I.currentValue}));let E=m.options.find(R=>R.id==="mode");E&&(Wt=E.options.map(R=>({id:R.value,name:R.name??R.value,...R.description!==void 0?{description:R.description}:{}})));return}if(m.kind==="mode-changed"){S.setBanner({currentMode:m.mode||void 0});return}if(m.kind==="session-info"){m.title!==void 0&&S.setSessionbar({title:m.title}),m.agentId!==void 0&&m.agentId!==Xe&&(Xe=m.agentId,S.setSessionbar({agent:m.agentId}));return}if(m.kind==="usage-update"){let I=!1;m.used!==void 0&&At.used!==m.used&&(At.used=m.used,I=!0),m.size!==void 0&&At.size!==m.size&&(At.size=m.size,I=!0),m.costAmount!==void 0&&At.costAmount!==m.costAmount&&(At.costAmount=m.costAmount,I=!0),m.costCurrency!==void 0&&At.costCurrency!==m.costCurrency&&(At.costCurrency=m.costCurrency,I=!0),I&&S.setSessionbar({usage:{...At}});return}if(m.kind==="user-text"){xi&&_e(m.text),_n(),On(),Te!==null&&(xe=Date.now(),Et()),Kt=null,S.ensureSeparator();let I=nn(m);I.length>0&&S.appendLines(I),Ea(),S.clearKey("plan"),Ee=null,Tt=null,lt.clear(),$n.clear(),T.length=0,xe=null,Gc(),S.redraw();return}if(m.kind==="agent-text"){On(),$s===null&&z(m.workerTaskId),rg(m.text);return}if(m.kind==="agent-thought"){_n(),cs===null&&z(m.workerTaskId),dg(m.text,m.workerTaskId);return}if(m.kind==="exit-plan-mode"){_n(),On();let I=$n.get(m.toolCallId),E={plan:m.plan??I?.plan??"",status:m.status??I?.status};if($n.set(m.toolCallId,E),E.plan.length===0)return;let R=Up(E);R.length>0&&S.upsertLines(m.toolCallId,R);return}if(m.kind==="tool-call"){_n(),On(),lt.has(m.toolCallId)||z(m.workerTaskId),Xc(m.toolCallId,m.title,m.status,void 0,m.editDiff,m.detail,m.workerTaskId),Et(),el(m.toolCallId);return}if(m.kind==="plan"){_n(),On(),Ee=m;let I=nn(m,Ta());I.length>0&&S.upsertLines("plan",[{body:""},...I]);let E=m.entries.length>0&&m.entries.every(R=>(R.status??"pending")==="completed");S.setStickyBottomKey(E?null:"plan");return}if(m.kind==="tool-call-update"){_n(),On(),Xc(m.toolCallId,m.title,m.status,m.errorText,m.editDiff,m.detail,m.workerTaskId),m.upstreamInterrupted&&(te=!0),Et(),el(m.toolCallId);return}m.kind==="model-changed"&&S.setSessionbar({model:m.model});let w=nn(m);if(w.length>0&&S.appendLines(w),m.kind==="turn-complete"){K=void 0,_n(),On();let I=m.amended?"amended":m.stopReason;if(!m.amended&&te&&(I===void 0||I==="end_turn")&&(I="error"),Ee!==null&&I!==void 0&&I!=="end_turn"){let E=nn({...Ee,stopped:!0,amended:m.amended===!0},Ta());E.length>0&&S.upsertLines("plan",[{body:""},...E])}Ee=null,Tt=null,S.clearKey("plan"),S.setStickyBottomKey("plan"),Te!==null?(xe=Date.now(),ze=I??null,Et(),Ea()):I!==void 0&&I!=="end_turn"&&I!=="amended"&&S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${I}`,bodyStyle:"tool-status-fail"}]),lt.clear(),$n.clear(),T.length=0,Te=null,xe=null,ze=null,te=!1,S.ensureSeparator(),Fh({pendingTurns:$,queueSize:Ye.size,ownTurnInFlight:We!==null,hasInFlightHead:K!==void 0,replayDraining:x,amended:m.amended===!0})&&pe(-$)}};let tl=y;y=[];let Li=[];for(let m of tl)m.kind==="user-text"&&typeof m.text=="string"&&Li.push(m.text);S.pauseRepaint(),x=!0;try{for(let m of tl)v(m)}finally{x=!1,S.resumeRepaint()}if(Li.length>0){let m=kd(He,Li);m!==He&&(He=m,jt=kd(jt,Li),oe.setHistory(fo(Re,jt)),ms(ss,He).catch(()=>{}))}xi=!0,yt!==void 0&&$>0?(ee=yt,S.setBanner({status:"busy",elapsedMs:Date.now()-yt}),he===null&&(he=setInterval(()=>{ee===null||H===null||(H.setBanner({elapsedMs:Date.now()-ee}),Et())},1e3)),Te===null&&Gc(),Te=yt,Et()):yt===void 0&&$>0&&pe(-$);let mg=()=>{if(ve){let m=ve.resolve;ve=null,S.setPermissionPrompt(null),m({outcome:{outcome:"cancelled"}})}_n(),On()},nl=()=>{Te!==null&&(xe=Date.now(),ze="reconnect-recovery-failed",Et(),Ea(),lt.clear(),$n.clear(),T.length=0,Te=null,xe=null,ze=null)};return p=()=>{S.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{mg();let m={jsonrpc:"2.0",id:`tui-reinit-${Nh()}`,method:"initialize",params:{protocolVersion:tt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ce}}};try{await g.request(m)}catch{}let w=Xn!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Nh()}`,method:"session/attach",params:{sessionId:Pe,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Xn}:{},clientInfo:{name:"hydra-acp-tui",version:ce},...(()=>{let B={};return ts!==void 0&&(B.resume={upstreamSessionId:ts,agentId:Xe,cwd:ot}),e.tui.toolContent==="references"&&(B.toolContent="references"),Object.keys(B).length>0?{_meta:{[pt]:B}}:{}})()}};Lt=[];let E,R,U;try{let B=await g.request(I);if(B.error)throw new Error(B.error.message);U=Oh(B.result),E=U.appliedPolicy,U.clientId!==void 0&&(kn=U.clientId)}catch(B){R=B}let q=Lt??[];if(Lt=null,R)nl(),S.appendLines([{prefix:" ",body:`reattach failed: ${R.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&E!=="after_message")nl(),S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{x=!0;try{for(let B of q)ht(B)}finally{x=!1}}if(U){let B=Lh({daemonTurnStartedAt:U.turnStartedAt,pendingTurns:$});B.pendingTurnsDelta!==0&&pe(B.pendingTurnsDelta),B.banner==="busy"&&B.busySince!==void 0?(ee=B.busySince,S.setBanner({status:"busy",elapsedMs:Date.now()-B.busySince}),he===null&&(he=setInterval(()=>{ee===null||H===null||(H.setBanner({elapsedMs:Date.now()-ee}),Et())},1e3))):S.setBanner({status:"ready",elapsedMs:void 0})}else S.setBanner({status:$>0?"busy":"ready",elapsedMs:$>0?0:void 0})},h.onClose(m=>{m&&t.red(`
206
+ `)})};re(),Me({onKey:J=>{if(J==="ESCAPE"||J==="CTRL_C"){vt();return}},onResize:()=>re()}),(async()=>{try{let J=await fetch(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(C.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`}});if(!J.ok)throw new Error(`daemon returned HTTP ${J.status}`);let le=await J.json(),Je=qt(le),Pe=tc(Je,C.status);U=sa(Pe,!1).replace(/\n$/,"").split(`
207
+ `)}catch(J){ae=`failed to load info: ${J.message}`}finally{F=!1,re()}})()},hn=()=>{if(o.length===0){se="no sessions to search",ve();return}Q=new kn({history:[],collapsePastes:!1}),W=[],z=!1,$=0,D=0,_e=0,j=null,Z=!1,_="input",M=!0,S(),pn(),Me({onKey:(U,ae,F)=>{if(_==="input"){if(Z)return;if(U==="ESCAPE"||U==="CTRL_C"){ct();return}if(U==="ENTER"||U==="KP_ENTER"){if($i().trim().length===0)return;Ct();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&W.length>0){_="results",$=0,D=0,$e(()=>{Jt(),En(0,!0),Os(),t.hideCursor()});return}let re=Q.state(),J=null;if(F?.isCharacter)J={type:"char",ch:U};else{let Ye=Sa(U);Ye!==null&&(J={type:"key",name:Ye})}if(J===null){t.moveTo(Tn(),zt());return}Q.feed(J);let le=Q.state();if(re.buffer.length===le.buffer.length&&re.buffer.every((Ye,Be)=>Ye===le.buffer[Be])&&re.row===le.row&&re.col===le.col){t.moveTo(Tn(),zt());return}let Pe=ot;S(),ot!==Pe?pn():Fr();return}if(_==="results"){if(U==="ESCAPE"||U==="CTRL_C"){ct();return}if(U==="CTRL_F"){_="input",Mi(),Os(),Jt();return}if(U==="ENTER"||U==="KP_ENTER"){let J=W[$];if(!J)return;let le=o.find(Pe=>Pe.sessionId===J.sessionId);if(!!le?.importedFromMachine&&!le.upstreamSessionId){Ze();let Pe={kind:"attach",sessionId:J.sessionId};le.agentId!==void 0&&(Pe.agentId=le.agentId),k(Pe);return}(async()=>{let Pe=await Ih(t,{sessionId:J.sessionId,title:J.title,cwd:J.cwd},_n);if(Pe==="cancel"){Ze(),k({kind:"abort"});return}if(Pe==="back")return;Ze();let Ye={kind:"attach",sessionId:J.sessionId,readonly:Pe==="view"};le?.agentId!==void 0&&(Ye.agentId=le.agentId),k(Ye)})();return}if(F?.isCharacter&&(U==="n"||U==="N")){let J=W[$];if(!J||J.snippets.length<=1)return;D=(D+1)%J.snippets.length,En($,!0);return}if(F?.isCharacter&&(U==="p"||U==="P")){let J=W[$];if(!J||J.snippets.length<=1)return;D=(D-1+J.snippets.length)%J.snippets.length,En($,!0);return}let re=J=>{if(J<0&&$===0){_="input",$e(()=>{En(0,!1),Os(),Jt()});return}let le=Math.min(W.length-1,Math.max(0,$+J));if(le===$)return;let Je=$,Pe=_e;$=le,D=0,as(),_e!==Pe?Mi():($e(()=>{En(Je,!1),En($,!0)}),Os())};switch(U){case"UP":case"SHIFT_TAB":case"CTRL_P":re(-1);return;case"DOWN":case"TAB":case"CTRL_N":re(1);return;case"PAGE_UP":re(-ze());return;case"PAGE_DOWN":re(ze());return;case"HOME":re(-$);return;case"END":re(W.length);return}return}},onResize:()=>pn()})},Fn=(C,U,ae)=>{if(b!=="busy"){if(C==="CTRL_P"){ls();return}if(b==="rename"){if(C==="ENTER"||C==="KP_ENTER"){let F=ie.trim();if(F.length===0){b="normal",x=null,ie="",ve();return}Qt(F);return}if(C==="ESCAPE"||C==="CTRL_C"){b="normal",x=null,ie="",ve();return}if(C==="BACKSPACE"){ie.length>0&&(ie=ie.slice(0,-1),ve());return}if(C==="CTRL_U"){ie="",ve();return}if(C==="CTRL_W"){let F=ie.replace(/\s+$/,""),re=F.lastIndexOf(" ");ie=re>=0?F.slice(0,re):"",ve();return}if(ae?.isCharacter){ie+=C,ve();return}return}if(b==="confirm-kill"||b==="confirm-delete"){if(ae?.isCharacter&&(C==="y"||C==="Y")){Fi(b==="confirm-kill"?"kill":"delete");return}if(C==="ESCAPE"||C==="CTRL_C"||C==="ENTER"||C==="KP_ENTER"||ae?.isCharacter&&(C==="n"||C==="N")){b="normal",x=null,ve();return}return}if(Hr(),C==="CTRL_F"){hn();return}if(u===0&&!p){if(C==="ESCAPE"){ut();return}if(C==="ENTER"||C==="KP_ENTER"){Ze();let Be=K.expandedText(),Ht={kind:"new"};Be.trim().length>0&&(Ht.prompt=Be),s!==e.cwd&&(Ht.cwd=s),k(Ht);return}if(C==="UP"&&y){let Be=Date.now(),Ht=Be-I;if(I=Be,Ht<h){Ue();return}y=!1}if(C==="DOWN"){let Be=K.state(),Ht=Be.historyIndex!==-1||Be.queueIndex!==-1,Ur=Lt.length===0||ns===Lt.length-1;if(!Ht&&Ur&&o.length>0){It(1);return}}if(C==="PAGE_DOWN"&&(Lt.length===0||ns===Lt.length-1)&&o.length>0){It(1);return}y=!1;let F=K.state(),re=null;if(ae?.isCharacter)re={type:"char",ch:C};else{let Be=Sa(C);Be!==null&&(re={type:"key",name:Be})}if(re===null){Ue();return}let J=K.feed(re),le=K.state(),Je=F.buffer.length===le.buffer.length&&F.buffer.every((Be,Ht)=>Be===le.buffer[Ht])&&F.row===le.row&&F.col===le.col;if(J.some(Be=>Be.type==="exit")){ut();return}if(Je){Ue();return}let Pe=An(le.buffer,Ft);if(es(Pe,le,Aa).rendered!==yt){ke();return}Lr();return}if(!p&&ae?.isCharacter&&C==="?"){ft();return}if(p){if(ae?.isCharacter){g+=C,at(),ke();return}if(C==="BACKSPACE"){g.length>0?(g=g.slice(0,-1),at(),ke()):(p=!1,at(),ke());return}if(C==="ESCAPE"||C==="CTRL_C"){p=!1,g="",at(),ke();return}}if(ae?.isCharacter){if(C==="/"){p=!0,g="",at(),ke();return}if(C==="n"||C==="N"){It(1);return}if(C==="p"||C==="P"){It(-1);return}if(C==="c"||C==="C"){Ze(),k(Ls());return}if(C==="q"||C==="Q"){ut();return}if(C==="o"||C==="O"){let F=u>0?o[u-1]?.sessionId:void 0;n.filters.cwdOnly=!n.filters.cwdOnly,at(),Te(F),ke();return}if(C==="h"||C==="H"){let F=u>0?o[u-1]?.sessionId:void 0;n.filters.hostFilter=Xk(n.filters.hostFilter,r),at(),Te(F),ke();return}if(C==="i"&&u>0){let F=o[u-1];if(!F)return;On(F);return}if(C==="I"){let F=u>0?o[u-1]?.sessionId:void 0;n.filters.includeNonInteractive=!n.filters.includeNonInteractive,at(),Te(F),ke();return}if(C==="r"||C==="R"){let F=u>0?o[u-1]?.sessionId:void 0;Yt(F);return}if(C==="s"||C==="S"){Dr();return}if((C==="v"||C==="V")&&u>0){let F=o[u-1];if(!F)return;Ze();let re={kind:"attach",sessionId:F.sessionId,readonly:!0};F.agentId!==void 0&&(re.agentId=F.agentId),k(re);return}if((C==="f"||C==="F")&&u>0){let F=o[u-1];if(!F)return;Ze();let re={kind:"fork",sourceSessionId:F.sessionId,sourceCwd:F.cwd};F.agentId!==void 0&&(re.sourceAgentId=F.agentId),F.importedFromMachine!==void 0&&(re.sourceImportedFromMachine=F.importedFromMachine),F.upstreamSessionId!==void 0&&(re.sourceUpstreamSessionId=F.upstreamSessionId),k(re);return}if((C==="k"||C==="K")&&u>0){let F=o[u-1];if(!F)return;x={sessionId:F.sessionId,cwd:F.cwd,status:F.status},b="confirm-kill",ve();return}if(C==="t"&&u>0){let F=o[u-1];if(!F)return;x={sessionId:F.sessionId,cwd:F.cwd,status:F.status},ie=F.title??"",b="rename",ve();return}if(C==="T"&&u>0){let F=o[u-1];if(!F||F.status!=="live")return;fs({sessionId:F.sessionId});return}if(C==="*"&&u>0){let F=o[u-1];if(!F)return;Oi(F);return}if((C==="d"||C==="D")&&u>0){let F=o[u-1];if(!F)return;x={sessionId:F.sessionId,cwd:F.cwd,status:F.status},b="confirm-delete",ve();return}return}switch(C){case"UP":case"SHIFT_TAB":C==="UP"&&(u===1&&(y=!0),I=Date.now()),It(-1);return;case"DOWN":case"TAB":case"CTRL_N":It(1);return;case"PAGE_UP":It(-Re);return;case"PAGE_DOWN":It(Re);return;case"HOME":It(1-u);return;case"END":It(l);return;case"ENTER":case"KP_ENTER":{if(Ze(),u===0){k(Ls());return}let F=o[u-1];if(!F){k({kind:"abort"});return}let re={kind:"attach",sessionId:F.sessionId};F.agentId!==void 0&&(re.agentId=F.agentId),k(re);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":ut();return}}};Me({onKey:(C,U,ae)=>Fn(C,U,ae),onResize:()=>{P||ke()}});let Dt=()=>{t.grabInput({});let C=t;C.stdin&&typeof C.onStdin=="function"&&(bt=C.onStdin,C.stdin.removeListener("data",C.onStdin),C.stdin.on("data",$n),process.stdout.write("\x1B[?2004h")),t.on("key",us),t.on("resize",lt)},Ln=()=>{process.stdout.write("\x1B[?2004l");let C=t;C.stdin&&bt&&(C.stdin.removeListener("data",$n),C.stdin.on("data",bt),bt=null),Pn=!1,Mn="",t.off("key",us),t.off("resize",lt),t.grabInput(!1),t.hideCursor(!1)};if(Dt(),process.platform!=="win32"){let C=!1,U=()=>{C&&(C=!1,process.stdout.write("\x1B[?1049h"),Dt(),P||ke())};mn=()=>{C||P||(C=!0,Ln(),process.stdout.write(`\x1B[?1049l\x1B[?7h\x1B[?25h
208
+ `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}O=setInterval(Vt,3e3)})}function Uc(t){let e=t.height;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:24}function Cs(t){let e=t.width;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:80}function Qk(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+fi(Ne(t),s)}function Ca(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="live",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function Gk(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Xk(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function Zk(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[qe(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ne(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Hc,Aa,Kk,Ah,Vk,Yk,Ch=V(()=>{"use strict";Zo();me();nn();ui();go();wc();_c();Bc();Dc();xc();bs();nc();Hc=2,Aa=4,Kk=4,Ah=4,Vk=20,Yk=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],null,["\u2191 / \u2193, n / p, ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^p","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected live session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent (live session)"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});function sx(t){let e=t.findIndex(n=>n.id===ex);return e===-1?0:e}async function Th(t,e){Er();let n=sx(e),s=0,r=()=>{let a=Fc(t)-8;return Math.max(1,Math.min(tx,e.length,a))},i=()=>{let a=r();n<s?s=n:n>=s+a&&(s=n-a+1);let d=Math.max(0,e.length-a);s>d&&(s=d),s<0&&(s=0)},o=()=>{i();let a=r(),d=a+4,c=Math.min(nx,Math.max(40,Oc(t)-8)),l=xs(t,{contentHeight:d,contentWidth:c,title:"Select agent"}),u=l.contentW,f=0;t.moveTo(l.contentX,l.contentY+f),t.noFormat(" Which agent should this session use?"),f+=2;let p=Math.min(e.length,s+a);for(let h=s;h<p;h++){let y=e[h];if(!y)continue;let I=h===n?"\u276F":" ",b=y.description??y.name,x=` ${I} ${y.id}`;if(t.moveTo(l.contentX,l.contentY+f),h===n){let M=`${x} ${b}`;t.brightWhite.bgBlue.noFormat(rx(Rh(M,u),u))}else{t.noFormat(x);let M=u-x.length-2;M>1&&t.dim.noFormat(` ${Rh(b,M)}`)}f++}f++,t.moveTo(l.contentX,l.contentY+f);let g=e.length>a?` (${n+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${g}`),l};return o(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",g),t.off("resize",u),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=h=>{c(),a(h)},u=()=>{d||o()},f=()=>{n<e.length-1&&(n++,o())},p=()=>{n>0&&(n--,o())},g=(h,y,I)=>{if(h==="CTRL_C"||h==="CTRL_D"){l({kind:"cancel"});return}if(h==="ESCAPE"){l({kind:"back"});return}if(h==="ENTER"||h==="KP_ENTER"){let b=e[n];b&&l({kind:"select",agentId:b.id,persist:!1});return}if(h==="UP"||h==="SHIFT_TAB"){p();return}if(h==="DOWN"||h==="TAB"){f();return}if(I?.isCharacter){let b=h.toLowerCase();if(b==="s"){let x=e[n];x&&l({kind:"select",agentId:x.id,persist:!0});return}if(b==="j"){f();return}if(b==="k"){p();return}}};t.grabInput({}),t.on("key",g),t.on("resize",u)})}function Rh(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function rx(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var ex,tx,nx,Eh=V(()=>{"use strict";ka();ex="opencode",tx=20,nx=88});import*as Mh from"fs";import*as $h from"os";import*as Ra from"path";function _h(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function ix(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function ox(t){return t.replace(/\\ /g," ")}function Ph(t){return t.replace(/ /g,"\\ ")}function ax(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function dx(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=$h.homedir()+n.slice(1)),Ra.isAbsolute(n)?n:Ra.resolve(e,n)}function cx(t){let e;try{e=Mh.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Oh(t,e,n=cx){if(!ix(t))return null;let s=ox(t),{dirPrefix:r,base:i}=ax(s),o=dx(r,e),a=n(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(f=>f.name.startsWith(i)&&(d||!f.name.startsWith(".")));if(c.length===0)return null;let l=c.map(f=>f.isDir?f.name+"/":f.name);if(c.length===1){let f=c[0],p=f.isDir?f.name+"/":f.name;return{replacement:Ph(r+p),candidates:l}}let u=Ci(c.map(f=>f.name));return{replacement:Ph(r+u),candidates:l}}var Fh=V(()=>{"use strict";xa()});function Lh(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Bh(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Nh(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var Dh=V(()=>{"use strict"});import{appendFileSync as lx,statSync as ux,renameSync as fx}from"fs";import{nanoid as Hh}from"nanoid";import px from"terminal-kit";import mx from"fs/promises";import Wc from"path";function Uh(t){if(!Array.isArray(t))return;let e=bn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function jh(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}async function zh(t){let e=await G(),n=t.target??await Xt(e);Vh=e.tui.logMaxBytes,n.isLocal&&!t.target&&await ur(e);let s=px.terminal;bh(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:bl(e),defaultEnterAction:e.tui.defaultEnterAction},o=jc(),a=!1,d=()=>{a||(s.fullscreen(!0),a=!0)},c=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
209
+ `))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await yx(s,e,n,u,r,i,o)}finally{c(),process.off("exit",l)}let f=await yi();if(f&&process.stderr.write(`\u2728 ${wi(f)}
210
+ `),process.stdout.isTTY){let p=await fr(e);if(p?.version!==void 0){let g=p.version!==pe,h=ar(e),y=p.configDigest!==void 0&&p.configDigest!==h;if(g||y){let I=g?`daemon ${p.version} \u2260 cli ${pe}`:"config changed since daemon started",b=x=>`\x1B[33m${x}\x1B[0m`;process.stderr.write(b(`! ${I} \u2014 run \`${Dn()} daemon restart\` to apply.`)+`
211
+ `)}}}if(r.sessionId&&process.stdout.isTTY){let p=qe(r.sessionId),g=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Dn()} --session ${p}${g}
212
+ `)}}async function yx(t,e,n,s,r,i,o){let a=await wx(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let d=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",c=Ix(t,d);c.write(d);let l=n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,g=new Ar({url:l,subprotocols:u,onConnect:async m=>{m||f&&await f()},onDisconnect:m=>{p&&p(m)},log:()=>{}}),h=new Pt(g);await g.start(),h.onNotification(no,m=>{let w=hu.safeParse(m);w.success&&c.applyProgress(w.data)});let y=[],I=null,b=!1,x=!1,M=m=>{m&&(I?I(m):y.push(m))},_,Q=m=>{m!==_&&(_=m,m!==void 0&&S.appendLines([{prefix:" ",body:`\u2500\u2500 T${m} \u2500\u2500`,bodyStyle:"dim"}]))},W=null,z=null,$=!1,D=0,j=0,Z=!1,ie,se=null,Ee=null,K=null,Ce=!1,X=m=>{let w=j;j=Math.max(0,j+m);let v=typeof ee<"u"&&ee!==null;w===0&&j>0?(Z=!1,se=Date.now(),K=Date.now(),Re?.setTurnRunning(!0),v&&ee.setBanner({status:"busy",elapsedMs:0,stalled:!1}),Ee===null&&v&&(Ee=setInterval(()=>{if(se===null||ee===null)return;let T=K===null?0:Date.now()-K;ee.setBanner({elapsedMs:Date.now()-se,stalled:T>=hx}),Tt()},1e3))):w>0&&j===0?(Z=!1,se=null,K=null,Re?.setTurnRunning(!1),Ee!==null&&(clearInterval(Ee),Ee=null),v&&ee.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):j>0&&Z&&(Z=!1,v&&ee.setBanner({status:"busy",stalled:!1}))},ee=null,Re=null,Rs,Ft=null,Lt=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]),yt=m=>{let{update:w}=m??{},v=bn(w,{cwd:dt});bx(w,v),K=Date.now();let T=w?.sessionUpdate;if(typeof T=="string"&&!Lt.has(T)){let R=w??{};typeof R.messageId=="string"&&(Rs=R.messageId)}if(T==="prompt_received"?X(1):v?.kind==="turn-complete"&&(X(-1),$=!0),T==="permission_resolved"){ss(w);return}M(v),ot(w)};h.onNotification("session/update",m=>{if(!b){if(Ft!==null){Ft.push(m);return}yt(m)}}),h.onNotification("hydra-acp/session/closed",()=>{if(b)return;j>0&&X(-j),typeof ee<"u"&&ee!==null&&ee.setBanner({status:"cold",elapsedMs:void 0})});let Bt=new Map,ns=200,Ts=0,cn=!1,Ri=4e3;h.onNotification("hydra-acp/prompt_queue/added",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let T=w.messageId,R=w.prompt,H=setTimeout(()=>{Bt.delete(T),et.set(T,Vt(T,R)),ee&&Re&&fs()},ns);Bt.set(T,H)}else et.set(w.messageId,Vt(w.messageId,w.prompt)),ee&&Re&&fs();if(Cn!==void 0&&w.originator?.clientId===Cn){let T=ut.shift();T&&(T.messageId=w.messageId,Nt.set(w.messageId,T))}}),h.onNotification("hydra-acp/prompt_queue/updated",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string"||!et.has(w.messageId))return;et.set(w.messageId,Vt(w.messageId,w.prompt));let v=Nt.get(w.messageId);if(v){let T=Array.isArray(w.prompt)?w.prompt:[],R="",H=[];for(let q of T){if(!q||typeof q!="object")continue;let L=q;L.type==="text"&&typeof L.text=="string"?R+=L.text:L.type==="image"&&typeof L.data=="string"&&typeof L.mimeType=="string"&&H.push({data:L.data,mimeType:L.mimeType,sizeBytes:Math.floor(L.data.length*3/4)})}v.text=R,v.attachments=H}ee&&Re&&fs()}),h.onNotification("hydra-acp/prompt_queue/removed",m=>{if(b)return;let w=m??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(ie=w.messageId);let v=Bt.get(w.messageId);v!==void 0&&(clearTimeout(v),Bt.delete(w.messageId)),et.delete(w.messageId)&&ee&&Re&&fs();let R=Nt.get(w.messageId);R&&(Nt.delete(w.messageId),w.reason==="started"&&(R.flushed=!0,M({kind:"user-text",text:R.displayText,attachments:R.attachments}),Qt=R))}),h.onNotification("hydra-acp/cancel_failed",m=>{if(b)return;let w=m??{};if(!(typeof ee<"u"&&ee!==null))return;Ts=Date.now(),cn=!0;let T=typeof w.code=="number"?` (${w.code})`:"",R=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";ee.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${T}${R} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",m=>{if(b)return;let w=m??{};if(typeof w.cancelledMessageId!="string")return;let v=w.cancelledMessageId;Yt.add(v),Qt!==null&&Qt.messageId!==void 0&&Qt.messageId===v&&(M({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Qt=null,Yt.delete(v))});let ss=m=>{let w=m??{},v=typeof w.toolCallId=="string"?w.toolCallId:void 0,T;w.outcome&&typeof w.outcome=="object"?T=w.outcome:typeof w.chosenOptionId=="string"&&(T={kind:"selected",optionId:w.chosenOptionId}),Es(v,T?{outcome:T}:void 0)},be=null,Es=(m,w)=>{if(!be||be.toolCallId&&m&&be.toolCallId!==m)return;let v=be.resolve;be=null,S.setPermissionPrompt(null),v(w??{outcome:{outcome:"cancelled"}})},ot=m=>{if(!be?.toolCallId)return;let w=m??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===be.toolCallId&&(!w.status||w.status==="pending"||Es(w.toolCallId,void 0))},ln=()=>{if(!be){S.setPermissionPrompt(null);return}S.setPermissionPrompt({title:be.title,detail:be.detail,options:be.options.map(m=>({label:m.name})),selectedIndex:be.selectedIndex})},Ps=m=>{if(!be)return;let{options:w,resolve:v}=be;if(be=null,S.setPermissionPrompt(null),m===null){v({outcome:{outcome:"cancelled"}});return}v({outcome:{outcome:"selected",optionId:m}})};h.onRequest("session/request_permission",async m=>{if(b)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Ss(m);let w=m??{},T=(Array.isArray(w.options)?w.options:[]).map(te=>({optionId:te.optionId,name:Ae(te.name??""),...te.kind!==void 0?{kind:te.kind}:{}})),R=w.toolCall?.title??w.toolCall?.name??"tool",H=Ae(R),q=Ae(Mm(Pm(m))),L=w.toolCall?.toolCallId;return T.length===0?(S.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${H} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(te=>{be={title:H,detail:q,options:T,selectedIndex:0,resolve:te,toolCallId:L},ln()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let rs,Pr,Mr=!0,at=!1;try{let m=await h.request("initialize",{protocolVersion:nt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}});Pr=m?.agentInfo?.name,m?.agentCapabilities?.promptCapabilities?.image===!1&&(Mr=!1),at=xt(m?._meta??void 0).prompt?.amending===!0}catch{}let Te=a.sessionId,Xe=a.agentId,dt=a.cwd,Ms,Cn,is,un,$r,Rn,ve,fn,_r,wt;if(a.sessionId==="__new__"){let m={};s.agentId&&(m.agentId=s.agentId),s.name&&(m.title=s.name),s.model&&(m.model=s.model);let w=await h.request("session/new",{cwd:a.cwd,...Object.keys(m).length>0?{_meta:{[ht]:m}}:{}});Te=w.sessionId,r.sessionId=Te,r.readonly=!1;let v=xt(w._meta??void 0);v.clientId&&(Cn=v.clientId),rs=v.upstreamSessionId,v.agentId&&(Xe=v.agentId),v.cwd&&(dt=v.cwd),v.title&&(Ms=v.title),is=v.currentModel,un=v.currentMode,_r=v.currentUsage,wt=v.turnStartedAt,v.availableCommands&&($r=Oo(v.availableCommands)),v.availableModes&&(Rn=v.availableModes),ve=Uh(w.configOptions),fn=v.queue}else{let m={};s.readonly===!0&&(m.readonly=!0),e.tui.toolContent==="references"&&(m.toolContent="references"),s.drip===!0&&(m.replayMode="drip",s.dripSpeed!==void 0&&(m.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(m.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let w=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:pe},...Object.keys(m).length>0?{_meta:{[ht]:m}}:{}});Te=w.sessionId,w.clientId&&(Cn=w.clientId),r.sessionId=Te,r.readonly=s.readonly===!0;let v=xt(w._meta??void 0);rs=v.upstreamSessionId,v.agentId&&(Xe=v.agentId),v.cwd&&(dt=v.cwd),v.title&&(Ms=v.title),is=v.currentModel,un=v.currentMode,_r=v.currentUsage,wt=v.turnStartedAt,v.availableCommands&&($r=Oo(v.availableCommands)),v.availableModes&&(Rn=v.availableModes),ve=Uh(w.configOptions),fn=v.queue}let os=E.tuiHistoryFile(Te),Or=E.globalTuiHistoryFile(),Ue=await Gr(os).catch(()=>[]),ke=await Gr(Or).catch(()=>[]);ke.length>e.tui.promptHistoryMaxEntries&&(ke=ke.slice(ke.length-e.tui.promptHistoryMaxEntries));let Wt=[...Ue],de=new kn({history:ho(ke,Wt)});Re=de;let Ti=!1,_e=(m,w)=>{let v=m.replace(/\n+$/,"");if(v.length===0)return;let T=(w??m).replace(/\n+$/,""),R=Xr(Ue,v),H=R!==Ue;Ue=R,Wt=Xr(Wt,T);let q=Xr(ke,v,e.tui.promptHistoryMaxEntries),L=q!==ke;ke=q,de.setHistory(ho(ke,Wt)),H&&ws(os,Ue).catch(()=>{}),L&&Zu(Or,v).catch(()=>{})};j>0&&de.setTurnRunning(!0);let ze=null,as=null;yh(e.tui.ambiguousWidth==="wide"),Hp(e.tui.diffContextLines);let ds=!1,S,$s=()=>{ds&&(ds=!1,S.start())},Ei=()=>{ds||(ds=!0,S.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",$s),S=new va({term:t,dispatcher:de,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?Ei:void 0,onBlockClick:m=>{mg(m)},onBlockVisible:m=>{fg(m)},onMouse:m=>{if(m.kind!=="press"||m.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&jh(w)||ls(w)},onKey:m=>{for(let w of m){if(be&&$i(w)||bt(w)||Ie(w)||Mi(w)||pn(w)||Os(w))continue;if(w.type==="attachment-paths"){us(w.paths);continue}let v=de.feed(w);for(let T of v)s.readonly===!0&&jh(T)||ls(T)}cs(),S.setBannerSearchIndicator(de.state().historySearchQuery),S.setAttachments(de.state().attachments),S.refreshPrompt()}}),ee=S,S.setStickyBottomKey("plan");let Tn=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/demo-plan",description:"Inject synthetic plan events (UI test)"},{name:"/demo-tool",description:"Inject a synthetic tool-call sequence (UI test)"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt>"}],zt=$r??[],Jt=Rn??[],Fr=ve??[],Ta=()=>Fr.find(m=>m.id==="agent"),Pi=()=>{let m=new Set,w=[];for(let v of[...Tn,...zt])m.has(v.name)||(m.add(v.name),w.push(v));return w},_s=()=>{let m=de.state().buffer,w=m[0]??"";if(!w.startsWith("/"))return[];if(m.length>1)return[];let v=w.indexOf(" "),T=v===-1?w:w.slice(0,v);if(T.lastIndexOf("/")>0)return[];let R=Pi().filter(H=>H.name.startsWith(T));return R.length===1&&R[0]?.name===T&&v===-1?[]:R},Kt=[],cs=()=>{let m=_s();if(m.length>0){Kt=[],S.setCompletions(m);return}S.setCompletions(Kt)},pn=m=>{if(m.type!=="key"||m.name!=="tab")return Kt.length>0&&(Kt=[]),!1;let w=_s();if(S.isOverlayOpen()&&w.length===0)return S.toggleFocusedPane(),!0;if(w.length>0){Kt=[];let v=de.state().buffer[0]??"",T=kh({matches:w.map(R=>R.name),firstLine:v});return T===null||de.replaceFirstLine(T),!0}return En()},En=()=>{let m=de.state(),w=m.buffer[m.row]??"",v=_h(w,m.col);if(v===null)return!1;let T=Oh(v.token,dt);return T===null?!1:(T.replacement!==v.token&&de.replaceRangeOnCurrentLine(v.start,m.col,T.replacement),Kt=T.candidates.length>1?T.candidates.map(R=>({name:R})):[],!0)},Os=m=>!S.isOverlayOpen()||m.type!=="key"||m.name!=="escape"&&m.name!=="ctrl-c"?!1:(W&&(W.cancel(),W=null,z=null),S.closeBtwOverlay(),!0),Mi=m=>{if(!S.isScrollbackSearchActive())return m.type==="key"&&m.name==="ctrl-r"&&S.isScrolledBack()?(S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(""),!0):!1;if(m.type==="char"){let w=S.scrollbackSearchTerm()+m.ch;return S.updateScrollbackSearchTerm(w),!0}if(m.type==="paste"){let w=S.scrollbackSearchTerm()+m.text.replace(/\n/g," ");return S.updateScrollbackSearchTerm(w),!0}if(m.type==="key")switch(m.name){case"ctrl-r":return S.advanceScrollbackSearch(),!0;case"ctrl-s":return S.retreatScrollbackSearch(),!0;case"backspace":{let w=S.scrollbackSearchTerm();return w.length===0?S.cancelScrollbackSearch():S.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return S.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return S.cancelScrollbackSearch(),!0;default:return!0}return!0},$i=m=>{if(!be)return!1;let w=be.options;if(m.type==="key")switch(m.name){case"up":return be.selectedIndex=Math.max(0,be.selectedIndex-1),ln(),!0;case"down":return be.selectedIndex=Math.min(w.length-1,be.selectedIndex+1),ln(),!0;case"enter":{let v=w[be.selectedIndex];return v&&Ps(v.optionId),!0}case"escape":case"ctrl-c":return Ps(null),!0;default:return!0}if(m.type==="char"&&/^[1-9]$/.test(m.ch)){let v=parseInt(m.ch,10)-1,T=w[v];return T&&Ps(T.optionId),!0}return!0},Ea=Xe||Pr||"?",Ct={..._r??{}};c.finalize(),S.start({skipFullscreen:!0}),S.setHideThoughts(!i.showThoughts),S.setSessionbar({agent:Ea,cwd:dt,sessionId:Te,title:Ms,model:is,usage:{...Ct}}),un&&S.setBanner({currentMode:un}),yi().then(m=>{m&&S.notify(`\u2728 ${wi(m)}`,3e4)});let ct=null,Pa=new Promise(m=>{ct=m}),Lr=()=>{h.notify("session/cancel",{sessionId:Te}).catch(()=>{})},_i=()=>{ee!==null&&j===1&&(Z=!0,ee.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Fs=()=>{if(ze){ze.cancel(),_i();return}if(j>0){Lr(),_i();return}Br()},Br=()=>{vt(0)},Pn=()=>{let m="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",m]]:[["Enter",m],["Ctrl+Enter / Shift+Enter / ^S",w]],...gx]},Mn=()=>{if(S.isHelpPromptActive()){S.setHelpPrompt(null);return}S.setHelpPrompt({title:"Hotkeys",entries:Pn(),hint:"any key dismisses \xB7 /help lists commands"})},bt=m=>S.isHelpPromptActive()?(m.type==="key"&&m.name==="ctrl-g",S.setHelpPrompt(null),!0):!1,mn=["tools","plan","thoughts","diffs","mouse","enter"],Rt=0,Nr=m=>{switch(m){case"tools":return i.toolsExpanded?"expanded":"collapsed";case"plan":return i.planExpanded?"expanded":"collapsed";case"thoughts":return i.showThoughts?"shown":"hidden";case"diffs":return i.showFileUpdates;case"mouse":return i.mouseEnabled?"on":"off";case"enter":return i.defaultEnterAction}},$n=m=>{switch(m){case"tools":return"Tools";case"plan":return"Plan";case"thoughts":return"Thoughts";case"diffs":return"File updates";case"mouse":return"Mouse capture";case"enter":return"Enter key"}},k=()=>({title:"Session options",options:mn.map(m=>({label:$n(m),value:Nr(m)})),selectedIndex:Rt}),P=()=>{S.isOptionsPromptActive()&&S.setOptionsPrompt(k())},O=()=>{if(S.isOptionsPromptActive()){S.setOptionsPrompt(null);return}Rt=0,S.setOptionsPrompt(k())},Y=m=>{switch(m){case"tools":i.toolsExpanded=!i.toolsExpanded,ae.clear(),lg();break;case"plan":i.planExpanded=!i.planExpanded,Ye=null,Vc();break;case"thoughts":i.showThoughts=!i.showThoughts,S.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",hn.clear(),pg();break;case"mouse":{let w=!S.isMouseEnabled();S.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}P()},ge=m=>{(async()=>{try{switch(m){case"tools":case"plan":S.notify(`${$n(m)} is session-only \u2014 not saved`);return;case"thoughts":await qr("showThoughts",i.showThoughts);break;case"diffs":await qr("showFileUpdates",i.showFileUpdates);break;case"mouse":await qr("mouse",i.mouseEnabled);break;case"enter":await qr("defaultEnterAction",i.defaultEnterAction);break}S.notify(`saved default: ${$n(m)} ${Nr(m)}`)}catch(w){S.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Ie=m=>{if(!S.isOptionsPromptActive())return!1;if(m.type==="key")switch(m.name){case"up":return Rt=Math.max(0,Rt-1),P(),!0;case"down":return Rt=Math.min(mn.length-1,Rt+1),P(),!0;case"enter":{let w=mn[Rt];return w&&Y(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return S.setOptionsPrompt(null),!0;case"ctrl-d":return S.setOptionsPrompt(null),!1;default:return!0}if(m.type==="char"){if(/^[1-9]$/.test(m.ch)){let w=parseInt(m.ch,10)-1,v=mn[w];return v&&(Rt=w,Y(v)),!0}if(m.ch==="s"||m.ch==="S"){let w=mn[Rt];return w&&ge(w),!0}}return!0},Me=()=>{b=!0,W?(W.cancel(),W=null,z=null):z!==null&&(rn(n,z).catch(()=>{}),z=null),process.off("SIGINT",Fs),process.platform!=="win32"&&process.off("SIGCONT",$s),Ee!==null&&(clearInterval(Ee),Ee=null),S.clearWindowTitle(),S.stop({keepFullscreen:!0}),ws(os,Ue).catch(()=>{}),g.close().catch(()=>{})},vt=(m=0)=>{Me(),ct&&(ct(null),ct=null),m!==0&&process.exit(m)},_n=async()=>{if(!ct)return;W?(W.cancel(),W=null,z=null):z!==null&&(rn(n,z).catch(()=>{}),z=null);let m=de.state().buffer.join(`
213
+ `);m.replace(/\s+$/,"").length>0&&_e(m),S.pauseRepaint(),S.stop({keepFullscreen:!0}),ws(os,Ue).catch(()=>{});let w=null,v=null;for(;w===null;){let q=await vn(n,{includeNonInteractive:!0}),L=await qc(t,{cwd:dt,sessions:q,config:e,target:n,currentSessionId:Te,prefs:o});if(L.kind==="abort"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(L.kind==="exit"){vt(0);return}if(L.kind==="new"){w={choice:L,sessions:q};break}if(L.kind==="fork"){let je=await Kh(t,n,L,q);if(je.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(je.kind==="back")continue;w={choice:{kind:"attach",sessionId:je.ctx.sessionId,...je.ctx.agentId?{agentId:je.ctx.agentId}:{}},sessions:q},v={readonly:!1,cwd:je.ctx.cwd},je.ctx.resumeHint!==void 0&&(v.resumeHint=je.ctx.resumeHint);break}let te=q.find(je=>je.sessionId===L.sessionId);if(!(te!==void 0&&!!te.importedFromMachine&&!te.upstreamSessionId&&L.readonly!==!0)){if(n.isLocal&&te&&!te.importedFromMachine&&L.readonly!==!0&&!(await vi(te.cwd)).ok){let pt=await As(t,te,{defaultCwd:Ut(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(pt.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(pt.kind==="back")continue;w={choice:L,sessions:q},v={readonly:!1,cwd:pt.path,resumeHint:{agentId:L.agentId??te.agentId??"",cwd:pt.path,upstreamSessionId:""}};break}w={choice:L,sessions:q};break}let ce={...s,readonly:!1},Se=await Jh(t,te,L,ce);if(Se.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}Se.kind!=="back"&&(w={choice:L,sessions:q},v={readonly:ce.readonly===!0,cwd:Se.ctx.cwd},Se.ctx.resumeHint!==void 0&&(v.resumeHint=Se.ctx.resumeHint))}let{choice:T}=w,R=ct;if(ct=null,process.off("SIGINT",Fs),g.close().catch(()=>{}),T.kind==="new"){let{sessionId:q,...L}=s,te={...L,cwd:dt,forceNew:!0,readonly:!1};T.prompt!==void 0&&(te.initialPrompt=T.prompt),R(te);return}if(T.kind!=="attach")return;let H={...s,sessionId:T.sessionId,cwd:v?.cwd??dt,readonly:v?.readonly??T.readonly===!0};T.agentId!==void 0&&(H.agentId=T.agentId),v?.resumeHint!==void 0?H.resumeHint=v.resumeHint:delete H.resumeHint,R(H)},Ls=async()=>{if(!ct)return;let w=(await vn(n)).filter(q=>q.status==="live");if(w.length<=1)return;let v=w.findIndex(q=>q.sessionId===Te),T=w[(v+1)%w.length],R=ct;ct=null,process.off("SIGINT",Fs),g.close().catch(()=>{});let H={...s,sessionId:T.sessionId,cwd:dt,readonly:!1};T.agentId!==void 0&&(H.agentId=T.agentId),R(H)},ls=m=>{switch(m.type){case"send":i.defaultEnterAction==="amend"?Fi(m.text,m.attachments,m.displayText):Dr(m.text,m.attachments,m.displayText);return;case"amend":i.defaultEnterAction==="amend"?Dr(m.text,m.attachments,m.displayText):Fi(m.text,m.attachments,m.displayText);return;case"queue-edit":{let w=Oi(m.index);if(!w)return;let v=[];m.text.length>0&&v.push({type:"text",text:m.text});for(let T of m.attachments)v.push({type:"image",data:T.data,mimeType:T.mimeType});h.request("hydra-acp/prompt/update",{sessionId:Te,messageId:w,prompt:v}).then(T=>{let R=T;!R.updated&&R.reason!=="ok"&&S.notify(`queue edit skipped (${R.reason})`)}).catch(T=>{S.notify(`queue edit failed: ${T.message}`)});return}case"queue-remove":{let w=Oi(m.index);if(!w)return;h.request("hydra-acp/prompt/cancel",{sessionId:Te,messageId:w}).then(v=>{let T=v;!T.cancelled&&T.reason!=="ok"&&S.notify(`queue cancel skipped (${T.reason})`)}).catch(v=>{S.notify(`queue cancel failed: ${v.message}`)});return}case"cancel":{if(S.isOverlayOpen()){W&&(W.cancel(),W=null,z=null),S.closeBtwOverlay();return}if(m.prefill&&ze){let w=et.size===0,v=de.state().buffer.every(T=>T==="");w&&v&&(as={text:ze.text,attachments:ze.attachments})}ze?ze.cancel():j>0&&Lr(),_i();return}case"exit":Br();return;case"plan-toggle":Ma(m.on);return;case"redraw-banner":S.setBanner({});return;case"redraw":S.fullRedraw();return;case"scroll-to-top":S.scrollToTop();return;case"scroll-to-bottom":S.scrollToBottom();return;case"switch-session":_n();return;case"next-live-session":Ls();return;case"toggle-options":O();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,S.setHideThoughts(!i.showThoughts),S.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!S.isMouseEnabled();S.setMouseEnabled(w),i.mouseEnabled=w,S.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Mn();return;case"escalate-search":S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(m.query);return;case"attachment-request":lt(m.source);return}},us=async m=>{if(!Mr){S.notify("agent does not accept image attachments");return}let w=0;for(let v of m){if(v.startsWith("data:")){let R=bc(v);if(!R){S.notify("unsupported data: URI");continue}if(R.sizeBytes>dn){S.notify(`image too large (${Ot(R.sizeBytes)}, max ${Ot(dn)})`);continue}de.addAttachment({mimeType:R.mimeType,data:R.data,name:"pasted image",sizeBytes:R.sizeBytes}),w++;continue}let T=Ii(v);if(!T){S.notify(`unsupported image type: ${Wc.basename(v)}`);continue}try{let R=await mx.readFile(v);if(R.length>dn){S.notify(`image too large (${Ot(R.length)}, max ${Ot(dn)})`);continue}de.addAttachment({mimeType:T,data:R.toString("base64"),name:Wc.basename(v),sizeBytes:R.length}),w++}catch(R){S.notify(`cannot read ${Wc.basename(v)}: ${R.message}`)}}w>0&&(S.setAttachments(de.state().attachments),S.refreshPrompt())},lt=async(m="clipboard")=>{let w=m==="primary"?await rh():await sh();if(!w.ok){S.notify(w.reason);return}if(w.kind==="image"){if(!Mr){S.notify("agent does not accept image attachments");return}de.addAttachment(w.attachment),S.setAttachments(de.state().attachments),S.refreshPrompt();return}let v=de.feed({type:"paste",text:w.text});for(let T of v)ls(T);S.refreshPrompt()},Ze=m=>m.attachmentCount>0?`${m.text} \xB7 \u{1F4CE}\xD7${m.attachmentCount}`:m.text,Vt=(m,w)=>{let v=Array.isArray(w)?w:[],T="",R=0;for(let H of v){if(!H||typeof H!="object")continue;let q=H;q.type==="text"&&typeof q.text=="string"?T+=q.text:q.type==="image"&&(R+=1)}return{messageId:m,text:Ae(T),attachmentCount:R}},et=new Map,ut=[],Nt=new Map,Yt=new Set,Qt=null,fs=()=>{let m=[...et.values()],w=m.map(Ze);S.setQueuedPrompts(w),S.setBanner({queued:m.length}),de.setQueue(m.map(v=>v.text))},Oi=m=>[...et.values()][m]?.messageId;if(fn&&fn.length>0){for(let m of fn){if(m.position===0){ie=m.messageId;continue}et.set(m.messageId,Vt(m.messageId,m.prompt))}et.size>0&&fs()}let Dr=(m,w,v)=>{S.scrollToBottom(),!It(m)&&(_e(m,v),Hr(m,w,v))},Fi=(m,w,v)=>{if(S.scrollToBottom(),It(m))return;if(_e(m,v),!at||ie===void 0){Hr(m,w,v);return}let T=ie,R=[];m.length>0&&R.push({type:"text",text:m});for(let L of w)R.push({type:"image",data:L.data,mimeType:L.mimeType});let H={text:m,displayText:v??m,attachments:w,flushed:!1};ut.push(H);let q=()=>{let L=ut.indexOf(H);L>=0&&ut.splice(L,1),H.messageId!==void 0&&Nt.delete(H.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Te,targetMessageId:T,prompt:R}).then(L=>{let te=L;if(te.amended&&te.reason==="ok"){X(1);return}if(q(),te.reason==="target_completed"){S.notify("previous response finished \u2014 press Enter to send as a new turn"),de.setBuffer(m,w),S.refreshPrompt();return}if(te.reason==="target_cancelled"){S.notify("amend skipped \u2014 previous turn was cancelled"),de.setBuffer(m,w),S.refreshPrompt();return}if(te.reason==="target_not_found"){S.notify("amend skipped \u2014 no matching prompt"),de.setBuffer(m,w),S.refreshPrompt();return}}).catch(L=>{q(),S.notify(`amend failed: ${L.message}`),de.setBuffer(m,w),S.refreshPrompt()})},Ma=async m=>{if(Jt.length===0){S.notify("no modes advertised by agent");return}let w=S.currentModeId(),v=Jt.findIndex(H=>H.id===w),T=v===-1?0:(v+1)%Jt.length,R=Jt[T]?.id;if(R){S.setBanner({currentMode:R});try{await h.request("session/set_mode",{sessionId:Te,modeId:R})}catch(H){S.notify(`set_mode failed: ${H.message}`)}}},It=m=>{let w=m.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
214
+ `))return!1;let v=w.indexOf(" ");switch(v===-1?w:w.slice(0,v)){case"/quit":case"/exit":return Br(),!0;case"/clear":return ft.clear(),Fn.clear(),Dt.length=0,J=null,le=null,Je=null,On.clear(),hn.clear(),U.clear(),ae.clear(),F.clear(),re.clear(),S.clearScrollback(),!0;case"/demo-plan":{S.clearKey("plan");let R=["Step 1","Step 2","Step 3","Step 4","Step 5"],H=[["pending","pending","pending","pending","pending"],["in_progress","pending","pending","pending","pending"],["completed","in_progress","pending","pending","pending"],["completed","completed","in_progress","pending","pending"],["completed","completed","completed","in_progress","pending"],["completed","completed","completed","completed","in_progress"],["completed","completed","completed","completed","completed"]],q=0,L=()=>{let te=H[q];te&&(M({kind:"plan",entries:R.map((xe,ce)=>({content:xe,status:te[ce]??"pending"}))}),q+=1,setTimeout(L,600))};return L(),!0}case"/demo-tool":{let R=`demo-${Date.now()}`;return M({kind:"tool-call",toolCallId:R,title:"Terminal",status:"pending"}),setTimeout(()=>{M({kind:"tool-call-update",toolCallId:R,title:"echo hello world",status:"in_progress"})},500),setTimeout(()=>{M({kind:"tool-call-update",toolCallId:R,status:"completed"})},1500),!0}case"/help":{let R=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let H of Tn)R.push({prefix:" ",body:` ${H.name.padEnd(12)} ${H.description??""}`,bodyStyle:"info"});if(zt.length>0){R.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let H of zt)R.push({prefix:" ",body:` ${H.name.padEnd(12)} ${H.description??""}`,bodyStyle:"info"})}return S.appendLines(R),!0}case"/agent":{let R=v===-1?"":w.slice(v+1).trim(),H=Ta();if(!H)return S.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!R){let q=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let L of H.options){let te=L.value===H.currentValue?"* ":" ";q.push({prefix:" ",body:`${te}${L.value.padEnd(16)} ${L.name}`,bodyStyle:"info"})}return S.appendLines(q),!0}return H.options.some(q=>q.value===R)?R===H.currentValue?(S.notify(`already on agent ${R}`),!0):(S.notify(`switching to ${R}\u2026`),h.request("session/set_config_option",{sessionId:Te,configId:"agent",value:R}).catch(q=>{S.notify(`set_config_option failed: ${q.message}`)}),!0):(S.notify(`unknown agent: ${R}`),!0)}case"/sessions":return S.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return _n(),!0;case"/rename":{let R=v===-1?"":w.slice(v+1).trim(),H=R.length>0?`/hydra title ${R}`:"/hydra title";return _e(w,w),Hr(H,[],w),!0}case"/btw":{let R=v===-1?"":w.slice(v+1).trim();if(!R)return S.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(Te==="__new__")return S.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;D+=1;let H=D;W&&(W.cancel(),W=null);let q=null;z!==null&&!$?q=z:z!==null&&(rn(n,z).catch(()=>{}),z=null),$=!1,S.openBtwOverlay(),S.setBtwOverlayStatus({label:"busy",style:"busy"});let L=new pa;L.on("changed",()=>{S.setBtwOverlayContent(L.getLines())}),L.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:R}]});let te=ce=>{L.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ce}})},xe={};return q!==null&&(xe.reuseSessionId=q),Km(n,Te,R,xe).then(ce=>{if(H!==D){ce.cancel();return}W=ce,z=ce.sessionId,ce.on("event",Se=>{H===D&&(Se.kind==="update"?L.append(Se.update):Se.kind==="completed"?(S.setBtwOverlayStatus({label:"done",style:"done"}),W=null):Se.kind==="cancelled"?(S.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),W=null,z=null):Se.kind==="errored"&&(S.setBtwOverlayStatus({label:"errored",style:"errored"}),te(`btw errored: ${Se.error.message}`),z!==null&&rn(n,z).catch(()=>{}),W=null,z=null))})}).catch(ce=>{if(H!==D)return;let Se=ce instanceof Error?ce.message:String(ce);S.setBtwOverlayStatus({label:"errored",style:"errored"}),te(`btw startup failed: ${Se}`),S.appendLines([{prefix:" ",body:`btw startup failed: ${Se}`,bodyStyle:"tool-status-fail"}])}),!0}default:return!1}},Hr=async(m,w,v)=>{let T=[];m.length>0&&T.push({type:"text",text:m});for(let ce of w)T.push({type:"image",data:ce.data,mimeType:ce.mimeType});X(1);let R={text:m,displayText:v??m,attachments:w,flushed:!1};ut.push(R),cn=!1;let H=!1,q=null,L=ce=>{typeof ee<"u"&&ee!==null&&ee.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:ce,bodyStyle:"tool-status-fail"}])},te=!1;ze={text:m,attachments:w,cancel:()=>{if(cn){cn=!1,te=!0,L("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Te}).catch(Se=>{L(`force-stop failed: ${Se.message}`)});return}if(H)return;H=!0,h.notify("session/cancel",{sessionId:Te}).catch(()=>{});let ce=Date.now();q=setTimeout(()=>{ze!==null&&(Ts>=ce||(cn=!0,L("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Ri)}};let xe;try{let ce=await h.request("session/prompt",{sessionId:Te,prompt:T});ce&&typeof ce.stopReason=="string"&&(xe=ce.stopReason)}catch(ce){let Se=ut.indexOf(R);Se>=0&&ut.splice(Se,1),R.messageId!==void 0&&Nt.delete(R.messageId),te?S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):S.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:ce.message,bodyStyle:"tool-status-fail"}])}finally{if(ze=null,q!==null&&(clearTimeout(q),q=null),X(-1),R.flushed&&Qt===R){let ce=R.messageId!==void 0&&Yt.has(R.messageId);ce&&R.messageId!==void 0&&Yt.delete(R.messageId);let Se={kind:"turn-complete"};xe!==void 0&&(Se.stopReason=xe),ce&&(Se.amended=!0),M(Se),Qt=null}if(as!==null){let{text:ce,attachments:Se}=as;as=null,de.state().buffer.every(pt=>pt==="")&&(de.setBuffer(ce,Se),S.refreshPrompt())}}},ft=new Map,On=new Map,hn=new Map,Fn=new Map,Dt=[],Ln=0,C=`tools:${Ln}`,U=new Map,ae=new Map,F=new Map,re=new Map,J=null,le=null,Je=null,Pe=null,Ye=null,Be=e.tui.maxToolItems,Ht=e.tui.maxPlanItems,Ur=()=>({maxPlanItems:Ye??i.planExpanded?1/0:Ht}),Vc=()=>{if(Pe===null)return;let m=on(Pe,Ur());m.length>0&&S.upsertLines("plan",[{body:""},...m])},Li="",Bs=null,Yc=0,rg=()=>{if(Bs===null)return;let m=S.width(),w=Ir(Li,m>0?{maxWidth:m}:void 0);w.length!==0&&S.upsertLines(Bs,w)},ig=m=>{m.length!==0&&(Bs===null&&(S.ensureSeparator(),Bs=`agent:${Yc}`,Yc+=1,Li=""),Li+=m,rg())},Bn=()=>{Bs=null,Li=""},Ns="",ps=null,Qc=0,og=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),ag=()=>{if(ps===null||Ns.length===0)return;let m=Vd(Ns);m.length!==0&&S.upsertLines(ps,m)},dg=m=>{let w=F.get(m);if(w===void 0)return[];let v=Vd(w.text);return w.workerTaskId&&v.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),v},cg=(m,w)=>{m.length!==0&&(ps===null&&(S.ensureSeparator("thought"),ps=`thought:${Qc}`,Qc+=1,Ns=""),Ns+=m,F.set(ps,{text:Ns,workerTaskId:w}),ag())},Nn=()=>{ps=null,Ns=""},Gc=m=>{let{order:w,states:v,startedAt:T,endedAt:R,stopReason:H}=m,q=w.length,L=Be>0,te=!L||m.expanded?w:w.slice(Math.max(0,q-Be)),xe=q-te.length,ce=R===null,Se=R??Date.now(),je=Se-T,pt=!ce&&H!==null&&H!=="end_turn"?H:null,ol=pt==="amended",al=ol?`amended \xB7 ${an(je)}`:`stopped (${pt}) \xB7 ${an(je)}`,Hi;if(q===0)pt!==null?Hi=al:Hi=ce?`thinking \xB7 ${an(je)}`:`thought \xB7 ${an(je)}`;else{let _a=q===1?"tool":"tools",Ui=pt!==null?al:ce?an(je):`took ${an(je)}`,ul=[`${q} ${_a}`,Ui];ce&&L&&xe>0&&ul.push(`${xe} hidden`),Hi=ul.join(" \xB7 ")}let dl=q===0&&ce,cl=ol?"tool-status-cancelled":"tool-status-fail",ll=[{prefix:"\u2699 ",prefixStyle:dl?"tool-status-running":pt!==null?cl:"tool",body:Hi,bodyStyle:dl?"tool-status-running":pt!==null?cl:"dim"}];for(let _a of te){let Ui=v.get(_a);Ui&&ll.push(...hi(Ui,Se))}return ll},Xc=m=>ae.get(m)??i.toolsExpanded,Tt=()=>{if(J===null)return;let m=Gc({order:Dt,states:ft,startedAt:J,endedAt:le,stopReason:Je,expanded:Xc(C)});S.upsertLines(C,m)},Zc=m=>{let w=U.get(m);if(!w)return;let v=Gc({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Xc(m)});S.upsertLines(m,v)},lg=()=>{J!==null&&!U.has(C)&&Tt();for(let m of U.keys())Zc(m)},$a=()=>{J!==null&&U.set(C,{order:[...Dt],states:new Map(ft),startedAt:J,endedAt:le??Date.now(),stopReason:Je})},el=()=>{Ln+=1,C=`tools:${Ln}`,J=Date.now(),le=null,Je=null,Tt()},tl=(m,w,v,T,R,H,q)=>{let L=!ft.has(m),te=ft.get(m),xe=te??{initialTitle:w??"tool",latestTitle:w??"tool",status:v??"pending",startedAt:Date.now()};!te&&q!==void 0&&(xe.workerTaskId=q),te&&w!==void 0&&(xe.latestTitle=w),H!==void 0&&xe.detail===void 0&&(xe.detail=H),te&&v!==void 0&&(xe.status=v),te||(xe.status=v??"pending"),xe.endedAt===void 0&&qp(xe.status)&&(xe.endedAt=Date.now()),T!==void 0&&(xe.errorText=T),R!==void 0&&(xe.editDiff=R),ft.set(m,xe),L&&(J===null&&(Ln+=1,C=`tools:${Ln}`,J=Date.now(),le=null,Je=null),Dt.push(m))},nl=async m=>{try{let w=await h.request("hydra-acp/session/tool_content",{sessionId:Te,hash:m});return typeof w?.content=="string"?w.content:null}catch{return null}},Bi=new Set,ug=(m,w)=>{Bi.has(m)||w.oldRef===void 0&&w.newRef===void 0||(Bi.add(m),(async()=>{let[v,T]=await Promise.all([w.oldRef?nl(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?nl(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&v===null||w.newRef!==void 0&&T===null){Bi.delete(m);let xe=Yd(w,"diff",{deferredStatus:"error"});xe.length>0&&(S.upsertLines(`editdiff:${m}`,xe),S.repaintNow());return}let H={...w.path!==void 0?{path:w.path}:{},oldText:v??"",newText:T??""};On.set(m,H);let q=ft.get(m);q?.editDiff&&(q.editDiff=H),Bi.delete(m);let L=hn.get(m),te=L===void 0?i.showFileUpdates:L?"diff":"edit";te!=="none"&&(Ni(m,H,te==="diff"?"diff":"edit"),S.repaintNow())})())},Ni=(m,w,v)=>{let T=`editdiff:${m}`,R=Yd(w,v);if(R.length===0){S.removeKey(T);return}S.upsertLines(T,R),v==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&S.notifyWhenVisible(T)},fg=m=>{if(!m.startsWith("editdiff:"))return;let w=m.slice(9),v=On.get(w);v&&(v.oldRef!==void 0||v.newRef!==void 0)&&ug(w,v)},sl=m=>{let w=`editdiff:${m}`,v=i.showFileUpdates,T=ft.get(m),R;if(v==="none"||!T?.editDiff||T.status!=="completed")R=null;else{let q=hn.get(m);R=q!==void 0?q?"diff":"edit":v==="diff"?"diff":"edit"}if(R===null){S.removeKey(w);return}let H=T.editDiff;On.set(m,H),Ni(m,H,R)},pg=()=>{let m=i.showFileUpdates;for(let[w,v]of On){let T=`editdiff:${w}`,R=hn.get(w),H=R===void 0?m:R?"diff":"edit";if(H==="none"){S.removeKey(T);continue}Ni(w,v,H==="diff"?"diff":"edit")}},mg=m=>{if(m.startsWith("editdiff:")){let w=m.slice(9),v=On.get(w);if(!v)return;let T=hn.get(w)??i.showFileUpdates==="diff";hn.set(w,!T),Ni(w,v,T?"edit":"diff"),S.repaintNow();return}if(m==="plan"){if(Pe===null)return;Ye=!(Ye??i.planExpanded),Vc(),S.repaintNow();return}if(m.startsWith("tools:")){let w=ae.get(m)??i.toolsExpanded;ae.set(m,!w),m===C&&J!==null?Tt():Zc(m),S.repaintNow();return}if(m.startsWith("thought:")){if(!F.has(m))return;let w=re.get(m);if(w!==void 0){re.delete(m),S.setRunCollapsed(w,!1,dg(m)),S.repaintNow();return}let v=S.contiguousRun(m,new Set(F.keys()));if(v.length===0)return;let T=v[0];re.set(T,v),S.setRunCollapsed(v,!0,[og()]),S.repaintNow();return}};I=m=>{if(m.kind==="available-commands"){zt=m.commands,cs();return}if(m.kind==="available-modes"){Jt=m.modes;return}if(m.kind==="config-options"){Fr=m.options;let v=m.options.find(R=>R.id==="agent");v&&v.currentValue&&v.currentValue!==Xe&&(Xe=v.currentValue,S.setSessionbar({agent:v.currentValue}));let T=m.options.find(R=>R.id==="mode");T&&(Jt=T.options.map(R=>({id:R.value,name:R.name??R.value,...R.description!==void 0?{description:R.description}:{}})));return}if(m.kind==="mode-changed"){S.setBanner({currentMode:m.mode||void 0});return}if(m.kind==="session-info"){m.title!==void 0&&S.setSessionbar({title:m.title}),m.agentId!==void 0&&m.agentId!==Xe&&(Xe=m.agentId,S.setSessionbar({agent:m.agentId}));return}if(m.kind==="usage-update"){let v=!1;m.used!==void 0&&Ct.used!==m.used&&(Ct.used=m.used,v=!0),m.size!==void 0&&Ct.size!==m.size&&(Ct.size=m.size,v=!0),m.costAmount!==void 0&&Ct.costAmount!==m.costAmount&&(Ct.costAmount=m.costAmount,v=!0),m.costCurrency!==void 0&&Ct.costCurrency!==m.costCurrency&&(Ct.costCurrency=m.costCurrency,v=!0),v&&S.setSessionbar({usage:{...Ct}});return}if(m.kind==="user-text"){Ti&&_e(m.text),Bn(),Nn(),J!==null&&(le=Date.now(),Tt()),Qt=null,S.ensureSeparator();let v=on(m);v.length>0&&S.appendLines(v),$a(),S.clearKey("plan"),Pe=null,Ye=null,ft.clear(),Fn.clear(),Dt.length=0,le=null,el(),S.redraw();return}if(m.kind==="agent-text"){Nn(),Bs===null&&Q(m.workerTaskId),ig(m.text);return}if(m.kind==="agent-thought"){Bn(),ps===null&&Q(m.workerTaskId),cg(m.text,m.workerTaskId);return}if(m.kind==="exit-plan-mode"){Bn(),Nn();let v=Fn.get(m.toolCallId),T={plan:m.plan??v?.plan??"",status:m.status??v?.status};if(Fn.set(m.toolCallId,T),T.plan.length===0)return;let R=Wp(T);R.length>0&&S.upsertLines(m.toolCallId,R);return}if(m.kind==="tool-call"){Bn(),Nn(),ft.has(m.toolCallId)||Q(m.workerTaskId),tl(m.toolCallId,m.title,m.status,void 0,m.editDiff,m.detail,m.workerTaskId),Tt(),sl(m.toolCallId);return}if(m.kind==="plan"){Bn(),Nn(),Pe=m;let v=on(m,Ur());v.length>0&&S.upsertLines("plan",[{body:""},...v]);let T=m.entries.length>0&&m.entries.every(R=>(R.status??"pending")==="completed");S.setStickyBottomKey(T?null:"plan");return}if(m.kind==="tool-call-update"){Bn(),Nn(),tl(m.toolCallId,m.title,m.status,m.errorText,m.editDiff,m.detail,m.workerTaskId),m.upstreamInterrupted&&(Ce=!0),Tt(),sl(m.toolCallId);return}m.kind==="model-changed"&&S.setSessionbar({model:m.model});let w=on(m);if(w.length>0&&S.appendLines(w),m.kind==="turn-complete"){ie=void 0,Bn(),Nn();let v=m.amended?"amended":m.stopReason;if(!m.amended&&Ce&&(v===void 0||v==="end_turn")&&(v="error"),Pe!==null&&v!==void 0&&v!=="end_turn"){let T=on({...Pe,stopped:!0,amended:m.amended===!0},Ur());T.length>0&&S.upsertLines("plan",[{body:""},...T])}Pe=null,Ye=null,S.clearKey("plan"),S.setStickyBottomKey("plan"),J!==null?(le=Date.now(),Je=v??null,Tt(),$a()):v!==void 0&&v!=="end_turn"&&v!=="amended"&&S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${v}`,bodyStyle:"tool-status-fail"}]),ft.clear(),Fn.clear(),Dt.length=0,J=null,le=null,Je=null,Ce=!1,S.ensureSeparator(),Bh({pendingTurns:j,queueSize:et.size,ownTurnInFlight:ze!==null,hasInFlightHead:ie!==void 0,replayDraining:x,amended:m.amended===!0})&&X(-j)}};let rl=y;y=[];let Di=[];for(let m of rl)m.kind==="user-text"&&typeof m.text=="string"&&Di.push(m.text);S.pauseRepaint(),x=!0;try{for(let m of rl)I(m)}finally{x=!1,S.resumeRepaint()}if(Di.length>0){let m=Cd(Ue,Di);m!==Ue&&(Ue=m,Wt=Cd(Wt,Di),de.setHistory(ho(ke,Wt)),ws(os,Ue).catch(()=>{}))}Ti=!0,wt!==void 0&&j>0?(se=wt,S.setBanner({status:"busy",elapsedMs:Date.now()-wt}),Ee===null&&(Ee=setInterval(()=>{se===null||ee===null||(ee.setBanner({elapsedMs:Date.now()-se}),Tt())},1e3)),J===null&&el(),J=wt,Tt()):wt===void 0&&j>0&&X(-j);let hg=()=>{if(be){let m=be.resolve;be=null,S.setPermissionPrompt(null),m({outcome:{outcome:"cancelled"}})}Bn(),Nn()},il=()=>{J!==null&&(le=Date.now(),Je="reconnect-recovery-failed",Tt(),$a(),ft.clear(),Fn.clear(),Dt.length=0,J=null,le=null,Je=null)};return p=()=>{S.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{hg();let m={jsonrpc:"2.0",id:`tui-reinit-${Hh()}`,method:"initialize",params:{protocolVersion:nt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}}};try{await g.request(m)}catch{}let w=Rs!==void 0,v={jsonrpc:"2.0",id:`tui-reattach-${Hh()}`,method:"session/attach",params:{sessionId:Te,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Rs}:{},clientInfo:{name:"hydra-acp-tui",version:pe},...(()=>{let L={};return rs!==void 0&&(L.resume={upstreamSessionId:rs,agentId:Xe,cwd:dt}),e.tui.toolContent==="references"&&(L.toolContent="references"),Object.keys(L).length>0?{_meta:{[ht]:L}}:{}})()}};Ft=[];let T,R,H;try{let L=await g.request(v);if(L.error)throw new Error(L.error.message);H=Lh(L.result),T=H.appliedPolicy,H.clientId!==void 0&&(Cn=H.clientId)}catch(L){R=L}let q=Ft??[];if(Ft=null,R)il(),S.appendLines([{prefix:" ",body:`reattach failed: ${R.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&T!=="after_message")il(),S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{x=!0;try{for(let L of q)yt(L)}finally{x=!1}}if(H){let L=Nh({daemonTurnStartedAt:H.turnStartedAt,pendingTurns:j});L.pendingTurnsDelta!==0&&X(L.pendingTurnsDelta),L.banner==="busy"&&L.busySince!==void 0?(se=L.busySince,S.setBanner({status:"busy",elapsedMs:Date.now()-L.busySince}),Ee===null&&(Ee=setInterval(()=>{se===null||ee===null||(ee.setBanner({elapsedMs:Date.now()-se}),Tt())},1e3))):S.setBanner({status:"ready",elapsedMs:void 0})}else S.setBanner({status:j>0?"busy":"ready",elapsedMs:j>0?0:void 0})},h.onClose(m=>{m&&t.red(`
215
215
  connection lost: ${m.message}
216
- `),bt(m?1:0)}),process.on("SIGINT",Es),s.initialPrompt&&a.sessionId==="__new__"&&Or(s.initialPrompt,[]),await Ca}async function yx(t,e,n,s,r){let i=s.cwd??process.cwd();if(s.sessionId){let o={sessionId:s.sessionId,agentId:s.agentId??"",cwd:i};return s.resumeHint!==void 0&&(o.resumeHint=s.resumeHint),o}if(s.forceNew)return await jh(t,n,s)!=="ok"?null:Uh(s,i,e);if(s.resume){let o=await yn(n,{cwd:i,all:!0}),a=Ko(o,i);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}:(t.yellow(`No sessions found for ${i}.
217
- `),null)}for(;;){let o=await yn(n,{includeNonInteractive:!0}),a=await Dc(t,{cwd:i,sessions:o,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt);let l=await jh(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return Uh(s,i,e)}if(a.kind==="fork"){let l=await zh(t,n,a,o);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let d=o.find(l=>l.sessionId===a.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let l=await Wh(t,d,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await hi(d.cwd)).ok){let f=await Si(t,d,{defaultCwd:Dt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let u=a.agentId??d.agentId??"";return{sessionId:a.sessionId,agentId:u,cwd:f.path,resumeHint:{agentId:u,cwd:f.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Wh(t,e,n,s){for(;;){let r=await yh(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await Si(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function zh(t,e,n,s){let r=s.find(d=>d.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let d=await Si(t,r);if(d.kind==="cancel")return{kind:"cancel"};if(d.kind==="back")return{kind:"back"};o=d.path}let a;try{a=await Jo(e,n.sourceSessionId,i?{cwd:o}:{})}catch(d){return t.red(`
216
+ `),vt(m?1:0)}),process.on("SIGINT",Fs),s.initialPrompt&&a.sessionId==="__new__"&&Dr(s.initialPrompt,[]),await Pa}async function wx(t,e,n,s,r){let i=s.cwd??process.cwd();if(s.sessionId){let o={sessionId:s.sessionId,agentId:s.agentId??"",cwd:i};return s.resumeHint!==void 0&&(o.resumeHint=s.resumeHint),o}if(s.forceNew)return await Wh(t,n,s)!=="ok"?null:qh(s,i,e);if(s.resume){let o=await vn(n,{cwd:i,all:!0}),a=Qo(o,i);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}:(t.yellow(`No sessions found for ${i}.
217
+ `),null)}for(;;){let o=await vn(n,{includeNonInteractive:!0}),a=await qc(t,{cwd:i,sessions:o,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt),a.cwd!==void 0&&(i=a.cwd,s.cwd=a.cwd);let l=await Wh(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return qh(s,i,e)}if(a.kind==="fork"){let l=await Kh(t,n,a,o);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let d=o.find(l=>l.sessionId===a.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let l=await Jh(t,d,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await vi(d.cwd)).ok){let u=await As(t,d,{defaultCwd:Ut(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(u.kind==="cancel")return null;if(u.kind==="back")continue;let f=a.agentId??d.agentId??"";return{sessionId:a.sessionId,agentId:f,cwd:u.path,resumeHint:{agentId:f,cwd:u.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Jh(t,e,n,s){for(;;){let r=await vh(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await As(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function Kh(t,e,n,s){let r=s.find(d=>d.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let d=await As(t,r);if(d.kind==="cancel")return{kind:"cancel"};if(d.kind==="back")return{kind:"back"};o=d.path}let a;try{a=await Yo(e,n.sourceSessionId,i?{cwd:o}:{})}catch(d){return t.red(`
218
218
  fork failed: ${d.message}
219
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function Uh(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function jh(t,e,n){if(n.agentId||await Sl())return"ok";let s;try{s=await pp(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await Ch(t,s);if(r.kind==="cancel")return"cancel";if(r.kind==="back")return"back";if(n.agentId=r.agentId,r.persist)try{await Ui(r.agentId)}catch{}return"ok"}function wx(t,e){bx({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function bx(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?P.tuiLogFile():e;if(n.length!==0)try{Ix(n);let s=JSON.stringify({t:new Date().toISOString(),...t});cx(n,`${s}
220
- `)}catch{}}function vx(t,e){let n=!1,s="",r=!1,i=d=>{n||d===3&&r||d===0&&!r||(r=d===3,process.stdout.write(`\x1B]9;4;${d}\x1B\\`))},o=d=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(d),s=d)},a=d=>{let c=`${d.agentId}@${d.version}`;if(d.source==="npm")return d.phase==="install_start"||d.phase==="download_start"?`${e} installing ${c} via npm\u2026`:d.phase==="installed"?`${e} ${c} installed`:`${e} installing ${c} via npm\u2026`;if(d.phase==="download_start"||d.phase==="download_progress"){let l=d.receivedBytes??0,f=d.totalBytes??0,u=(l/1e6).toFixed(1);if(f>0){let p=(f/1e6).toFixed(1),g=Math.min(100,Math.floor(l/f*100));return`${e} downloading ${c} ${u}/${p} MB (${g}%)`}return`${e} downloading ${c} ${u} MB`}return d.phase==="download_done"?`${e} downloaded ${c}, verifying\u2026`:d.phase==="extract"?`${e} extracting ${c}\u2026`:d.phase==="installed"?`${e} ${c} installed`:s||e};return{write(d){n||(t.brightYellow(d),s=d)},applyProgress(d){if(n)return;d.phase==="download_start"||d.phase==="download_progress"||d.phase==="install_start"||d.phase==="extract"||d.phase==="download_done"?i(3):d.phase==="installed"&&i(0),o(a(d))},finalize(){n||(n=!0,i(0),process.stdout.write(`
221
- `))}}}function Ix(t){try{if(lx(t).size<Jh)return;ux(t,`${t}.0`)}catch{}}var mx,hx,Jh,Kh=V(()=>{"use strict";Ks();nt();oc();Oe();uc();js();dr();xo();Wi();en();ue();$t();oa();cc();po();oi();zm();Jm();Ih();xh();Oc();Rh();Pc();hc();fa();vc();Sa();_h();Bh();Un();yr();mx=12e4;hx=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next live session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];Jh=5*1024*1024});var Vh={};gg(Vh,{runTui:()=>qh});var Yh=V(()=>{"use strict";Kh()});import{readFileSync as Sx}from"fs";import{fileURLToPath as kx}from"url";import{dirname as xx,resolve as Ax}from"path";var cl=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),yg=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function ll(t){for(let e of Object.keys(t))if(!cl.has(e)&&!yg.has(e))return e}function Ma(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let d=r.slice(2,i);n[d]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(cl.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function wg(t,e){let n=t[e];if(typeof n=="string")return n}function Os(t,e){return t[e]===!0||t[e]==="true"}var bg="HYDRA_ACP_";function vg(t){return bg+t.toUpperCase().replace(/-/g,"_")}function Ve(t,e){let n=wg(t,e);return n!==void 0?n:process.env[vg(e)]}Oe();js();async function Ml(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=La(n);return{target:await El(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await G();return{target:await Qt(s),sessionId:n,fromUrl:!1}}function ja(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}ue();Oe();ft();import*as $l from"fs/promises";async function _l(t){if(await $l.mkdir(P.home(),{recursive:!0}),await Hi(),!await Bs()){let n=Ls();await Ns(n),process.stdout.write(`Initialized ${P.authToken()}
219
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function qh(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Wh(t,e,n){if(n.agentId||await Al())return"ok";let s;try{s=await gp(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await Th(t,s);if(r.kind==="cancel")return"cancel";if(r.kind==="back")return"back";if(n.agentId=r.agentId,r.persist)try{await Wi(r.agentId)}catch{}return"ok"}function bx(t,e){vx({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function vx(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?E.tuiLogFile():e;if(n.length!==0)try{Sx(n);let s=JSON.stringify({t:new Date().toISOString(),...t});lx(n,`${s}
220
+ `)}catch{}}function Ix(t,e){let n=!1,s="",r=!1,i=d=>{n||d===3&&r||d===0&&!r||(r=d===3,process.stdout.write(`\x1B]9;4;${d}\x1B\\`))},o=d=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(d),s=d)},a=d=>{let c=`${d.agentId}@${d.version}`;if(d.source==="npm")return d.phase==="install_start"||d.phase==="download_start"?`${e} installing ${c} via npm\u2026`:d.phase==="installed"?`${e} ${c} installed`:`${e} installing ${c} via npm\u2026`;if(d.phase==="download_start"||d.phase==="download_progress"){let l=d.receivedBytes??0,u=d.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),g=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${c} ${f}/${p} MB (${g}%)`}return`${e} downloading ${c} ${f} MB`}return d.phase==="download_done"?`${e} downloaded ${c}, verifying\u2026`:d.phase==="extract"?`${e} extracting ${c}\u2026`:d.phase==="installed"?`${e} ${c} installed`:s||e};return{write(d){n||(t.brightYellow(d),s=d)},applyProgress(d){if(n)return;d.phase==="download_start"||d.phase==="download_progress"||d.phase==="install_start"||d.phase==="extract"||d.phase==="download_done"?i(3):d.phase==="installed"&&i(0),o(a(d))},finalize(){n||(n=!0,i(0),process.stdout.write(`
221
+ `))}}}function Sx(t){try{if(ux(t).size<Vh)return;fx(t,`${t}.0`)}catch{}}var hx,gx,Vh,Yh=V(()=>{"use strict";Xs();st();cc();Oe();mc();Ks();pr();Ro();Ki();nn();me();Mt();ca();fc();go();ui();Vm();Ym();Ch();Dc();Bc();Eh();_c();wc();ha();kc();xa();Fh();Dh();zn();Sr();hx=12e4;gx=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next live session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];Vh=5*1024*1024});var Qh={};yg(Qh,{runTui:()=>zh});var Gh=V(()=>{"use strict";Yh()});import{readFileSync as kx}from"fs";import{fileURLToPath as xx}from"url";import{dirname as Ax,resolve as Cx}from"path";var fl=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),wg=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function pl(t){for(let e of Object.keys(t))if(!fl.has(e)&&!wg.has(e))return e}function Oa(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let d=r.slice(2,i);n[d]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(fl.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function bg(t,e){let n=t[e];if(typeof n=="string")return n}function Ds(t,e){return t[e]===!0||t[e]==="true"}var vg="HYDRA_ACP_";function Ig(t){return vg+t.toUpperCase().replace(/-/g,"_")}function Ve(t,e){let n=bg(t,e);return n!==void 0?n:process.env[Ig(e)]}Oe();Ks();async function Ol(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=Da(n);return{target:await $l(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await G();return{target:await Xt(s),sessionId:n,fromUrl:!1}}function za(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}me();Oe();mt();import*as Fl from"fs/promises";async function Ll(t){if(await Fl.mkdir(E.home(),{recursive:!0}),await qi(),!await js()){let n=Us();await qs(n),process.stdout.write(`Initialized ${E.authToken()}
222
222
  Service token: ${n}
223
- `);return}if(Os(t,"rotate-token")){let n=Ls();await Ns(n),process.stdout.write(`Rotated token in ${P.authToken()}
223
+ `);return}if(Ds(t,"rotate-token")){let n=Us();await qs(n),process.stdout.write(`Rotated token in ${E.authToken()}
224
224
  New token: ${n}
225
- `);return}process.stdout.write(`Service token already exists at ${P.authToken()}.
225
+ `);return}process.stdout.write(`Service token already exists at ${E.authToken()}.
226
226
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
227
- `)}ue();Oe();ft();import*as op from"fs/promises";import{setTimeout as $v}from"timers/promises";import ip from"chalk";import*as np from"fs";import*as Wn from"fs/promises";import kv from"fastify";import xv from"@fastify/websocket";var Ol="acp.v1";function Fl(t,e){return t.has(Ol)?Ol:!1}Oe();import tp from"pino";import Av from"pino-roll";ue();import*as Qe from"fs/promises";import{createHash as Dg}from"crypto";import{gzip as Hg,gunzip as Ug}from"zlib";import{promisify as Ll}from"util";var Bl=Ll(Hg),jg=Ll(Ug),Nl=/^[A-Za-z0-9_-]+$/,qg=/^[a-f0-9]{64}$/,qa=!0;function Dl(t){qa=t}function zi(t,e){return Nl.test(t)?e===void 0||qg.test(e):!1}function Ji(t,e){return`${P.toolBlobFile(t,e)}.gz`}async function Wa(t,e){if(!zi(t))return null;let n=Dg("sha256").update(e,"utf8").digest("hex"),s=Ji(t,n),r=P.toolBlobFile(t,n);for(let a of[s,r])try{return await Qe.access(a),n}catch{}await Qe.mkdir(P.toolsDir(t),{recursive:!0});let i=qa?s:r,o=qa?await Bl(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Qe.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Ki(t,e){if(!zi(t,e))return null;try{let n=await Qe.readFile(Ji(t,e));return(await jg(n)).toString("utf8")}catch{}try{return await Qe.readFile(P.toolBlobFile(t,e),"utf8")}catch{return null}}async function Hl(t,e){if(!zi(t,e))return null;try{return await Qe.readFile(Ji(t,e))}catch{}try{let n=await Qe.readFile(P.toolBlobFile(t,e));return await Bl(n)}catch{return null}}async function Ul(t,e,n){if(!zi(t,e))return;let s=Ji(t,e);try{await Qe.access(s);return}catch{}await Qe.mkdir(P.toolsDir(t),{recursive:!0}),await Qe.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function jl(t){Nl.test(t)&&await Qe.rm(P.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}ue();ls();import*as Zl from"fs/promises";import*as Yi from"path";import{z as re}from"zod";ue();import*as Wl from"fs";import*as et from"fs/promises";import*as Ln from"path";import{spawn as zl}from"child_process";import{Readable as Wg}from"stream";function Gt(){let t=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(!(!t||!e))return`${t}-${e}`}function Ka(t,e=Gt()){if(e)return t[e]}var qs=t=>{process.stderr.write(t+`
228
- `)};function Va(t){qs=t??(e=>process.stderr.write(e+`
229
- `))}async function Jl(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Gt()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=P.agentInstallDir(t.agentId,e,t.version),s=Ln.resolve(n,t.target.cmd);if(await Ja(s))return s;if(await zg({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Ja(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await et.chmod(s,493).catch(()=>{}),s}async function zg(t){await et.mkdir(Ln.dirname(t.installDir),{recursive:!0});let e=await et.mkdtemp(`${t.installDir}.partial-`);try{qs(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await Jg({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});qs(`hydra-acp: extracting ${t.agentId}`),Ws(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await Vg(n,e),await et.unlink(n).catch(()=>{});try{await et.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Ja(t.installDir)){await et.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ws(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}qs(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Ws(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await et.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Ws(t,e){if(t)try{t(e)}catch{}}async function Jg(t){let e=Kg(t.url),n=Ln.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Wl.createWriteStream(n),o=Wg.fromWeb(s.body);Ws(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,d=Date.now(),c=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-c>=f&&(c=p,Ws(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-d>=l&&(d=p,qs(ql(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),qs(ql(t.agentId,a,r,!0)),Ws(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function ql(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function Kg(t){let e=new URL(t);return Ln.posix.basename(e.pathname)||"archive"}async function Vg(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await za("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await Yg("unzip")){await za("unzip",["-q",t,"-d",e]);return}await za("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function za(t,e){return new Promise((n,s)=>{let r=zl(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function Yg(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=zl(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Ja(t){try{return await et.access(t),!0}catch{return!1}}ue();import*as St from"fs/promises";import*as Xt from"path";import{spawn as Qg}from"child_process";var Qa=t=>{process.stderr.write(t+`
230
- `)};function Ga(t){Qa=t??(e=>process.stderr.write(e+`
231
- `))}async function Vl(t){let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=P.agentNpmInstallDir(t.agentId,e,t.version),s=ty(t.packageSpec),r=ny(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Xt.join(n,"node_modules",".bin",t.bin);if(await us(o))return o;if(await us(n)){let f=await Kl(i);if(f)return f.binPath}await Gg({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Kl(i);if(a)return a.binPath;let d=await Ql(n,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],l=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function Gg(t){await St.mkdir(Xt.dirname(t.installDir),{recursive:!0});let e=await St.mkdtemp(`${t.installDir}.partial-`);try{Qa(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Ya(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await ey({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await St.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await us(t.installDir)){await St.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ya(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Qa(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Ya(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await St.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Ya(t,e){if(t)try{t(e)}catch{}}var Xg=5,Zg=25;function ey(t){return Yl(t,0)}async function Yl(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=Qg("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.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){n();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${c})
232
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${c})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<Xg)return await new Promise(r=>setTimeout(r,Zg*(e+1))),Yl(t,e+1);throw n}}function ty(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function ny(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Ql(t,e){let n=Xt.join(t,"node_modules",e,"package.json");try{let s=await St.readFile(n,"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 Kl(t){let e=Xt.join(t.installDir,"node_modules",".bin"),n=Xt.join(e,t.hint);if(await us(n))return{binName:t.hint,binPath:n};let s=await Ql(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Xt.join(e,i);if(await us(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=Xt.join(e,i);if(await us(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Xt.join(e,t.basename);if(await us(r))return{binName:t.basename,binPath:r}}}async function us(t){try{return await St.access(t),!0}catch{return!1}}var sy=re.object({package:re.string(),bin:re.string().optional(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),zs=re.object({archive:re.string().url().optional(),cmd:re.string().optional(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),ry=re.object({"darwin-aarch64":zs.optional(),"darwin-x86_64":zs.optional(),"linux-aarch64":zs.optional(),"linux-x86_64":zs.optional(),"windows-x86_64":zs.optional(),"windows-aarch64":zs.optional()}),iy=re.object({package:re.string(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),oy=re.object({command:re.string(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),ay=re.object({npx:sy.optional(),binary:ry.optional(),uvx:iy.optional(),exec:oy.optional()}),dy=re.object({id:re.string(),name:re.string(),version:re.string().optional(),description:re.string().optional(),authors:re.array(re.string()).optional(),license:re.string().optional(),icon:re.string().optional(),repository:re.string().optional(),website:re.string().optional(),distribution:ay}),Gl=re.object({version:re.string(),agents:re.array(dy),extensions:re.array(re.unknown()).optional()}),Vi=class{constructor(e,n={}){this.config=e;this.options=n}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 n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}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 n=this.localAgents().find(o=>o.id===e);if(n)return n;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=>Xa(o)===e);return i?this.applyOverride(i):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:n.command??e,args:n.args,env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:cy(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=Gl.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await Pt(P.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Gl.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await It(P.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function cy(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Xa(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Js(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.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 Za(o),source:s.has(o.id)?"local":"registry"})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Za(t){let e=Gt();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Ka(t.distribution.binary,e);if(s?.cmd){let r=Yi.resolve(P.agentInstallDir(t.id,e,n),s.cmd);if(await Xl(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Xa(t)??s.package,i=P.agentNpmInstallDir(t.id,e,n),o=Yi.join(i,"node_modules",".bin",r);if(await Xl(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Xl(t){try{return await Zl.access(t),!0}catch{return!1}}async function Bn(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.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??Xa(t)??r.package,a=n.onInstallProgress;return{command:await Vl({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=Ka(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Gt()??"this platform"}.`);let i=n.onInstallProgress,o=await Jl({agentId:t.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(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as my}from"child_process";import*as to from"fs";import*as pu from"path";nt();function eo(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let d=n.indexOf(`
233
- `);for(;d!==-1;){let c=n.slice(0,d).trim();if(n=n.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:0,error:{code:N.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}d=n.indexOf(`
227
+ `)}me();Oe();mt();import*as cp from"fs/promises";import{setTimeout as _v}from"timers/promises";import dp from"chalk";import*as ip from"fs";import*as Vn from"fs/promises";import xv from"fastify";import Av from"@fastify/websocket";var Bl="acp.v1";function Nl(t,e){return t.has(Bl)?Bl:!1}Oe();import rp from"pino";import Cv from"pino-roll";me();import*as Qe from"fs/promises";import{createHash as Hg}from"crypto";import{gzip as Ug,gunzip as jg}from"zlib";import{promisify as Dl}from"util";var Hl=Dl(Ug),qg=Dl(jg),Ul=/^[A-Za-z0-9_-]+$/,Wg=/^[a-f0-9]{64}$/,Ja=!0;function jl(t){Ja=t}function Vi(t,e){return Ul.test(t)?e===void 0||Wg.test(e):!1}function Yi(t,e){return`${E.toolBlobFile(t,e)}.gz`}async function Ka(t,e){if(!Vi(t))return null;let n=Hg("sha256").update(e,"utf8").digest("hex"),s=Yi(t,n),r=E.toolBlobFile(t,n);for(let a of[s,r])try{return await Qe.access(a),n}catch{}await Qe.mkdir(E.toolsDir(t),{recursive:!0});let i=Ja?s:r,o=Ja?await Hl(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Qe.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Qi(t,e){if(!Vi(t,e))return null;try{let n=await Qe.readFile(Yi(t,e));return(await qg(n)).toString("utf8")}catch{}try{return await Qe.readFile(E.toolBlobFile(t,e),"utf8")}catch{return null}}async function ql(t,e){if(!Vi(t,e))return null;try{return await Qe.readFile(Yi(t,e))}catch{}try{let n=await Qe.readFile(E.toolBlobFile(t,e));return await Hl(n)}catch{return null}}async function Wl(t,e,n){if(!Vi(t,e))return;let s=Yi(t,e);try{await Qe.access(s);return}catch{}await Qe.mkdir(E.toolsDir(t),{recursive:!0}),await Qe.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function zl(t){Ul.test(t)&&await Qe.rm(E.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}me();ms();import*as nu from"fs/promises";import*as Xi from"path";import{z as oe}from"zod";me();import*as Kl from"fs";import*as tt from"fs/promises";import*as Hn from"path";import{spawn as Vl}from"child_process";import{Readable as zg}from"stream";function Zt(){let t=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(!(!t||!e))return`${t}-${e}`}function Qa(t,e=Zt()){if(e)return t[e]}var Vs=t=>{process.stderr.write(t+`
228
+ `)};function Ga(t){Vs=t??(e=>process.stderr.write(e+`
229
+ `))}async function Yl(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Zt()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Zt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=E.agentInstallDir(t.agentId,e,t.version),s=Hn.resolve(n,t.target.cmd);if(await Ya(s))return s;if(await Jg({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Ya(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await tt.chmod(s,493).catch(()=>{}),s}async function Jg(t){await tt.mkdir(Hn.dirname(t.installDir),{recursive:!0});let e=await tt.mkdtemp(`${t.installDir}.partial-`);try{Vs(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await Kg({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Vs(`hydra-acp: extracting ${t.agentId}`),Ys(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await Yg(n,e),await tt.unlink(n).catch(()=>{});try{await tt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Ya(t.installDir)){await tt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ys(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Vs(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Ys(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await tt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Ys(t,e){if(t)try{t(e)}catch{}}async function Kg(t){let e=Vg(t.url),n=Hn.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Kl.createWriteStream(n),o=zg.fromWeb(s.body);Ys(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,d=Date.now(),c=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-c>=u&&(c=p,Ys(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-d>=l&&(d=p,Vs(Jl(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),Vs(Jl(t.agentId,a,r,!0)),Ys(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Jl(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function Vg(t){let e=new URL(t);return Hn.posix.basename(e.pathname)||"archive"}async function Yg(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Va("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await Qg("unzip")){await Va("unzip",["-q",t,"-d",e]);return}await Va("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Va(t,e){return new Promise((n,s)=>{let r=Vl(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function Qg(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Vl(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Ya(t){try{return await tt.access(t),!0}catch{return!1}}me();import*as kt from"fs/promises";import*as en from"path";import{spawn as Gg}from"child_process";var Za=t=>{process.stderr.write(t+`
230
+ `)};function ed(t){Za=t??(e=>process.stderr.write(e+`
231
+ `))}async function Gl(t){let e=Zt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=E.agentNpmInstallDir(t.agentId,e,t.version),s=ny(t.packageSpec),r=sy(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=en.join(n,"node_modules",".bin",t.bin);if(await hs(o))return o;if(await hs(n)){let u=await Ql(i);if(u)return u.binPath}await Xg({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Ql(i);if(a)return a.binPath;let d=await Zl(n,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],l=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function Xg(t){await kt.mkdir(en.dirname(t.installDir),{recursive:!0});let e=await kt.mkdtemp(`${t.installDir}.partial-`);try{Za(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Xa(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await ty({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await kt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await hs(t.installDir)){await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Xa(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Za(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Xa(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Xa(t,e){if(t)try{t(e)}catch{}}var Zg=5,ey=25;function ty(t){return Xl(t,0)}async function Xl(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=Gg("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.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){n();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${c})
232
+ stderr: ${l}`:`npm install ${t.packageSpec} failed (${c})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<Zg)return await new Promise(r=>setTimeout(r,ey*(e+1))),Xl(t,e+1);throw n}}function ny(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function sy(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Zl(t,e){let n=en.join(t,"node_modules",e,"package.json");try{let s=await kt.readFile(n,"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 Ql(t){let e=en.join(t.installDir,"node_modules",".bin"),n=en.join(e,t.hint);if(await hs(n))return{binName:t.hint,binPath:n};let s=await Zl(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=en.join(e,i);if(await hs(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=en.join(e,i);if(await hs(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=en.join(e,t.basename);if(await hs(r))return{binName:t.basename,binPath:r}}}async function hs(t){try{return await kt.access(t),!0}catch{return!1}}var ry=oe.object({package:oe.string(),bin:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),Qs=oe.object({archive:oe.string().url().optional(),cmd:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),iy=oe.object({"darwin-aarch64":Qs.optional(),"darwin-x86_64":Qs.optional(),"linux-aarch64":Qs.optional(),"linux-x86_64":Qs.optional(),"windows-x86_64":Qs.optional(),"windows-aarch64":Qs.optional()}),oy=oe.object({package:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),ay=oe.object({command:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),dy=oe.object({npx:ry.optional(),binary:iy.optional(),uvx:oy.optional(),exec:ay.optional()}),cy=oe.object({id:oe.string(),name:oe.string(),version:oe.string().optional(),description:oe.string().optional(),authors:oe.array(oe.string()).optional(),license:oe.string().optional(),icon:oe.string().optional(),repository:oe.string().optional(),website:oe.string().optional(),distribution:dy}),eu=oe.object({version:oe.string(),agents:oe.array(cy),extensions:oe.array(oe.unknown()).optional()}),Gi=class{constructor(e,n={}){this.config=e;this.options=n}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 n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}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 n=this.localAgents().find(o=>o.id===e);if(n)return n;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=>td(o)===e);return i?this.applyOverride(i):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:n.command??e,args:n.args,env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:ly(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=eu.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await Et(E.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=eu.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await St(E.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function ly(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function td(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Gs(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.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 nd(o),source:s.has(o.id)?"local":"registry"})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function nd(t){let e=Zt();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Qa(t.distribution.binary,e);if(s?.cmd){let r=Xi.resolve(E.agentInstallDir(t.id,e,n),s.cmd);if(await tu(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??td(t)??s.package,i=E.agentNpmInstallDir(t.id,e,n),o=Xi.join(i,"node_modules",".bin",r);if(await tu(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function tu(t){try{return await nu.access(t),!0}catch{return!1}}async function Un(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.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??td(t)??r.package,a=n.onInstallProgress;return{command:await Gl({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=Qa(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Zt()??"this platform"}.`);let i=n.onInstallProgress,o=await Yl({agentId:t.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(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as hy}from"child_process";import*as ro from"fs";import*as gu from"path";st();function so(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let d=n.indexOf(`
233
+ `);for(;d!==-1;){let c=n.slice(0,d).trim();if(n=n.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:0,error:{code:N.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}d=n.indexOf(`
234
234
  `)}}),t.on("end",()=>o()),t.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)+`
235
- `;await new Promise((c,l)=>{e.write(d,f=>{if(f){l(f);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Ks();ue();var hy=4096,Nn=class t{agentId;version;cwd;connection;child;exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??hy,this.killEscalationMs=e.killEscalationMs??gy,this.logger=e.logger,this.fileLog=yy(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
236
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=eo(n.stdout,n.stdin);this.connection=new Mt(s),n.stderr?.setEncoding("utf8"),n.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}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
235
+ `;await new Promise((c,l)=>{e.write(d,u=>{if(u){l(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Xs();me();var gy=4096,jn=class t{agentId;version;cwd;connection;child;exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??gy,this.killEscalationMs=e.killEscalationMs??yy,this.logger=e.logger,this.fileLog=wy(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
236
+ `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=so(n.stdout,n.stdin);this.connection=new Pt(s),n.stderr?.setEncoding("utf8"),n.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}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
237
237
  `),this.connection.fail(new Error(i))}),n.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
238
238
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${n.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=${n.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 n=this.stderrTail.trim();return n?`${e}
239
- stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=my(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(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()} ---
239
+ stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=hy(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(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()} ---
240
240
  `),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()} ---
241
- `),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 n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},gy=2e3;function yy(t){try{let e=P.agentLogFile(t);to.mkdirSync(pu.dirname(e),{recursive:!0});let n=to.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as gs from"fs/promises";import*as yo from"os";import*as Vr from"path";import{customAlphabet as Tw}from"nanoid";en();pd();ue();ls();import*as hn from"fs/promises";import{z as tn}from"zod";var tw=tn.object({version:tn.literal(1),agentId:tn.string(),upstreamSessionId:tn.string(),deletedAt:tn.string(),upstreamUpdatedAt:tn.string().optional(),cwd:tn.string().optional(),title:tn.string().optional(),reason:tn.enum(["user","expired"]).optional(),interactive:tn.boolean().optional()}),ao=class{async add(e){let n={version:1,...e};await It(P.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await hn.access(P.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=P.tombstoneFile(e,n),r=await Pt(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return tw.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await hn.unlink(P.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await hn.rmdir(P.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 n;try{n=await hn.readdir(P.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await hn.readdir(P.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Mu(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as ju from"fs/promises";nt();$t();io();var $u=`[older history truncated]
242
- `,rw=["file_path","path","command","pattern","query"];function _u(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){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 l=dw(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=cw(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(i(),s.push(iw(d))):c==="turn_complete"&&i()}return i(),uw(s.join(`
243
- `),n)}function iw(t){let e=ow(t),n=aw(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function ow(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function aw(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of rw){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${lw(r,200)}`)}return n}function dw(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function cw(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function lw(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function uw(t,e){if(t.length<=e)return t;let n=t.split(`
244
- `);for(;n.length>0;){let s=$u+n.join(`
245
- `);if(s.length<=e)return s;n.shift()}return $u}var fw=12e4;async function Fu(t){let e=t.timeoutMs??fw,n,s,r=!1;try{let i=(async()=>{n=Nn.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let o=await n.connection.request("initialize",{protocolVersion:tt,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ce}}),a=await n.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`);return}if(t.modelId){let g=mw(a);if(g.size===0||g.has(t.modelId))try{await n.connection.request("session/set_model",{sessionId:d,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];n.connection.onNotification("session/update",g=>{let h=pw(g);h.length>0&&c.push(h)});let l=_u(t.history,{maxChars:t.maxTranscriptChars}),f=l.length>0?`${l}
241
+ `),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 n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},yy=2e3;function wy(t){try{let e=E.agentLogFile(t);ro.mkdirSync(gu.dirname(e),{recursive:!0});let n=ro.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as vs from"fs/promises";import*as vo from"os";import*as ei from"path";import{customAlphabet as Ew}from"nanoid";nn();gd();me();ms();import*as wn from"fs/promises";import{z as sn}from"zod";var nw=sn.object({version:sn.literal(1),agentId:sn.string(),upstreamSessionId:sn.string(),deletedAt:sn.string(),upstreamUpdatedAt:sn.string().optional(),cwd:sn.string().optional(),title:sn.string().optional(),reason:sn.enum(["user","expired"]).optional(),interactive:sn.boolean().optional()}),uo=class{async add(e){let n={version:1,...e};await St(E.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await wn.access(E.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=E.tombstoneFile(e,n),r=await Et(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return nw.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await wn.unlink(E.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await wn.rmdir(E.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 n;try{n=await wn.readdir(E.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await wn.readdir(E.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Ou(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as zu from"fs/promises";st();Mt();co();var Fu=`[older history truncated]
242
+ `,iw=["file_path","path","command","pattern","query"];function Lu(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){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 l=cw(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=lw(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(i(),s.push(ow(d))):c==="turn_complete"&&i()}return i(),fw(s.join(`
243
+ `),n)}function ow(t){let e=aw(t),n=dw(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function aw(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function dw(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of iw){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${uw(r,200)}`)}return n}function cw(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function lw(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function uw(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function fw(t,e){if(t.length<=e)return t;let n=t.split(`
244
+ `);for(;n.length>0;){let s=Fu+n.join(`
245
+ `);if(s.length<=e)return s;n.shift()}return Fu}var pw=12e4;async function Nu(t){let e=t.timeoutMs??pw,n,s,r=!1;try{let i=(async()=>{n=jn.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let o=await n.connection.request("initialize",{protocolVersion:nt,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:pe}}),a=await n.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`);return}if(t.modelId){let g=hw(a);if(g.size===0||g.has(t.modelId))try{await n.connection.request("session/set_model",{sessionId:d,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];n.connection.onNotification("session/update",g=>{let h=mw(g);h.length>0&&c.push(h)});let l=Lu(t.history,{maxChars:t.maxTranscriptChars}),u=l.length>0?`${l}
246
246
 
247
- ${od}`:od;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:f}]});let u=c.join(""),p=Pu(u);return p||t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse as snapshot JSON (replyLen=${u.length} preview=${JSON.stringify(u.slice(0,200))})`),p})();return await new Promise((o,a)=>{s=setTimeout(()=>{r=!0,t.logger?.warn(`synopsis: agent ${t.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){t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${i.message}`);return}finally{s&&clearTimeout(s),n&&await n.kill().catch(()=>{})}}function pw(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function mw(t){let e=new Set;Ou(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Ou(e,n.availableModels),e}function Ou(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}gd();ue();var hw=2,lo=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??hw}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 n=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=n-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 n=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,n)}}async runOne(e){try{let n=await this.opts.store.read(e);if(!n){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=n.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??n.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 Bn(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=P.sessionDir(e);await ju.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let l=await Fu({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!l){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}l.title&&await this.opts.persistTitle(e,l.title);let f=gw(l.synopsis,s);f&&yw(f)?(await this.opts.persistSynopsis(e,f,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!l.title)} fields=${ww(f)}`)):l.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(n){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${n.message}`)}}};function gw(t,e){let n=Du(e),s=Nu(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function yw(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function ww(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}ue();import*as st from"fs/promises";function qu(t){return t==="summary"?"summary":"inline"}var yd=256;function Wu(t,e){return e!=="summary"?t:t.map(bw)}function bw(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(zu));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=wd(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...t,params:{...n,update:i}}}function vw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function zu(t){if(vw(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=wd(e.text)),typeof e.content=="string"?n.content=wd(e.content):e.content&&typeof e.content=="object"&&(n.content=zu(e.content)),n}function wd(t){if(typeof t=="string"&&t.length>yd){let e=t.length-yd;return`${t.slice(0,yd)}\u2026[+${e} chars omitted from summary export]`}return t}var Iw=2048;function Ju(t){let e=new Set,n=s=>{if(Ku(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function Ku(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Sw(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Id(t,e){if(!Sw(t))return t;let n=t.params,s=n.update,r=await bd(s,e);return{...t,params:{...n,update:r}}}async function bd(t,e){if(typeof t=="string"){if(t.length<=Iw)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await bd(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await bd(r,e);return n}return t}async function Vu(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await vd(n,e);return s===n?t:{...t,params:s}}async function vd(t,e){if(Ku(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await vd(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await vd(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var qr=/^[A-Za-z0-9_-]+$/,kw=1e3,uo=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??kw}async append(e,n){if(qr.test(e))return this.enqueue(e,async()=>{await st.mkdir(P.sessionDir(e),{recursive:!0});let s=await Id(n,i=>Wa(e,i)),r=JSON.stringify(s)+`
248
- `;await st.appendFile(P.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(qr.test(e))return this.enqueue(e,async()=>{await st.mkdir(P.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Id(i,o=>Wa(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
247
+ ${cd}`:cd;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let f=c.join(""),p=_u(f);return p||t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse as snapshot JSON (replyLen=${f.length} preview=${JSON.stringify(f.slice(0,200))})`),p})();return await new Promise((o,a)=>{s=setTimeout(()=>{r=!0,t.logger?.warn(`synopsis: agent ${t.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){t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${i.message}`);return}finally{s&&clearTimeout(s),n&&await n.kill().catch(()=>{})}}function mw(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function hw(t){let e=new Set;Bu(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Bu(e,n.availableModels),e}function Bu(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}bd();me();var gw=2,po=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??gw}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 n=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=n-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 n=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,n)}}async runOne(e){try{let n=await this.opts.store.read(e);if(!n){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=n.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??n.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 Un(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=E.sessionDir(e);await zu.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let l=await Nu({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!l){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}l.title&&await this.opts.persistTitle(e,l.title);let u=yw(l.synopsis,s);u&&ww(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!l.title)} fields=${bw(u)}`)):l.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(n){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${n.message}`)}}};function yw(t,e){let n=ju(e),s=Uu(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function ww(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function bw(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}me();import*as rt from"fs/promises";function Ju(t){return t==="summary"?"summary":"inline"}var vd=256;function Ku(t,e){return e!=="summary"?t:t.map(vw)}function vw(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(Vu));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=Id(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...t,params:{...n,update:i}}}function Iw(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Vu(t){if(Iw(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=Id(e.text)),typeof e.content=="string"?n.content=Id(e.content):e.content&&typeof e.content=="object"&&(n.content=Vu(e.content)),n}function Id(t){if(typeof t=="string"&&t.length>vd){let e=t.length-vd;return`${t.slice(0,vd)}\u2026[+${e} chars omitted from summary export]`}return t}var Sw=2048;function Yu(t){let e=new Set,n=s=>{if(Qu(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function Qu(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function kw(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function xd(t,e){if(!kw(t))return t;let n=t.params,s=n.update,r=await Sd(s,e);return{...t,params:{...n,update:r}}}async function Sd(t,e){if(typeof t=="string"){if(t.length<=Sw)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await Sd(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Sd(r,e);return n}return t}async function Gu(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await kd(n,e);return s===n?t:{...t,params:s}}async function kd(t,e){if(Qu(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await kd(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await kd(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Yr=/^[A-Za-z0-9_-]+$/,xw=1e3,mo=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??xw}async append(e,n){if(Yr.test(e))return this.enqueue(e,async()=>{await rt.mkdir(E.sessionDir(e),{recursive:!0});let s=await xd(n,i=>Ka(e,i)),r=JSON.stringify(s)+`
248
+ `;await rt.appendFile(E.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Yr.test(e))return this.enqueue(e,async()=>{await rt.mkdir(E.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await xd(i,o=>Ka(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
249
249
  `)+`
250
- `;await st.writeFile(P.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(qr.test(e))return this.enqueue(e,async()=>{let s;try{s=await st.readFile(P.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
251
- `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await st.writeFile(P.historyFile(e),i.join(`
250
+ `;await rt.writeFile(E.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Yr.test(e))return this.enqueue(e,async()=>{let s;try{s=await rt.readFile(E.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
251
+ `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await rt.writeFile(E.historyFile(e),i.join(`
252
252
  `)+`
253
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!qr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await st.readFile(P.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
254
- `)){if(f.length===0)continue;let u;try{u=JSON.parse(f)}catch{continue}if(!u||typeof u!="object"||Array.isArray(u))continue;let p=u;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 f=>{let u=d.get(f);if(u!==void 0)return u;let p=await Ki(e,f);return d.set(f,p),p},l=[];for(let f of a)l.push(await Vu(f,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(qr.test(e))return this.enqueue(e,async()=>{try{await st.unlink(P.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await jl(e);try{await st.rmdir(P.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};ue();Oe();po();hs();ro();nt();$t();td();var Gu=900*1e3,Ew="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",mo=Tw(Ew,16),go=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(i=>Nn.spawn(i)),this.store=s??new oo,this.tombstones=r.tombstones??new ao,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new uo({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 lo({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;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 Js(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress});if(e.transformChain&&e.transformChain.length>0){let r={...n.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_${mo()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}n.agentCapabilities=r}let s=new Xs({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.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:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=N.AlreadyAttached,i}return n}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 n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=N.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await Bn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r}),o;try{o=(await i.connection.request("initialize",{protocolVersion:tt,clientCapabilities:{},clientInfo:{name:"hydra",version:ce}})).agentCapabilities}catch(h){throw await i.kill().catch(()=>{}),h}let a;try{let h=_w(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
255
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=nf(a??{}),c=e.agentModes??Zu(tf(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(h=>h.id))}`);let l=await sf({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=Xu(a??{}),u=Zu(ef(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await rf({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new Xs({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:h=>this.bootstrapAgent({...h,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:u,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(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await sf({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await rf({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Xs({sessionId:e.hydraSessionId,cwd:n,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 gs.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Dt(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=N.AgentNotInstalled,p}let s=await Bn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:yo.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:tt,clientCapabilities:{},clientInfo:{name:"hydra",version:ce}})}catch(p){throw await r.kill().catch(()=>{}),p}if((i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=P.sessionsDir(),f=[],u=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){u+=1;continue}if(Pw(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!Mu(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let y=`${mn}${mo()}`,v=new Date().toISOString(),b=p.updatedAt??v,x={sessionId:y,lineageId:Ur(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(x.title=p.title);let C=fd(x);await this.store.write(C),f.push({version:1,...C})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s;for(let r=0;r<100;r+=1){let i={};s!==void 0&&(i.cursor=s);let o=await e.connection.request("session/list",i),a=Array.isArray(o.sessions)?o.sessions:[];for(let d of a){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let c={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(c.title=d.title),typeof d.updatedAt=="string"&&(c.updatedAt=d.updatedAt),n.push(c)}if(typeof o.nextCursor!="string"||o.nextCursor.length===0)break;s=o.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,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 n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=N.AgentNotInstalled,i}let s=await Bn(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let o=(await r.connection.request("initialize",{protocolVersion:tt,clientCapabilities:{},clientInfo:{name:"hydra",version:ce}})).agentCapabilities,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=Xu(a),l=ef(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let g=Ys(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,f,h)&&(c=f);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${h} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let y=l.map(v=>v.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let u=tf(a),p=nf(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),i}}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=ho({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(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:af(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.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 n=await this.store.read(e.sessionId),s=Mw(e,n);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,n){return Ki(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:$w(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Gs(r.update.prompt),o=id(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 n of this.sessions.values()){let s=n.agent.agentId,r=n.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(mn))return;let n=mn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=N.SessionNotFound,s}return n}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 list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=o=>e.includeNonInteractive?!0:o===!0;for(let o of this.sessions.values()){if(e.cwd&&o.cwd!==e.cwd)continue;s.add(o.sessionId);let a=await xd(o.sessionId),d=ho({interactive:o.interactive,...o.originatingClient?{originatingClient:o.originatingClient}:{}},a.hasContent);if(!r(d))continue;let c=a.mtime??new Date(o.updatedAt).toISOString();n.push({sessionId:o.sessionId,upstreamSessionId:o.upstreamSessionId,cwd:o.cwd,title:o.title,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,parentSessionId:o.parentSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,originatingClient:o.originatingClient,interactive:d,priority:o.priority,updatedAt:c,attachedClients:o.attachedCount,status:"live",busy:o.turnStartedAt!==void 0,awaitingInput:o.awaitingInput})}let i=await this.store.list().catch(()=>[]);for(let o of i){if(s.has(o.sessionId)||e.cwd&&o.cwd!==e.cwd)continue;let a=await xd(o.sessionId),d=ho(o,a.hasContent);if(!r(d))continue;let c=a.mtime??o.updatedAt;n.push({sessionId:o.sessionId,upstreamSessionId:o.upstreamSessionId,cwd:o.cwd,title:o.title,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage?{...o.currentUsage,costAmount:(o.currentUsage.cumulativeCost??0)+(o.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,parentSessionId:o.parentSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,originatingClient:o.originatingClient,interactive:d,priority:o.priority,updatedAt:c,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return n.sort((o,a)=>o.updatedAt<a.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Ur(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await of(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of Ju(o)){let l=await Hl(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=N.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:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${mn}${mo()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=N.SessionNotFound,g}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=N.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,d;if(n.forkAt!==void 0){if(a=rd(o,n.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw g.code=N.InvalidParams,g}d=n.forkAt}else{let g=Ow(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),l=await of(e),f={...s,lineageId:Ur(),agentId:r,interactive:!1,...n.title!==void 0?{title:n.title}:{},...i?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},u=Kr({record:f,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:ce,machine:yo.hostname()}),p=`${mn}${mo()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.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 Ul(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await gs.utimes(P.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ms(P.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 n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await xd(e),r=ho(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.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,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let r={...s,updatedAt:new Date().toISOString()};n===void 0?delete r.priority:r.priority=n,await this.store.write(r)}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,title:n,updatedAt:new Date().toISOString()})})}async persistSynopsis(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,synopsis:n,summarizedThroughEntry:s,updatedAt:new Date().toISOString()})})}async persistAgentChange(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,agentId:n,upstreamSessionId:s,updatedAt:new Date().toISOString()})})}async persistSnapshot(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},...n.currentMode!==void 0?{currentMode:n.currentMode}:{},...n.currentUsage!==void 0?{currentUsage:n.currentUsage}:{},...n.agentCommands!==void 0?{agentCommands:n.agentCommands}:{},...n.agentModes!==void 0?{agentModes:n.agentModes}:{},...n.agentModels!==void 0?{agentModels:n.agentModels}:{},...n.interactive!==void 0?{interactive:n.interactive}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},updatedAt:new Date().toISOString()})})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).then(n,n),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(n=>n.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 n of e){let s=await Iu(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Gu),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Gu/1e3}s)`),await Dr(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Dr(n.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${d.message}`)}}}};function Pw(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Vr.resolve(t),s=Vr.resolve(e);return n===s||n.startsWith(s+Vr.sep)}function Mw(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return fd({sessionId:t.sessionId,lineageId:e?.lineageId??Ur(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:af(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function af(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function $w(t){return t?{...t}:void 0}function _w(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Xu(t){let e=qe(t.currentModelId)??qe(t.currentModel)??qe(t.modelId)??qe(t.model);if(e)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=qe(n.currentModelId)??qe(n.currentModel);if(i)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=qe(o.modelId)??qe(o.model)??qe(o.currentModelId);if(a)return a}}let r=wo(t,"model");if(r){let i=qe(r.currentValue);if(i)return i}}function qe(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function wo(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Zu(t){return t.length>0?t:void 0}function ef(t){let e=Dn(t.availableModels);if(e.length>0)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=Dn(n.availableModels);if(i.length>0)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=Dn(o.availableModels);if(a.length>0)return a}}let r=wo(t,"model");if(r){let i=Dn(r.options);if(i.length>0)return i}return[]}function tf(t){let e=fs(t.availableModes);if(e.length>0)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=fs(n.availableModes);if(i.length>0)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=fs(o.availableModes);if(a.length>0)return a}}let r=wo(t,"mode");if(r){let i=fs(r.options);if(i.length>0)return i}return[]}function nf(t){let e=qe(t.currentModeId)??qe(t.currentMode)??qe(t.modeId)??qe(t.mode);if(e)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=qe(n.currentModeId)??qe(n.currentMode);if(i)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=qe(o.currentModeId)??qe(o.currentMode)??qe(o.modeId);if(a)return a}}let r=wo(t,"mode");if(r){let i=qe(r.currentValue);if(i)return i}}async function sf(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;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:n,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 rf(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;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:n,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 Ow(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function of(t){try{let e=await gs.readFile(P.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
256
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function xd(t){try{let e=await gs.stat(P.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function ho(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===ps?!1:e?!0:void 0}import{spawn as Fw}from"child_process";import*as tr from"fs";import*as Hn from"fs/promises";import*as df from"path";var bo=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,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;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 ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Lw=1e3,Bw=6e4,Ad=3e3,er=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Lw,this.restartCapMs=r.restartCapMs??Bw;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Hn.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 n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.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()},Ad);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw Yr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Yr(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw Yr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Yr(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 n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw Yr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},Ad);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,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 bo(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Hn.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=df.join(this.adapter.paths.dir(),n),r;try{let i=await Hn.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Cd(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ad;for(;Date.now()<i&&Cd(r);)await new Promise(o=>setTimeout(o,50));if(Cd(r))try{process.kill(r,"SIGKILL")}catch{}}await Hn.unlink(s).catch(()=>{})}}spawn(e,n){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=tr.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
253
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Yr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await rt.readFile(E.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
254
+ `)){if(u.length===0)continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let p=f;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 f=d.get(u);if(f!==void 0)return f;let p=await Qi(e,u);return d.set(u,p),p},l=[];for(let u of a)l.push(await Gu(u,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Yr.test(e))return this.enqueue(e,async()=>{try{await rt.unlink(E.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await zl(e);try{await rt.rmdir(E.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};me();Oe();go();bs();ao();st();Mt();rd();var ef=900*1e3,Pw="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",yo=Ew(Pw,16),bo=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(i=>jn.spawn(i)),this.store=s??new lo,this.tombstones=r.tombstones??new uo,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new mo({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 po({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;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 Gs(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress});if(e.transformChain&&e.transformChain.length>0){let r={...n.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_${yo()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}n.agentCapabilities=r}let s=new sr({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.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:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=N.AlreadyAttached,i}return n}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 n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=N.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await Un(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r}),o;try{o=(await i.connection.request("initialize",{protocolVersion:nt,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}})).agentCapabilities}catch(h){throw await i.kill().catch(()=>{}),h}let a;try{let h=Ow(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
255
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=of(a??{}),c=e.agentModes??nf(rf(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(h=>h.id))}`);let l=await af({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=tf(a??{}),f=nf(sf(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await df({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new sr({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:h=>this.bootstrapAgent({...h,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:f,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await af({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await df({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new sr({sessionId:e.hydraSessionId,cwd:n,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 vs.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Ut(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=N.AgentNotInstalled,p}let s=await Un(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:vo.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:nt,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}})}catch(p){throw await r.kill().catch(()=>{}),p}if((i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=E.sessionsDir(),u=[],f=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){f+=1;continue}if(Mw(p.cwd,l)){f+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!Ou(h,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let y=`${yn}${yo()}`,I=new Date().toISOString(),b=p.updatedAt??I,x={sessionId:y,lineageId:Kr(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(x.title=p.title);let M=hd(x);await this.store.write(M),u.push({version:1,...M})}return{synced:u,skipped:f}}async collectAgentSessions(e){let n=[],s;for(let r=0;r<100;r+=1){let i={};s!==void 0&&(i.cursor=s);let o=await e.connection.request("session/list",i),a=Array.isArray(o.sessions)?o.sessions:[];for(let d of a){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let c={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(c.title=d.title),typeof d.updatedAt=="string"&&(c.updatedAt=d.updatedAt),n.push(c)}if(typeof o.nextCursor!="string"||o.nextCursor.length===0)break;s=o.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,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 n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=N.AgentNotInstalled,i}let s=await Un(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let o=(await r.connection.request("initialize",{protocolVersion:nt,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}})).agentCapabilities,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=tf(a),l=sf(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=er(u,l),h=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,h)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${h} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let y=l.map(I=>I.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let f=rf(a),p=of(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),i}}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=wo({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(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:lf(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.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 n=await this.store.read(e.sessionId),s=$w(e,n);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,n){return Qi(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:_w(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=nr(r.update.prompt),o=dd(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 n of this.sessions.values()){let s=n.agent.agentId,r=n.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(yn))return;let n=yn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=N.SessionNotFound,s}return n}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 list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=o=>e.includeNonInteractive?!0:o===!0;for(let o of this.sessions.values()){if(e.cwd&&o.cwd!==e.cwd)continue;s.add(o.sessionId);let a=await Rd(o.sessionId),d=wo({interactive:o.interactive,...o.originatingClient?{originatingClient:o.originatingClient}:{}},a.hasContent);if(!r(d))continue;let c=a.mtime??new Date(o.updatedAt).toISOString();n.push({sessionId:o.sessionId,upstreamSessionId:o.upstreamSessionId,cwd:o.cwd,title:o.title,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,parentSessionId:o.parentSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,originatingClient:o.originatingClient,interactive:d,priority:o.priority,updatedAt:c,attachedClients:o.attachedCount,status:"live",busy:o.turnStartedAt!==void 0,awaitingInput:o.awaitingInput})}let i=await this.store.list().catch(()=>[]);for(let o of i){if(s.has(o.sessionId)||e.cwd&&o.cwd!==e.cwd)continue;let a=await Rd(o.sessionId),d=wo(o,a.hasContent);if(!r(d))continue;let c=a.mtime??o.updatedAt;n.push({sessionId:o.sessionId,upstreamSessionId:o.upstreamSessionId,cwd:o.cwd,title:o.title,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage?{...o.currentUsage,costAmount:(o.currentUsage.cumulativeCost??0)+(o.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,parentSessionId:o.parentSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,originatingClient:o.originatingClient,interactive:d,priority:o.priority,updatedAt:c,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return n.sort((o,a)=>o.updatedAt<a.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Kr(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await cf(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of Yu(o)){let l=await ql(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=N.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:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${yn}${yo()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=N.SessionNotFound,g}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=N.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,d;if(n.forkAt!==void 0){if(a=ad(o,n.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw g.code=N.InvalidParams,g}d=n.forkAt}else{let g=Fw(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),l=await cf(e),u={...s,lineageId:Kr(),agentId:r,interactive:!1,...n.title!==void 0?{title:n.title}:{},...i?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},f=Zr({record:u,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:pe,machine:vo.hostname()}),p=`${yn}${yo()}`;return await this.writeImportedRecord({sessionId:p,bundle:f,cwd:n.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 Wl(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await vs.utimes(E.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ws(E.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 n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await Rd(e),r=wo(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.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,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let r={...s,updatedAt:new Date().toISOString()};n===void 0?delete r.priority:r.priority=n,await this.store.write(r)}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,title:n,updatedAt:new Date().toISOString()})})}async persistSynopsis(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,synopsis:n,summarizedThroughEntry:s,updatedAt:new Date().toISOString()})})}async persistAgentChange(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,agentId:n,upstreamSessionId:s,updatedAt:new Date().toISOString()})})}async persistSnapshot(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},...n.currentMode!==void 0?{currentMode:n.currentMode}:{},...n.currentUsage!==void 0?{currentUsage:n.currentUsage}:{},...n.agentCommands!==void 0?{agentCommands:n.agentCommands}:{},...n.agentModes!==void 0?{agentModes:n.agentModes}:{},...n.agentModels!==void 0?{agentModels:n.agentModels}:{},...n.interactive!==void 0?{interactive:n.interactive}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},updatedAt:new Date().toISOString()})})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).then(n,n),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(n=>n.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 n of e){let s=await xu(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<ef),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${ef/1e3}s)`),await zr(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await zr(n.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${d.message}`)}}}};function Mw(t,e){if(typeof t!="string"||t.length===0)return!1;let n=ei.resolve(t),s=ei.resolve(e);return n===s||n.startsWith(s+ei.sep)}function $w(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),c=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return hd({sessionId:t.sessionId,lineageId:e?.lineageId??Kr(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:lf(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function lf(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function _w(t){return t?{...t}:void 0}function Ow(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function tf(t){let e=We(t.currentModelId)??We(t.currentModel)??We(t.modelId)??We(t.model);if(e)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=We(n.currentModelId)??We(n.currentModel);if(i)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=We(o.modelId)??We(o.model)??We(o.currentModelId);if(a)return a}}let r=Io(t,"model");if(r){let i=We(r.currentValue);if(i)return i}}function We(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Io(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function nf(t){return t.length>0?t:void 0}function sf(t){let e=qn(t.availableModels);if(e.length>0)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=qn(n.availableModels);if(i.length>0)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=qn(o.availableModels);if(a.length>0)return a}}let r=Io(t,"model");if(r){let i=qn(r.options);if(i.length>0)return i}return[]}function rf(t){let e=gs(t.availableModes);if(e.length>0)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=gs(n.availableModes);if(i.length>0)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=gs(o.availableModes);if(a.length>0)return a}}let r=Io(t,"mode");if(r){let i=gs(r.options);if(i.length>0)return i}return[]}function of(t){let e=We(t.currentModeId)??We(t.currentMode)??We(t.modeId)??We(t.mode);if(e)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=We(n.currentModeId)??We(n.currentMode);if(i)return i}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,o]of Object.entries(s))if(i!=="hydra-acp"&&o&&typeof o=="object"&&!Array.isArray(o)){let a=We(o.currentModeId)??We(o.currentMode)??We(o.modeId);if(a)return a}}let r=Io(t,"mode");if(r){let i=We(r.currentValue);if(i)return i}}async function af(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;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:n,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 df(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;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:n,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 Fw(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function cf(t){try{let e=await vs.readFile(E.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
256
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function Rd(t){try{let e=await vs.stat(E.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function wo(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===ys?!1:e?!0:void 0}import{spawn as Lw}from"child_process";import*as or from"fs";import*as Wn from"fs/promises";import*as uf from"path";var So=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,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;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 ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Bw=1e3,Nw=6e4,Td=3e3,ir=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Bw,this.restartCapMs=r.restartCapMs??Nw;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Wn.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 n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.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()},Td);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw ti(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw ti(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw ti(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw ti(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 n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw ti(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},Td);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,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 So(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Wn.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=uf.join(this.adapter.paths.dir(),n),r;try{let i=await Wn.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Ed(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Td;for(;Date.now()<i&&Ed(r);)await new Promise(o=>setTimeout(o,50));if(Ed(r))try{process.kill(r,"SIGKILL")}catch{}}await Wn.unlink(s).catch(()=>{})}}spawn(e,n){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=or.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
257
257
  `);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,...l]=i;if(c===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
258
- `),o.end();return}let f=[...l,...r.args],u;try{u=Fw(c,f,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
259
- `),o.end(),this.scheduleRestart(e,n);return}if(u.stdout&&u.stdout.pipe(o,{end:!1}),u.stderr&&u.stderr.pipe(o,{end:!1}),typeof u.pid=="number")try{tr.writeFileSync(this.adapter.paths.pidFile(r.name),`${u.pid}
258
+ `),o.end();return}let u=[...l,...r.args],f;try{f=Lw(c,u,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
259
+ `),o.end(),this.scheduleRestart(e,n);return}if(f.stdout&&f.stdout.pipe(o,{end:!1}),f.stderr&&f.stderr.pipe(o,{end:!1}),typeof f.pid=="number")try{or.writeFileSync(this.adapter.paths.pidFile(r.name),`${f.pid}
260
260
  `,{encoding:"utf8",mode:384})}catch(p){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${p.message}
261
- `)}e.child=u,e.logStream=o,e.pid=typeof u.pid=="number"?u.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,u.on("error",p=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
262
- `)}),u.on("exit",(p,g)=>{try{tr.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"null"}
263
- `),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 h=e.exitWaiters.splice(0);for(let v of h)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let y=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof y=="object"){e.failureReason=y.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${y.tripped}
264
- `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Cd(t){try{return process.kill(t,0),!0}catch{return!1}}function Yr(t,e){return t.code=e,t}ue();var Nw={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:P.extensionsDir,logFile:P.extensionLogFile,pidFile:P.extensionPidFile}},vo=class extends er{constructor(e,n,s={}){super(e,Nw,n,s)}};ue();var Dw={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:P.transformersDir,logFile:P.transformerLogFile,pidFile:P.transformerPidFile}},Io=class extends er{connected=new Map;constructor(e,n,s={}){super(e,Dw,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var So=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,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[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};ue();ue();import*as Gr from"fs/promises";import*as ko from"path";var Qr=t=>{process.stderr.write(t+`
265
- `)};function Rd(t){Qr=t??(e=>process.stderr.write(e+`
266
- `))}async function cf(t,e){let n=Gt();if(!n)return;let s=await t.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=ko.join(P.agentsDir(),n),a;try{a=await Gr.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;Qr(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let f=i.get(c)??new Set,u=ko.join(o,c),p;try{p=await Gr.readdir(u,{withFileTypes:!0})}catch(g){Qr(`hydra-acp: prune: failed to read ${u}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let h=g.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let y=ko.join(u,h);try{await Gr.rm(y,{recursive:!0,force:!0}),Qr(`hydra-acp: pruned stale ${c} ${h} (${y})`)}catch(v){Qr(`hydra-acp: prune: failed to remove ${y}: ${v.message}`)}}}}function lf(t){let e,n=!1,s=0,r=(a,d)=>{t.logger&&t.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await Za(f)==="yes"&&a.push(f.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Td(t){let e=t.maxDeletions??200,n=(p,g)=>{t.logger&&t.logger[p](`session-gc: ${g}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,n("warn",`delete ${p} failed: ${g.message}`)}let f=o.length-a.length;if(t.verbose||c>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${c} ${p} session(s) older than ${Hw(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:c,failed:l,deferred:f};return d!==void 0&&(u.oldestLastUsedMs=d),u}function uf(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Td({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function Hw(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}$t();xo();ue();ls();import*as mf from"path";import{createHash as jw,randomBytes as qw,timingSafeEqual as Ww}from"crypto";var hf="hydra_session_",zw=3600*24*30,ff=12,Jw=32,Kw=50;function Vw(){return mf.join(P.home(),"session-tokens.json")}function pf(t){return jw("sha256").update(t).digest("hex")}function gf(t){return qw(t).toString("hex")}function Yw(){return gf(ff).slice(0,ff*2)}function Qw(){return`${hf}${gf(Jw)}`}var Ao=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=Vw(),s=await Pt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(Gw));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=Qw(),s=pf(n),r=Yw(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:zw,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:n,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(hf))return;let n=pf(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!Ww(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),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:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}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(()=>{})},Kw))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>It(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 Gw(t){if(!t||typeof t!="object")return!1;let e=t;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")}ft();var yf="Bearer ",Co=class{constructor(e){this.token=e}token;async validate(e){return Xw(e,this.token)?"service":void 0}},Ro=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},To=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function wf(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(yf)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(yf.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function bf(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Eo=class{tokens=new Map;mint(e,n){let s=Ls();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function Xw(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var Po=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}};Oe();hs();_o();import*as ei from"os";import*as _f from"path";Md();nt();$t();Nr();Un();function _b(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let l of s){let f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>Ob(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function Ob(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Rf(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:Rf(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Rf(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Fb(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Lb=5,Bb=200,Tf=30;async function Mf(t,e,n={}){let s=_b(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Lb,i=n.maxSessions??Bb,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),d=o?a.filter(f=>o.has(f.sessionId)):a,c=[],l=!1;for(let f of d){if(c.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Nb(u,s,r);if(p.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(g.title=f.title),c.push(g)}return{query:e,truncated:l,results:c}}function Nb(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Db(t,o,i,n-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 Db(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let d=Hb(a).filter(c=>Fb(n,c.kind));for(let c of d){let l=c.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(i+=u,o.length<s){let p=l.indexOf(r),g={kind:c.kind,text:zb(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 Hb(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Fo(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?mt(s.text):Fo(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(qb(s))return[];let i=Fo(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Wb(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Ub(s);default:return[]}}function Ub(t){let e=Ef(t,"name"),n=Ef(t,"title"),s=[];if(n!==void 0){let a=Ce(n);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==n){let a=Ce(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Pf(r);if(a.length>0){let d={kind:"tool-input",text:Ce(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Pf(i);if(a.length>0){let d={kind:"tool-input",text:Ce(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=jb(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function jb(t){let e=t.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=Ce(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ce(s);if(r.length>0)return r}}return null}function qb(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function Fo(t){if(typeof t=="string")return mt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?mt(e.text):""}function Wb(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Fo(n);s.length>0&&e.push(s)}return e.join("")}function Ef(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Pf(t){try{return JSON.stringify(t)}catch{return""}}function zb(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Tf),d=Math.min(s.length,o+i.length+Tf),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}function $f(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!pn(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Of(t,e,n){t.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})}}),t.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 Mf(e,o,{sessionIds:a})}),t.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Dt(i.cwd??n.cwd),a=i.agentId??n.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})}}),t.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 Td({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),t.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()}),t.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=l=>_f.join(ei.tmpdir(),`hydra-acp-stdin-${l}.log`));try{return a.openStream(c)}catch(l){return r.code(409).send({error:l.message}),r}}),t.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:"",l=d.eof===!0;try{return a.streamWrite(c,l)}catch(f){return r.code(409).send({error:f.message}),r}}),t.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,l;if(c===null||c===0)l=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)l=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,l)){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()}),t.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()}),t.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":qu(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let l=Kr({record:c.record,history:d==="summary"?Wu(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:ce,machine:ei.hostname(),hydraHost:$f(n)}),f=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${f}.hydra"`),r.code(200).send(l)}),t.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",l=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(u=>u.trim()).filter(u=>u.length>0)):void 0,f=sr(a.history);l&&(f=f.filter(u=>l.has(u.path))),c&&(f=f.map(u=>({...u,hunks:rr(u.hunks)}))),r.code(200).send(f)}),t.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)}),t.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=Kr({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:ce,machine:ei.hostname(),hydraHost:$f(n)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Oo(d))}),t.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=Dt(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 l=c;if(l.code===N.SessionNotFound){r.code(404).send({error:l.message});return}if(l.code===N.InvalidParams||l.code===N.AgentNotInstalled){r.code(400).send({error:l.message});return}r.code(500).send({error:l.message})}}),t.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=Ut(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===N.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),t.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),l,f,u=!1,p=[];if(c)a&&(f=c.onBroadcast(h=>{r.raw.writableEnded||(u?r.raw.write(JSON.stringify(h)+`
261
+ `)}e.child=f,e.logStream=o,e.pid=typeof f.pid=="number"?f.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,f.on("error",p=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
262
+ `)}),f.on("exit",(p,g)=>{try{or.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"null"}
263
+ `),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 h=e.exitWaiters.splice(0);for(let I of h)I();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let y=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof y=="object"){e.failureReason=y.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${y.tripped}
264
+ `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Ed(t){try{return process.kill(t,0),!0}catch{return!1}}function ti(t,e){return t.code=e,t}me();var Dw={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:E.extensionsDir,logFile:E.extensionLogFile,pidFile:E.extensionPidFile}},ko=class extends ir{constructor(e,n,s={}){super(e,Dw,n,s)}};me();var Hw={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:E.transformersDir,logFile:E.transformerLogFile,pidFile:E.transformerPidFile}},xo=class extends ir{connected=new Map;constructor(e,n,s={}){super(e,Hw,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Ao=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,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[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};me();me();import*as si from"fs/promises";import*as Co from"path";var ni=t=>{process.stderr.write(t+`
265
+ `)};function Pd(t){ni=t??(e=>process.stderr.write(e+`
266
+ `))}async function ff(t,e){let n=Zt();if(!n)return;let s=await t.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Co.join(E.agentsDir(),n),a;try{a=await si.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;ni(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=Co.join(o,c),p;try{p=await si.readdir(f,{withFileTypes:!0})}catch(g){ni(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let h=g.name;if(h===l||u.has(h)||h.includes(".partial-"))continue;let y=Co.join(f,h);try{await si.rm(y,{recursive:!0,force:!0}),ni(`hydra-acp: pruned stale ${c} ${h} (${y})`)}catch(I){ni(`hydra-acp: prune: failed to remove ${y}: ${I.message}`)}}}}function pf(t){let e,n=!1,s=0,r=(a,d)=>{t.logger&&t.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let u of l.agents)await nd(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Md(t){let e=t.maxDeletions??200,n=(p,g)=>{t.logger&&t.logger[p](`session-gc: ${g}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,n("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(t.verbose||c>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${c} ${p} session(s) older than ${Uw(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function mf(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Md({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function Uw(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}Mt();Ro();me();ms();import*as yf from"path";import{createHash as qw,randomBytes as Ww,timingSafeEqual as zw}from"crypto";var wf="hydra_session_",Jw=3600*24*30,hf=12,Kw=32,Vw=50;function Yw(){return yf.join(E.home(),"session-tokens.json")}function gf(t){return qw("sha256").update(t).digest("hex")}function bf(t){return Ww(t).toString("hex")}function Qw(){return bf(hf).slice(0,hf*2)}function Gw(){return`${wf}${bf(Kw)}`}var To=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=Yw(),s=await Et(n);s&&Array.isArray(s.records)&&(e=s.records.filter(Xw));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=Gw(),s=gf(n),r=Qw(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Jw,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:n,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(wf))return;let n=gf(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!zw(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),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:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}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(()=>{})},Vw))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>St(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 Xw(t){if(!t||typeof t!="object")return!1;let e=t;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")}mt();var vf="Bearer ",Eo=class{constructor(e){this.token=e}token;async validate(e){return Zw(e,this.token)?"service":void 0}},Po=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Mo=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function If(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(vf)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(vf.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Sf(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var $o=class{tokens=new Map;mint(e,n){let s=Us();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function Zw(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var _o=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}};Oe();bs();Lo();import*as oi from"os";import*as Lf from"path";Od();st();Mt();Wr();zn();function Ob(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>Fb(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function Fb(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Pf(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:Pf(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Pf(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Lb(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Bb=5,Nb=200,Mf=30;async function Of(t,e,n={}){let s=Ob(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Bb,i=n.maxSessions??Nb,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],l=!1;for(let u of d){if(c.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=Db(f,s,r);if(p.snippets.length===0)continue;let g={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(g.title=u.title),c.push(g)}return{query:e,truncated:l,results:c}}function Db(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Hb(t,o,i,n-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 Hb(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let d=Ub(a).filter(c=>Lb(n,c.kind));for(let c of d){let l=c.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),g={kind:c.kind,text:Jb(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 Ub(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=No(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?gt(s.text):No(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Wb(s))return[];let i=No(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=zb(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return jb(s);default:return[]}}function jb(t){let e=$f(t,"name"),n=$f(t,"title"),s=[];if(n!==void 0){let a=Ae(n);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==n){let a=Ae(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=_f(r);if(a.length>0){let d={kind:"tool-input",text:Ae(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=_f(i);if(a.length>0){let d={kind:"tool-input",text:Ae(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=qb(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function qb(t){let e=t.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=Ae(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ae(s);if(r.length>0)return r}}return null}function Wb(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function No(t){if(typeof t=="string")return gt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?gt(e.text):""}function zb(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=No(n);s.length>0&&e.push(s)}return e.join("")}function $f(t,e){let n=t[e];return typeof n=="string"?n:void 0}function _f(t){try{return JSON.stringify(t)}catch{return""}}function Jb(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Mf),d=Math.min(s.length,o+i.length+Mf),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}function Ff(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!gn(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Bf(t,e,n){t.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})}}),t.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 Of(e,o,{sessionIds:a})}),t.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Ut(i.cwd??n.cwd),a=i.agentId??n.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})}}),t.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 Md({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),t.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()}),t.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=l=>Lf.join(oi.tmpdir(),`hydra-acp-stdin-${l}.log`));try{return a.openStream(c)}catch(l){return r.code(409).send({error:l.message}),r}}),t.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:"",l=d.eof===!0;try{return a.streamWrite(c,l)}catch(u){return r.code(409).send({error:u.message}),r}}),t.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,l;if(c===null||c===0)l=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)l=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,l)){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()}),t.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()}),t.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":Ju(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let l=Zr({record:c.record,history:d==="summary"?Ku(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:pe,machine:oi.hostname(),hydraHost:Ff(n)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(l)}),t.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",l=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(f=>f.trim()).filter(f=>f.length>0)):void 0,u=dr(a.history);l&&(u=u.filter(f=>l.has(f.path))),c&&(u=u.map(f=>({...f,hunks:cr(f.hunks)}))),r.code(200).send(u)}),t.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)}),t.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=Zr({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:pe,machine:oi.hostname(),hydraHost:Ff(n)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Bo(d))}),t.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=Ut(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 l=c;if(l.code===N.SessionNotFound){r.code(404).send({error:l.message});return}if(l.code===N.InvalidParams||l.code===N.AgentNotInstalled){r.code(400).send({error:l.message});return}r.code(500).send({error:l.message})}}),t.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=qt(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===N.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),t.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),l,u,f=!1,p=[];if(c)a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(f?r.raw.write(JSON.stringify(h)+`
267
267
  `):p.push(h))})),l=await c.getHistorySnapshot();else{let h=await e.getHistory(d);if(h===void 0)return r.code(404).send({error:"session not found"}),r;l=h}r.raw.setHeader("Content-Type","application/x-ndjson"),r.raw.setHeader("Cache-Control","no-cache"),r.raw.statusCode=200;let g=new Set;for(let h of l??[]){r.raw.write(JSON.stringify(h)+`
268
- `);let y=h;typeof y.recordedAt=="number"&&g.add(String(y.recordedAt))}for(let h of p){let y=h,v=typeof y.recordedAt=="number"?String(y.recordedAt):"";v&&g.has(v)||r.raw.write(JSON.stringify(h)+`
269
- `)}return u=!0,f?(s.raw.on("close",()=>{f?.(),r.raw.writableEnded||r.raw.end()}),r):(r.raw.end(),r)})}nt();function Ff(t,e,n,s={}){t.get("/v1/agents",async()=>Js(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.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 Bn(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})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await n.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===N.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function Lf(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var Jb=/^[A-Za-z0-9._-]+$/;function Bf(t,e){t.get("/v1/extensions",async()=>({extensions:e.list()})),t.get("/v1/extensions/:name",async(n,s)=>{let r=n.params.name,i=e.get(r);if(!i){s.code(404).send({error:`unknown extension: ${r}`});return}return i}),t.post("/v1/extensions",async(n,s)=>{let r=n.body??{},i=Kb(r);if("error"in i){s.code(400).send({error:i.error});return}try{let o=e.register(i.config);s.code(201).send(o)}catch(o){ti(s,o)}}),t.delete("/v1/extensions/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(i){ti(s,i)}}),t.post("/v1/extensions/:name/start",async(n,s)=>{let r=n.params.name;try{let i=await e.startByName(r);s.code(200).send(i)}catch(i){ti(s,i)}}),t.post("/v1/extensions/:name/stop",async(n,s)=>{let r=n.params.name;try{let i=await e.stopByName(r);s.code(200).send(i)}catch(i){ti(s,i)}}),t.post("/v1/extensions/:name/restart",async(n,s)=>{let r=n.params.name;try{let i=await e.restartByName(r);s.code(200).send(i)}catch(i){ti(s,i)}})}function ti(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function Kb(t){let e=t.name;if(typeof e!="string"||!Jb.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.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=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}var Vb=/^[A-Za-z0-9._-]+$/;function Nf(t,e){t.get("/v1/transformers",async()=>({transformers:e.list()})),t.get("/v1/transformers/:name",async(n,s)=>{let r=n.params.name,i=e.get(r);if(!i){s.code(404).send({error:`unknown transformer: ${r}`});return}return i}),t.post("/v1/transformers",async(n,s)=>{let r=n.body??{},i=Yb(r);if("error"in i){s.code(400).send({error:i.error});return}try{let o=e.register(i.config);s.code(201).send(o)}catch(o){ni(s,o)}}),t.delete("/v1/transformers/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(i){ni(s,i)}}),t.post("/v1/transformers/:name/start",async(n,s)=>{let r=n.params.name;try{let i=await e.startByName(r);s.code(200).send(i)}catch(i){ni(s,i)}}),t.post("/v1/transformers/:name/stop",async(n,s)=>{let r=n.params.name;try{let i=await e.stopByName(r);s.code(200).send(i)}catch(i){ni(s,i)}}),t.post("/v1/transformers/:name/restart",async(n,s)=>{let r=n.params.name;try{let i=await e.restartByName(r);s.code(200).send(i)}catch(i){ni(s,i)}})}function ni(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function Yb(t){let e=t.name;if(typeof e!="string"||!Vb.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.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=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function Df(t,e){t.get("/v1/config",async()=>e)}import{z as ir}from"zod";ue();import*as jn from"fs/promises";import*as qf from"path";import{randomBytes as Qb,scrypt as Gb,timingSafeEqual as Xb}from"crypto";import{promisify as Zb}from"util";var Wf=Zb(Gb);function $d(){return qf.join(P.home(),"password-hash")}var Hf=32768,Uf=8,jf=1,ev=64,tv=16,zf=128*1024*1024;async function Jf(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=Qb(tv),n=await Wf(t,e,ev,{N:Hf,r:Uf,p:jf,maxmem:zf}),s=`scrypt$${Hf}$${Uf}$${jf}$${e.toString("hex")}$${n.toString("hex")}
270
- `;await jn.mkdir(P.home(),{recursive:!0}),await jn.writeFile($d(),s,{encoding:"utf8",mode:384})}async function Lo(){try{return(await jn.readFile($d(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bo(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await jn.readFile($d(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let d=await Wf(t,o,a.length,{N:s,r,p:i,maxmem:zf});return d.length!==a.length?!1:Xb(d,a)}var nv=ir.object({password:ir.string().min(1),label:ir.string().min(1).max(256).optional(),ttlSec:ir.number().int().positive().optional()}),sv=ir.object({id:ir.string().optional()}).optional();function Kf(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=rv(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=nv.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Lo())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Bo(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})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=sv.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.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})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function rv(t){return t.ip||"unknown"}Ks();si();ro();nt();import{nanoid as Bd}from"nanoid";$t();import{randomBytes as Yf}from"crypto";function Qf(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=bf({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=qn(n),a=new Mt(o),d={clientId:`hydra_client_${Bd(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly){let g=new Error(`${u} not permitted on a read-only attachment`);throw g.code=N.PermissionDenied,g}};if(a.onRequest("initialize",async f=>{let u=eu.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),dv()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},g=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.verb!="string")return;let v={verb:y.verb};return typeof y.argsHint=="string"&&(v.argsHint=y.argsHint),typeof y.description=="string"&&(v.description=y.description),v}).filter(h=>h!==void 0):[];return f.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},g=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let v=y;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let b={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(b.outputSchema=v.outputSchema),b}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,g,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.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 h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,g=typeof u.method=="string"?u.method:void 0,h=u.envelope,y=u.route;if(!p||!g)throw Object.assign(new Error("emit_message requires sessionId and method"),{code:-32602});let v=e.manager.get(p);if(!v)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});let b=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(b)return v.dischargeClaim(b,h),{ok:!0};if(y==="chain")return{ok:!0,response:await v.emitToChain(i.name,g,h)};if(y==="daemon")return{ok:!0,response:await v.emitToChain(i.name,g,h)};throw Object.assign(new Error(`unsupported route: ${JSON.stringify(y)}`),{code:-32602})}),a.onRequest("hydra-acp/session/request_permission",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw Object.assign(new Error("hydra-acp/session/request_permission requires sessionId"),{code:-32602});let g=e.manager.get(p);if(!g)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return g.requestPermissionFromClients(u)}),a.onRequest("hydra-acp/transformer/attach",async f=>ov(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0,y=u._meta&&typeof u._meta=="object"?u._meta:void 0,v=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,b=v&&typeof v.title=="string"?v.title:void 0;if(!g&&h){let F=e.manager.get(h);F&&(g=F.cwd)}if(!g)throw Object.assign(new Error("child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)"),{code:-32602});let x=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:h,interactive:x,transformChain:[],title:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("fork_session requires sessionId"),{code:N.InvalidParams});let p=typeof u.forkAt=="string"?u.forkAt:void 0,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("hydra-acp/session/delete requires sessionId"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.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 Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,g=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,30*6e4):5*6e4;if(!p)throw Object.assign(new Error("await_child requires childSessionId"),{code:-32602});let y=e.manager.get(p);if(!y)throw Object.assign(new Error(`child session ${p} not found`),{code:N.SessionNotFound});return new Promise(v=>{let b=[],x,C=()=>{clearTimeout(F),x?.(),v({entries:b})};x=y.onBroadcast(z=>{b.push(z),g==="turn_complete"&&z.params?.update?.sessionUpdate==="turn_complete"&&C()});let F=setTimeout(C,h);typeof F.unref=="function"&&F.unref(),y.onClose(()=>C())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw Object.assign(new Error("close_child_session requires childSessionId"),{code:-32602});let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,g=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw Object.assign(new Error("hydra-acp/session/tool_content requires sessionId and hash"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,g=await e.manager.loadToolBlob(p,u.hash);if(g===null)throw Object.assign(new Error("tool content not found"),{code:N.SessionNotFound});return{content:g}}),a.onRequest("session/new",async f=>{let u=tu.parse(f),p=kt(f?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(D=>typeof D=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(g)??[],y,v,b=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Yf(32).toString("hex"),v=e.mcpTokenRegistry.reserve(y);let $={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...u.mcpServers??[],$]}let x=Do(e);x!==void 0&&(b=[...b??[],...x.descriptors]);let C;try{C=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Vf(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(D){throw v!==void 0&&v.abandon(D instanceof Error?D:void 0),x!==void 0&&x.abandon(D instanceof Error?D:void 0),D}if(y!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let D=y,$=e.mcpTokenRegistry;v.complete(C),C.onClose(()=>{$.unbind(D)})}x!==void 0&&x.bindToSession(C);let F=No(a,C,d),{entries:z}=await C.attach(F,"full");d.attached.set(C.sessionId,{sessionId:C.sessionId,clientId:F.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let D of z)await a.notify(D.method,D.params).catch(()=>{})})()});let J=_d(C),X=Od(C);return{sessionId:C.sessionId,...J?{modes:J}:{},...X?{models:X}:{},configOptions:C.buildConfigOptions(),_meta:Fd(e.manager,C,{clientId:F.clientId})}}),a.onRequest("session/attach",async f=>{let u=nu.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=kt(u._meta),h=g.resume,y=g.readonly===!0;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${y}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,b=e.manager.get(v);if(!b&&y){let D=await e.manager.loadFromDisk(v);if(!D){let K=new Error(`session ${u.sessionId} not found`);throw K.code=N.SessionNotFound,K}let $=await e.manager.loadHistory(v),W=u.clientId??`cli_${Bd(8)}`;d.attached.set(D.hydraSessionId,{sessionId:D.hydraSessionId,clientId:W,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${D.hydraSessionId} clientId=${W} attachedCount=${d.attached.size} replayed=${$.length}`);for(let K of $)await a.notify(K.method,K.params).catch(()=>{});return{sessionId:D.hydraSessionId,clientId:W,connectedClients:[W],historyPolicy:"full",replayed:$.length,_meta:av(D)}}if(!b){let D=await e.manager.loadFromDisk(v),$=D;if(h&&($={...D,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!$){let ee=new Error(`session ${u.sessionId} not found and no resume hints provided`);throw ee.code=N.SessionNotFound,ee}let W=$.originatingClient?$:{...$,originatingClient:d.clientInfo},K=Do(e);try{b=await e.manager.resurrect({...W,mcpServers:K?.descriptors,onInstallProgress:Vf(a)})}catch(ee){throw K!==void 0&&K.abandon(ee instanceof Error?ee:void 0),ee}K!==void 0&&K.bindToSession(b),Ld(b,e)}let x=No(a,b,d,u.clientInfo,u.clientId),C=g.replayMode==="drip",{entries:F,appliedPolicy:z}=await b.attach(x,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:C,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:x.clientId,readonly:y}),t.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${x.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${z} replayed=${F.length} readonly=${y}${C?" replayMode=drip":""}`),C){let D=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,$=750;(async()=>{let W=null;for(let K of F){let ee=typeof K.recordedAt=="number"?K.recordedAt:null;if(W!==null&&ee!==null){let he=Math.min($,Math.max(0,(ee-W)/D));he>0&&await new Promise(ke=>setTimeout(ke,he))}ee!==null&&(W=ee);try{await a.notify(K.method,K.params)}catch{return}}})()}else for(let $=0;$<F.length;$++){let W=F[$],K=a.notify(W.method,W.params).catch(()=>{});($+1)%200===0&&await K}b.replayPendingPermissions(x);let J=_d(b),X=Od(b);return{sessionId:b.sessionId,clientId:x.clientId,connectedClients:b.connectedClients(x.clientId),historyPolicy:z,replayed:F.length,...J?{modes:J}:{},...X?{models:X}:{},configOptions:b.buildConfigOptions(),_meta:Fd(e.manager,b)}}),a.onRequest("session/detach",async f=>{let u=su.parse(f),p=d.attached.get(u.sessionId);if(!p){let h=new Error("client not attached to that session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);return g?.detach(p.clientId),d.attached.delete(u.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[pt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=ru.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==ps).map(ou)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry){let f=new Error("agent registry unavailable");throw f.code=N.InternalError,f}return Js(e.registry)}),a.onRequest("session/prompt",async f=>{let u=au.parse(f);c(u.sessionId,"session/prompt");let p=d.attached.get(u.sessionId);if(!p){t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`);let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=await e.manager.loadFromDisk(u.sessionId);if(!h){let b=new Error(`session ${u.sessionId} not found`);throw b.code=N.SessionNotFound,b}t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`);let y=Do(e);try{g=await e.manager.resurrect({...h,mcpServers:y?.descriptors})}catch(b){throw y!==void 0&&y.abandon(b instanceof Error?b:void 0),b}y!==void 0&&y.bindToSession(g),Ld(g,e);let v=No(a,g,d,void 0,p.clientId);await g.attach(v,"none")}return g.prompt(p.clientId,u)});let l=f=>{let u;try{u=Xi.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let g=e.manager.get(u.sessionId);g&&g.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Xi.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=cu.parse(f);c(u.sessionId,"hydra-acp/prompt/cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Xi.parse(f);c(u.sessionId,"hydra-acp/session/force_cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=lu.parse(f);c(u.sessionId,"hydra-acp/prompt/update");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=uu.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p){let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=new Error(`session ${u.sessionId} not found`);throw h.code=N.SessionNotFound,h}return g.amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p){let C=new Error("session/load requires sessionId");throw C.code=N.InvalidParams,C}let g=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(g);if(!h){let C=await e.manager.loadFromDisk(g);if(!C){let z=new Error(`session ${p} not found in memory or on disk`);throw z.code=N.SessionNotFound,z}let F=Do(e);try{h=await e.manager.resurrect({...C,mcpServers:F?.descriptors})}catch(z){throw F!==void 0&&F.abandon(z instanceof Error?z:void 0),z}F!==void 0&&F.bindToSession(h),Ld(h,e)}let y=No(a,h,d),{entries:v}=await h.attach(y,"pending_only");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1});for(let C of v)await a.notify(C.method,C.params);h.replayPendingPermissions(y);let b=_d(h),x=Od(h);return{sessionId:h.sessionId,...b?{modes:b}:{},...x?{models:x}:{},configOptions:h.buildConfigOptions(),_meta:Fd(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=iv(f,e.manager);if(p.kind==="error"){t.log.warn(p.logMessage);let y=new Error(p.message);throw y.code=p.code,y}if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:g}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:g});return p.session.applyModelChange(g),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string"){let y=new Error("session/set_mode requires string sessionId");throw y.code=N.InvalidParams,y}if(typeof u.modeId!="string"){let y=new Error("session/set_mode requires string modeId");throw y.code=N.InvalidParams,y}let g=e.manager.get(u.sessionId);if(!g){let y=new Error(`session ${u.sessionId} not found`);throw y.code=N.SessionNotFound,y}let h=await g.forwardRequest("session/set_mode",f);return g.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=v=>{let b=new Error(v);return b.code=N.InvalidParams,b},g=u?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=e.manager.get(u.sessionId);if(!h){let v=new Error(`session ${u.sessionId} not found`);throw v.code=N.SessionNotFound,v}let y=h.buildConfigOptions().find(v=>v.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(v=>v.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}let p=f.sessionId;if(typeof p!="string"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}c(p,u);let g=e.manager.get(p);if(!g){let h=new Error(`session ${p} not found`);throw h.code=N.SessionNotFound,h}return g.forwardRequest(u,f)})})}function Vf(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(Zi,n).catch(()=>{})}}function _d(t){let e=t.availableModes();if(e.length===0)return;let n=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:t.currentMode??e[0].id,availableModes:n}}function Od(t){let e=t.availableModels();if(e.length===0)return;let n=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:t.currentModel??e[0].modelId,availableModels:n}}function iv(t,e){if(!t||typeof t!="object")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:N.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Ys(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.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:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:N.InvalidParams,message:`model "${n.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=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function ov(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw Object.assign(new Error("transformer/attach requires sessionId"),{code:N.InvalidParams});if(!n.transformers)throw Object.assign(new Error("transformer manager not configured"),{code:N.InternalError});let i=n.transformers.resolveChain([e])[0];if(!i)throw Object.assign(new Error(`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`),{code:N.InternalError});let o=n.manager.get(r);if(!o)throw Object.assign(new Error(`session ${r} not found`),{code:N.SessionNotFound});return o.addTransformer(i),{ok:!0}}function av(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[pt]:Gi(e,n)}}function Fd(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.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 Qi(e.agentMeta,Gi(s,r))}function dv(){return{protocolVersion:tt,agentInfo:{name:"hydra",version:ce},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"bearer-token",description:"Bearer token presented at WS upgrade"}],_meta:Qi(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Ld(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function No(t,e,n,s,r){return{clientId:r??`cli_${Bd(8)}`,connection:t,clientInfo:s}}function Do(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=Yf(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var Ho=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as cv}from"crypto";import{McpServer as lv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as uv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ge}from"zod";var Gf="Bearer ";function Uo(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Gf))return;let n=e.slice(Gf.length).trim();return n.length>0?n:void 0}function fv(t){let e=new lv({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:Ge.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);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:Ge.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);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:Ge.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:Ge.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ge.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:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,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:Ge.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ge.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.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:Ge.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ge.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ge.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ge.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ge.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ge.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ge.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ge.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ge.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 n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.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 n=t.streamInfo();return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}),e}var pv=1e4;function Xf(t,e){let n=new Map;async function s(o,a){let d=n.get(o);if(d!==void 0)return d.transport;let c=fv(a),l=new uv({sessionIdGenerator:()=>cv()});await c.connect(l);let f={server:c,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=Uo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),pv)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let f=await s(d,l);a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var jo=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,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 n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as vv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Iv}from"crypto";import{Server as mv}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as hv,ListToolsRequestSchema as gv}from"@modelcontextprotocol/sdk/types.js";var yv=6e4;function Zf(t,e,n,s={}){let r=s.invokeTimeoutMs??yv,i=typeof n=="function"?async()=>n():async()=>n,o=new mv({name:t,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(gv,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(hv,async d=>{let c=d.params.name;if(!a.has(c))return qo(`unknown tool: ${c}`);try{let l=await i(),f=await wv(e.connection,t,c,d.params.arguments??{},l,r);return bv(f,c)}catch(l){return qo(l instanceof Error?l.message:String(l))}}),o}async function wv(t,e,n,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([t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function bv(t,e){if(t===null||typeof t!="object")return qo(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:qo(`extension ${e} omitted content array`)}function qo(t){return{content:[{type:"text",text:t}],isError:!0}}var Sv=1e4;function ep(t,e,n,s={}){let r=new Map;async function i(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let f of r.values()){let u=f.get(l);u!==void 0&&(f.delete(l),i(u))}}n.onChange(l=>{o(l)});async function a(l,f){let u=r.get(l);u===void 0&&(u=new Map,r.set(l,u),e.addDisposer(l,async()=>{let b=r.get(l);if(b!==void 0){r.delete(l);for(let x of b.values())await i(x)}}));let p=u.get(f);if(p!==void 0)return p.transport;let g=n.lookup(f);if(g===void 0)return;let y=Zf(f,g,async()=>{let b=e.lookup(l);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let x,C=new Promise(z=>{x=setTimeout(()=>z(void 0),Sv)}),F=await Promise.race([b.sessionReady.catch(()=>{}),C]);if(x!==void 0&&clearTimeout(x),F===void 0)throw new Error("session not ready");return F.sessionId},s.buildOptions),v=new vv({sessionIdGenerator:()=>Iv()});return await y.connect(v),u.set(f,{server:y,transport:v}),v}async function d(l,f){let u=Uo(l);if(u===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){f.code(404).send({error:"unknown mcp token"});return}let g=l.params.name,h=await a(u,g);if(h===void 0){f.code(404).send({error:`unknown mcp server: ${g}`});return}f.hijack(),await h.handleRequest(l.raw,f.raw,l.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.get("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.delete("/mcp/:name",c,async(l,f)=>{await d(l,f)})}async function sp(t,e){Rv(t);let n=t.daemon.tls?{key:await Wn.readFile(t.daemon.tls.key),cert:await Wn.readFile(t.daemon.tls.cert)}:void 0;await Wn.mkdir(P.home(),{recursive:!0});let{stream:s,fileStream:r}=await Cv(t.daemon.logLevel),i=kv({logger:{level:t.daemon.logLevel,stream:s},https:n??null,bodyLimit:256*1024*1024});await i.register(xv,{options:{handleProtocols:Fl}}),Va(H=>{i.log.info(H)}),Ga(H=>{i.log.info(H)});let o=await Ao.load(),a=new Po,d=new Eo,c=new To([new Co(e),new Ro(o),d]),l=wf({validator:c});i.addHook("onRequest",async(H,ge)=>{H.routeOptions.config?.skipAuth||H.url==="/acp"||H.url?.startsWith("/acp?")||await l(H,ge)});let f=setInterval(()=>{o.sweepExpired()},300*1e3);f.unref();let u=new Vi(t,{onFetched:()=>{cf(u,y)}});Rd(H=>i.log.info(H));let p={info:H=>i.log.info(H),warn:H=>i.log.warn(H)},g=H=>Nn.spawn({...H,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:p});Dl(t.compressToolContent);let h=new So,y=new go(u,g,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,synopsisOnClose:t.synopsisOnClose,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:p,npmRegistry:t.npmRegistry,extensionCommands:h,defaultCwd:t.defaultCwd}),v=new vo(yl(t),void 0,{tokenRegistry:d}),b=new Io(wl(t),void 0,{tokenRegistry:d});Lf(i,ce,nr(t)),Of(i,y,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port}),Ff(i,u,y,{npmRegistry:t.npmRegistry}),Bf(i,v),Nf(i,b),Df(i,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},synopsisOnClose:t.synopsisOnClose,defaultTransformers:[...t.defaultTransformers]}),Kf(i,{store:o,rateLimiter:a});let x=new Ho,C=new jo;Xf(i,x),ep(i,x,C);let F,z=()=>{if(F!==void 0)return F;let H=i.server.address(),ge=H&&typeof H=="object"?H.port:t.daemon.port;return F=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${ge}`,F};Qf(i,{validator:c,manager:y,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(H,ge)=>v.reportVersion(H,ge),onTransformerVersion:(H,ge)=>b.reportVersion(H,ge),transformers:b,extensionCommands:h,mcpTokenRegistry:x,extensionMcp:C,getDaemonOrigin:z,registry:u}),await i.listen({host:t.daemon.host,port:t.daemon.port});let J=i.server.address(),X=J&&typeof J=="object"?J.port:t.daemon.port;await Wn.mkdir(P.home(),{recursive:!0}),await Wn.writeFile(P.pidFile(),JSON.stringify({pid:process.pid,host:t.daemon.host,port:X,startedAt:new Date().toISOString()})+`
271
- `,{encoding:"utf8",mode:384});let D=t.daemon.tls?"https":"http",$=t.daemon.tls?"wss":"ws",W={daemonUrl:`${D}://${t.daemon.host}:${X}`,daemonHost:t.daemon.host,daemonPort:X,serviceToken:e,daemonWsUrl:`${$}://${t.daemon.host}:${X}/acp`,hydraHome:P.home()};v.setContext(W),b.setContext(W),await v.start(),await b.start(),y.resurrectPendingQueues().catch(H=>{i.log.warn(`queue replay scan failed: ${H.message}`)});let K=t.daemon.agentSyncIntervalMinutes*60*1e3,ee=K>0?lf({registry:u,manager:y,intervalMs:K,logger:p}):void 0,he=t.daemon.sessionGcIntervalMinutes*60*1e3,ke=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,te=he>0?uf({manager:y,intervalMs:he,maxAgeMs:ke,logger:p}):void 0;return{app:i,manager:y,registry:u,extensions:v,transformers:b,mcpTokenRegistry:x,extensionMcp:C,processRegistry:d,shutdown:async()=>{te&&te(),ee&&ee(),clearInterval(f),await o.flush(),await v.stop(),await b.stop(),await y.closeAll(),await y.flushSynopsis(3e4),await y.shutdownSynopsis(),await y.flushMetaWrites(),await y.flushHistoryWrites(),Va(null),Ga(null),Rd(null),await i.close();try{np.unlinkSync(P.pidFile())}catch{}try{r.flushSync()}catch{}}}}async function Cv(t){let e=await Av({file:P.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=tp.destination(2);return{stream:tp.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function Rv(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}dr();$t();xo();import*as rp from"fs";import*as cr from"fs/promises";async function zn(t,e,n){let s=Mv(e),r;try{r=await cr.stat(t)}catch(d){if(d.code==="ENOENT"){process.stderr.write(`${n} (${t})
272
- `),process.exit(1);return}throw d}let i=await Pv(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
273
- `);let o=!1,a=rp.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let d=await cr.stat(t);if(d.size<=i){d.size<i&&(i=d.size);return}let c=await cr.open(t,"r");try{let l=Buffer.alloc(d.size-i);await c.read(l,0,l.length,i),process.stdout.write(l),i=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function Pv(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await cr.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let f=Buffer.alloc(l);await r.read(f,0,l,i),o=f.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let c=o.split(`
268
+ `);let y=h;typeof y.recordedAt=="number"&&g.add(String(y.recordedAt))}for(let h of p){let y=h,I=typeof y.recordedAt=="number"?String(y.recordedAt):"";I&&g.has(I)||r.raw.write(JSON.stringify(h)+`
269
+ `)}return f=!0,u?(s.raw.on("close",()=>{u?.(),r.raw.writableEnded||r.raw.end()}),r):(r.raw.end(),r)})}st();function Nf(t,e,n,s={}){t.get("/v1/agents",async()=>Gs(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.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 Un(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})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await n.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===N.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function Df(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var Kb=/^[A-Za-z0-9._-]+$/;function Hf(t,e){t.get("/v1/extensions",async()=>({extensions:e.list()})),t.get("/v1/extensions/:name",async(n,s)=>{let r=n.params.name,i=e.get(r);if(!i){s.code(404).send({error:`unknown extension: ${r}`});return}return i}),t.post("/v1/extensions",async(n,s)=>{let r=n.body??{},i=Vb(r);if("error"in i){s.code(400).send({error:i.error});return}try{let o=e.register(i.config);s.code(201).send(o)}catch(o){ai(s,o)}}),t.delete("/v1/extensions/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(i){ai(s,i)}}),t.post("/v1/extensions/:name/start",async(n,s)=>{let r=n.params.name;try{let i=await e.startByName(r);s.code(200).send(i)}catch(i){ai(s,i)}}),t.post("/v1/extensions/:name/stop",async(n,s)=>{let r=n.params.name;try{let i=await e.stopByName(r);s.code(200).send(i)}catch(i){ai(s,i)}}),t.post("/v1/extensions/:name/restart",async(n,s)=>{let r=n.params.name;try{let i=await e.restartByName(r);s.code(200).send(i)}catch(i){ai(s,i)}})}function ai(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function Vb(t){let e=t.name;if(typeof e!="string"||!Kb.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.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=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}var Yb=/^[A-Za-z0-9._-]+$/;function Uf(t,e){t.get("/v1/transformers",async()=>({transformers:e.list()})),t.get("/v1/transformers/:name",async(n,s)=>{let r=n.params.name,i=e.get(r);if(!i){s.code(404).send({error:`unknown transformer: ${r}`});return}return i}),t.post("/v1/transformers",async(n,s)=>{let r=n.body??{},i=Qb(r);if("error"in i){s.code(400).send({error:i.error});return}try{let o=e.register(i.config);s.code(201).send(o)}catch(o){di(s,o)}}),t.delete("/v1/transformers/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(i){di(s,i)}}),t.post("/v1/transformers/:name/start",async(n,s)=>{let r=n.params.name;try{let i=await e.startByName(r);s.code(200).send(i)}catch(i){di(s,i)}}),t.post("/v1/transformers/:name/stop",async(n,s)=>{let r=n.params.name;try{let i=await e.stopByName(r);s.code(200).send(i)}catch(i){di(s,i)}}),t.post("/v1/transformers/:name/restart",async(n,s)=>{let r=n.params.name;try{let i=await e.restartByName(r);s.code(200).send(i)}catch(i){di(s,i)}})}function di(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function Qb(t){let e=t.name;if(typeof e!="string"||!Yb.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.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=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function jf(t,e){t.get("/v1/config",async()=>e)}import{z as lr}from"zod";me();import*as Jn from"fs/promises";import*as Jf from"path";import{randomBytes as Gb,scrypt as Xb,timingSafeEqual as Zb}from"crypto";import{promisify as ev}from"util";var Kf=ev(Xb);function Fd(){return Jf.join(E.home(),"password-hash")}var qf=32768,Wf=8,zf=1,tv=64,nv=16,Vf=128*1024*1024;async function Yf(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=Gb(nv),n=await Kf(t,e,tv,{N:qf,r:Wf,p:zf,maxmem:Vf}),s=`scrypt$${qf}$${Wf}$${zf}$${e.toString("hex")}$${n.toString("hex")}
270
+ `;await Jn.mkdir(E.home(),{recursive:!0}),await Jn.writeFile(Fd(),s,{encoding:"utf8",mode:384})}async function Do(){try{return(await Jn.readFile(Fd(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ho(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Jn.readFile(Fd(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let d=await Kf(t,o,a.length,{N:s,r,p:i,maxmem:Vf});return d.length!==a.length?!1:Zb(d,a)}var sv=lr.object({password:lr.string().min(1),label:lr.string().min(1).max(256).optional(),ttlSec:lr.number().int().positive().optional()}),rv=lr.object({id:lr.string().optional()}).optional();function Qf(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=iv(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=sv.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Do())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Ho(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})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=rv.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.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})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function iv(t){return t.ip||"unknown"}Xs();ci();ao();st();import{nanoid as Hd}from"nanoid";Mt();import{randomBytes as Xf}from"crypto";function Zf(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Sf({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Kn(n),a=new Pt(o),d={clientId:`hydra_client_${Hd(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,f)=>{if(d.attached.get(u)?.readonly){let g=new Error(`${f} not permitted on a read-only attachment`);throw g.code=N.PermissionDenied,g}};if(a.onRequest("initialize",async u=>{let f=su.parse(u??{});f.clientInfo?.name&&(d.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),cv()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},g=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.verb!="string")return;let I={verb:y.verb};return typeof y.argsHint=="string"&&(I.argsHint=y.argsHint),typeof y.description=="string"&&(I.description=y.description),I}).filter(h=>h!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},g=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let I=y;if(typeof I.name!="string"||I.name.length===0||typeof I.description!="string"||I.inputSchema===null||typeof I.inputSchema!="object")return;let b={name:I.name,description:I.description,inputSchema:I.inputSchema};return I.outputSchema!==null&&typeof I.outputSchema=="object"&&(b.outputSchema=I.outputSchema),b}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,g=typeof f.method=="string"?f.method:void 0,h=f.envelope,y=f.route;if(!p||!g)throw Object.assign(new Error("emit_message requires sessionId and method"),{code:-32602});let I=e.manager.get(p);if(!I)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});let b=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(b)return I.dischargeClaim(b,h),{ok:!0};if(y==="chain")return{ok:!0,response:await I.emitToChain(i.name,g,h)};if(y==="daemon")return{ok:!0,response:await I.emitToChain(i.name,g,h)};throw Object.assign(new Error(`unsupported route: ${JSON.stringify(y)}`),{code:-32602})}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw Object.assign(new Error("hydra-acp/session/request_permission requires sessionId"),{code:-32602});let g=e.manager.get(p);if(!g)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return g.requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>av(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,g=typeof f.cwd=="string"?f.cwd:void 0,h=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,I=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,b=I&&typeof I.title=="string"?I.title:void 0;if(!g&&h){let _=e.manager.get(h);_&&(g=_.cwd)}if(!g)throw Object.assign(new Error("child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)"),{code:-32602});let x=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:h,interactive:x,transformChain:[],title:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw Object.assign(new Error("fork_session requires sessionId"),{code:N.InvalidParams});let p=typeof f.forkAt=="string"?f.forkAt:void 0,g=typeof f.cwd=="string"?f.cwd:void 0,h=typeof f.agentId=="string"?f.agentId:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw Object.assign(new Error("hydra-acp/session/delete requires sessionId"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=e.manager.get(p);if(g)return await g.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,g=f.until==="idle"?"idle":"turn_complete",h=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,30*6e4):5*6e4;if(!p)throw Object.assign(new Error("await_child requires childSessionId"),{code:-32602});let y=e.manager.get(p);if(!y)throw Object.assign(new Error(`child session ${p} not found`),{code:N.SessionNotFound});return new Promise(I=>{let b=[],x,M=()=>{clearTimeout(_),x?.(),I({entries:b})};x=y.onBroadcast(Q=>{b.push(Q),g==="turn_complete"&&Q.params?.update?.sessionUpdate==="turn_complete"&&M()});let _=setTimeout(M,h);typeof _.unref=="function"&&_.unref(),y.onClose(()=>M())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw Object.assign(new Error("close_child_session requires childSessionId"),{code:-32602});let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,g=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw Object.assign(new Error("hydra-acp/session/tool_content requires sessionId and hash"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=await e.manager.loadToolBlob(p,f.hash);if(g===null)throw Object.assign(new Error("tool content not found"),{code:N.SessionNotFound});return{content:g}}),a.onRequest("session/new",async u=>{let f=ru.parse(u),p=xt(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every($=>typeof $=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(g)??[],y,I,b=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Xf(32).toString("hex"),I=e.mcpTokenRegistry.reserve(y);let D={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...f.mcpServers??[],D]}let x=jo(e);x!==void 0&&(b=[...b??[],...x.descriptors]);let M;try{M=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Gf(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch($){throw I!==void 0&&I.abandon($ instanceof Error?$:void 0),x!==void 0&&x.abandon($ instanceof Error?$:void 0),$}if(y!==void 0&&I!==void 0&&e.mcpTokenRegistry!==void 0){let $=y,D=e.mcpTokenRegistry;I.complete(M),M.onClose(()=>{D.unbind($)})}x!==void 0&&x.bindToSession(M);let _=Uo(a,M,d),{entries:Q}=await M.attach(_,"full");d.attached.set(M.sessionId,{sessionId:M.sessionId,clientId:_.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let $ of Q)await a.notify($.method,$.params).catch(()=>{})})()});let W=Ld(M),z=Bd(M);return{sessionId:M.sessionId,...W?{modes:W}:{},...z?{models:z}:{},configOptions:M.buildConfigOptions(),_meta:Nd(e.manager,M,{clientId:_.clientId})}}),a.onRequest("session/attach",async u=>{let f=iu.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=xt(f._meta),h=g.resume,y=g.readonly===!0;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!h} readonly=${y}`);let I=h?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,b=e.manager.get(I);if(!b&&y){let $=await e.manager.loadFromDisk(I);if(!$){let Z=new Error(`session ${f.sessionId} not found`);throw Z.code=N.SessionNotFound,Z}let D=await e.manager.loadHistory(I),j=f.clientId??`cli_${Hd(8)}`;d.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:j,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${j} attachedCount=${d.attached.size} replayed=${D.length}`);for(let Z of D)await a.notify(Z.method,Z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:D.length,_meta:dv($)}}if(!b){let $=await e.manager.loadFromDisk(I),D=$;if(h&&(D={...$,hydraSessionId:f.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!D){let ie=new Error(`session ${f.sessionId} not found and no resume hints provided`);throw ie.code=N.SessionNotFound,ie}let j=D.originatingClient?D:{...D,originatingClient:d.clientInfo},Z=jo(e);try{b=await e.manager.resurrect({...j,mcpServers:Z?.descriptors,onInstallProgress:Gf(a)})}catch(ie){throw Z!==void 0&&Z.abandon(ie instanceof Error?ie:void 0),ie}Z!==void 0&&Z.bindToSession(b),Dd(b,e)}let x=Uo(a,b,d,f.clientInfo,f.clientId),M=g.replayMode==="drip",{entries:_,appliedPolicy:Q}=await b.attach(x,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:M,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:x.clientId,readonly:y}),t.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${x.clientId} attachedCount=${d.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${Q} replayed=${_.length} readonly=${y}${M?" replayMode=drip":""}`),M){let $=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,D=750;(async()=>{let j=null;for(let Z of _){let ie=typeof Z.recordedAt=="number"?Z.recordedAt:null;if(j!==null&&ie!==null){let se=Math.min(D,Math.max(0,(ie-j)/$));se>0&&await new Promise(Ee=>setTimeout(Ee,se))}ie!==null&&(j=ie);try{await a.notify(Z.method,Z.params)}catch{return}}})()}else for(let D=0;D<_.length;D++){let j=_[D],Z=a.notify(j.method,j.params).catch(()=>{});(D+1)%200===0&&await Z}b.replayPendingPermissions(x);let W=Ld(b),z=Bd(b);return{sessionId:b.sessionId,clientId:x.clientId,connectedClients:b.connectedClients(x.clientId),historyPolicy:Q,replayed:_.length,...W?{modes:W}:{},...z?{models:z}:{},configOptions:b.buildConfigOptions(),_meta:Nd(e.manager,b)}}),a.onRequest("session/detach",async u=>{let f=ou.parse(u),p=d.attached.get(f.sessionId);if(!p){let h=new Error("client not attached to that session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(f.sessionId);return g?.detach(p.clientId),d.attached.delete(f.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[ht]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=au.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==ys).map(cu)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry){let u=new Error("agent registry unavailable");throw u.code=N.InternalError,u}return Gs(e.registry)}),a.onRequest("session/prompt",async u=>{let f=lu.parse(u);c(f.sessionId,"session/prompt");let p=d.attached.get(f.sessionId);if(!p){t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`);let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(f.sessionId);if(!g){let h=await e.manager.loadFromDisk(f.sessionId);if(!h){let b=new Error(`session ${f.sessionId} not found`);throw b.code=N.SessionNotFound,b}t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`);let y=jo(e);try{g=await e.manager.resurrect({...h,mcpServers:y?.descriptors})}catch(b){throw y!==void 0&&y.abandon(b instanceof Error?b:void 0),b}y!==void 0&&y.bindToSession(g),Dd(g,e);let I=Uo(a,g,d,void 0,p.clientId);await g.attach(I,"none")}return g.prompt(p.clientId,f)});let l=u=>{let f;try{f=to.parse(u)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let g=e.manager.get(f.sessionId);g&&g.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${f.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=to.parse(u);return c(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=fu.parse(u);c(f.sessionId,"hydra-acp/prompt/cancel");let p=e.manager.get(f.sessionId);if(!p){let g=new Error(`session ${f.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=to.parse(u);c(f.sessionId,"hydra-acp/session/force_cancel");let p=e.manager.get(f.sessionId);if(!p){let g=new Error(`session ${f.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=pu.parse(u);c(f.sessionId,"hydra-acp/prompt/update");let p=e.manager.get(f.sessionId);if(!p){let g=new Error(`session ${f.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=mu.parse(u);c(f.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(f.sessionId);if(!p){let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(f.sessionId);if(!g){let h=new Error(`session ${f.sessionId} not found`);throw h.code=N.SessionNotFound,h}return g.amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p){let M=new Error("session/load requires sessionId");throw M.code=N.InvalidParams,M}let g=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(g);if(!h){let M=await e.manager.loadFromDisk(g);if(!M){let Q=new Error(`session ${p} not found in memory or on disk`);throw Q.code=N.SessionNotFound,Q}let _=jo(e);try{h=await e.manager.resurrect({...M,mcpServers:_?.descriptors})}catch(Q){throw _!==void 0&&_.abandon(Q instanceof Error?Q:void 0),Q}_!==void 0&&_.bindToSession(h),Dd(h,e)}let y=Uo(a,h,d),{entries:I}=await h.attach(y,"pending_only");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1});for(let M of I)await a.notify(M.method,M.params);h.replayPendingPermissions(y);let b=Ld(h),x=Bd(h);return{sessionId:h.sessionId,...b?{modes:b}:{},...x?{models:x}:{},configOptions:h.buildConfigOptions(),_meta:Nd(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=ov(u,e.manager);if(p.kind==="error"){t.log.warn(p.logMessage);let y=new Error(p.message);throw y.code=p.code,y}if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:g}=p,h=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),h}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string"){let y=new Error("session/set_mode requires string sessionId");throw y.code=N.InvalidParams,y}if(typeof f.modeId!="string"){let y=new Error("session/set_mode requires string modeId");throw y.code=N.InvalidParams,y}let g=e.manager.get(f.sessionId);if(!g){let y=new Error(`session ${f.sessionId} not found`);throw y.code=N.SessionNotFound,y}let h=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(f.modeId),h}),a.onRequest("session/set_config_option",async u=>{let f=u,p=I=>{let b=new Error(I);return b.code=N.InvalidParams,b},g=f?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let h=e.manager.get(f.sessionId);if(!h){let I=new Error(`session ${f.sessionId} not found`);throw I.code=N.SessionNotFound,I}let y=h.buildConfigOptions().find(I=>I.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(I=>I.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),h.applyModelChange(f.value);break}case"mode":{f.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),h.applyModeChange(f.value);break}case"agent":{f.value!==h.agentId&&await h.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{if(!f.startsWith("session/")||u===null||typeof u!="object"){let h=new Error(`Method not found: ${f}`);throw h.code=N.MethodNotFound,h}let p=u.sessionId;if(typeof p!="string"){let h=new Error(`Method not found: ${f}`);throw h.code=N.MethodNotFound,h}c(p,f);let g=e.manager.get(p);if(!g){let h=new Error(`session ${p} not found`);throw h.code=N.SessionNotFound,h}return g.forwardRequest(f,u)})})}function Gf(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(no,n).catch(()=>{})}}function Ld(t){let e=t.availableModes();if(e.length===0)return;let n=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:t.currentMode??e[0].id,availableModes:n}}function Bd(t){let e=t.availableModels();if(e.length===0)return;let n=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:t.currentModel??e[0].modelId,availableModels:n}}function ov(t,e){if(!t||typeof t!="object")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:N.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=er(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.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:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:N.InvalidParams,message:`model "${n.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=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function av(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw Object.assign(new Error("transformer/attach requires sessionId"),{code:N.InvalidParams});if(!n.transformers)throw Object.assign(new Error("transformer manager not configured"),{code:N.InternalError});let i=n.transformers.resolveChain([e])[0];if(!i)throw Object.assign(new Error(`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`),{code:N.InternalError});let o=n.manager.get(r);if(!o)throw Object.assign(new Error(`session ${r} not found`),{code:N.SessionNotFound});return o.addTransformer(i),{ok:!0}}function dv(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[ht]:eo(e,n)}}function Nd(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.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 Zi(e.agentMeta,eo(s,r))}function cv(){return{protocolVersion:nt,agentInfo:{name:"hydra",version:pe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"bearer-token",description:"Bearer token presented at WS upgrade"}],_meta:Zi(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Dd(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function Uo(t,e,n,s,r){return{clientId:r??`cli_${Hd(8)}`,connection:t,clientInfo:s}}function jo(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=Xf(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var qo=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as lv}from"crypto";import{McpServer as uv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as fv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ge}from"zod";var ep="Bearer ";function Wo(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(ep))return;let n=e.slice(ep.length).trim();return n.length>0?n:void 0}function pv(t){let e=new uv({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:Ge.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);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:Ge.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);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:Ge.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:Ge.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ge.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:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,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:Ge.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ge.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.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:Ge.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ge.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ge.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ge.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ge.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ge.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ge.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ge.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ge.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 n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.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 n=t.streamInfo();return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}),e}var mv=1e4;function tp(t,e){let n=new Map;async function s(o,a){let d=n.get(o);if(d!==void 0)return d.transport;let c=pv(a),l=new fv({sessionIdGenerator:()=>lv()});await c.connect(l);let u={server:c,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=Wo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(h=>{f=setTimeout(()=>h(void 0),mv)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let u=await s(d,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var zo=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,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 n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as Iv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Sv}from"crypto";import{Server as hv}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as gv,ListToolsRequestSchema as yv}from"@modelcontextprotocol/sdk/types.js";var wv=6e4;function np(t,e,n,s={}){let r=s.invokeTimeoutMs??wv,i=typeof n=="function"?async()=>n():async()=>n,o=new hv({name:t,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(yv,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(gv,async d=>{let c=d.params.name;if(!a.has(c))return Jo(`unknown tool: ${c}`);try{let l=await i(),u=await bv(e.connection,t,c,d.params.arguments??{},l,r);return vv(u,c)}catch(l){return Jo(l instanceof Error?l.message:String(l))}}),o}async function bv(t,e,n,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([t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function vv(t,e){if(t===null||typeof t!="object")return Jo(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Jo(`extension ${e} omitted content array`)}function Jo(t){return{content:[{type:"text",text:t}],isError:!0}}var kv=1e4;function sp(t,e,n,s={}){let r=new Map;async function i(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),i(f))}}n.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let b=r.get(l);if(b!==void 0){r.delete(l);for(let x of b.values())await i(x)}}));let p=f.get(u);if(p!==void 0)return p.transport;let g=n.lookup(u);if(g===void 0)return;let y=np(u,g,async()=>{let b=e.lookup(l);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let x,M=new Promise(Q=>{x=setTimeout(()=>Q(void 0),kv)}),_=await Promise.race([b.sessionReady.catch(()=>{}),M]);if(x!==void 0&&clearTimeout(x),_===void 0)throw new Error("session not ready");return _.sessionId},s.buildOptions),I=new Iv({sessionIdGenerator:()=>Sv()});return await y.connect(I),f.set(u,{server:y,transport:I}),I}async function d(l,u){let f=Wo(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=l.params.name,h=await a(f,g);if(h===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await h.handleRequest(l.raw,u.raw,l.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),t.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),t.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)})}async function op(t,e){Tv(t);let n=t.daemon.tls?{key:await Vn.readFile(t.daemon.tls.key),cert:await Vn.readFile(t.daemon.tls.cert)}:void 0;await Vn.mkdir(E.home(),{recursive:!0});let{stream:s,fileStream:r}=await Rv(t.daemon.logLevel),i=xv({logger:{level:t.daemon.logLevel,stream:s},https:n??null,bodyLimit:256*1024*1024});await i.register(Av,{options:{handleProtocols:Nl}}),Ga(X=>{i.log.info(X)}),ed(X=>{i.log.info(X)});let o=await To.load(),a=new _o,d=new $o,c=new Mo([new Eo(e),new Po(o),d]),l=If({validator:c});i.addHook("onRequest",async(X,ee)=>{X.routeOptions.config?.skipAuth||X.url==="/acp"||X.url?.startsWith("/acp?")||await l(X,ee)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let f=new Gi(t,{onFetched:()=>{ff(f,y)}});Pd(X=>i.log.info(X));let p={info:X=>i.log.info(X),warn:X=>i.log.warn(X)},g=X=>jn.spawn({...X,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:p});jl(t.compressToolContent);let h=new Ao,y=new bo(f,g,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,synopsisOnClose:t.synopsisOnClose,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:p,npmRegistry:t.npmRegistry,extensionCommands:h,defaultCwd:t.defaultCwd}),I=new ko(vl(t),void 0,{tokenRegistry:d}),b=new xo(Il(t),void 0,{tokenRegistry:d});Df(i,pe,ar(t)),Bf(i,y,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port}),Nf(i,f,y,{npmRegistry:t.npmRegistry}),Hf(i,I),Uf(i,b),jf(i,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},synopsisOnClose:t.synopsisOnClose,defaultTransformers:[...t.defaultTransformers]}),Qf(i,{store:o,rateLimiter:a});let x=new qo,M=new zo;tp(i,x),sp(i,x,M);let _,Q=()=>{if(_!==void 0)return _;let X=i.server.address(),ee=X&&typeof X=="object"?X.port:t.daemon.port;return _=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${ee}`,_};Zf(i,{validator:c,manager:y,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(X,ee)=>I.reportVersion(X,ee),onTransformerVersion:(X,ee)=>b.reportVersion(X,ee),transformers:b,extensionCommands:h,mcpTokenRegistry:x,extensionMcp:M,getDaemonOrigin:Q,registry:f}),await i.listen({host:t.daemon.host,port:t.daemon.port});let W=i.server.address(),z=W&&typeof W=="object"?W.port:t.daemon.port;await Vn.mkdir(E.home(),{recursive:!0}),await Vn.writeFile(E.pidFile(),JSON.stringify({pid:process.pid,host:t.daemon.host,port:z,startedAt:new Date().toISOString()})+`
271
+ `,{encoding:"utf8",mode:384});let $=t.daemon.tls?"https":"http",D=t.daemon.tls?"wss":"ws",j={daemonUrl:`${$}://${t.daemon.host}:${z}`,daemonHost:t.daemon.host,daemonPort:z,serviceToken:e,daemonWsUrl:`${D}://${t.daemon.host}:${z}/acp`,hydraHome:E.home()};I.setContext(j),b.setContext(j),await I.start(),await b.start(),y.resurrectPendingQueues().catch(X=>{i.log.warn(`queue replay scan failed: ${X.message}`)});let Z=t.daemon.agentSyncIntervalMinutes*60*1e3,ie=Z>0?pf({registry:f,manager:y,intervalMs:Z,logger:p}):void 0,se=t.daemon.sessionGcIntervalMinutes*60*1e3,Ee=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,K=se>0?mf({manager:y,intervalMs:se,maxAgeMs:Ee,logger:p}):void 0;return{app:i,manager:y,registry:f,extensions:I,transformers:b,mcpTokenRegistry:x,extensionMcp:M,processRegistry:d,shutdown:async()=>{K&&K(),ie&&ie(),clearInterval(u),await o.flush(),await I.stop(),await b.stop(),await y.closeAll(),await y.flushSynopsis(3e4),await y.shutdownSynopsis(),await y.flushMetaWrites(),await y.flushHistoryWrites(),Ga(null),ed(null),Pd(null),await i.close();try{ip.unlinkSync(E.pidFile())}catch{}try{r.flushSync()}catch{}}}}async function Rv(t){let e=await Cv({file:E.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=rp.destination(2);return{stream:rp.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function Tv(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}pr();Mt();Ro();import*as ap from"fs";import*as mr from"fs/promises";async function Yn(t,e,n){let s=$v(e),r;try{r=await mr.stat(t)}catch(d){if(d.code==="ENOENT"){process.stderr.write(`${n} (${t})
272
+ `),process.exit(1);return}throw d}let i=await Mv(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
273
+ `);let o=!1,a=ap.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let d=await mr.stat(t);if(d.size<=i){d.size<i&&(i=d.size);return}let c=await mr.open(t,"r");try{let l=Buffer.alloc(d.size-i);await c.read(l,0,l.length,i),process.stdout.write(l),i=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function Mv(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await mr.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let c=o.split(`
274
274
  `).slice(-n-1);process.stdout.write(c.join(`
275
275
  `)),o.endsWith(`
276
276
  `)||process.stdout.write(`
277
- `)}finally{await r.close()}return e}function lr(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function Mv(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
277
+ `)}finally{await r.close()}return e}function hr(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function $v(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
278
278
  `),process.exit(2)),e=o,s+=2;continue}if(r==="--follow"||r==="-f"){n=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
279
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function ap(t={}){let e=await G(),n=await Lr();if(await ri(e)){let r=await ur();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
280
- `);return}if(Os(t,"foreground")){process.title="hydra-daemon";let r=await sp(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
279
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function lp(t={}){let e=await G(),n=await jr();if(await li(e)){let r=await gr();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
280
+ `);return}if(Ds(t,"foreground")){process.title="hydra-daemon";let r=await op(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
281
281
  `);let i=async()=>{process.stdout.write(`Shutting down...
282
- `),await r.shutdown(),process.exit(0)};process.on("SIGINT",()=>{i()}),process.on("SIGTERM",()=>{i()}),process.on("SIGHUP",()=>{});return}Wo(),await zo(e);let s=await ur();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
283
- `)}async function dp(){let t=await ur();if(!t){process.stdout.write(`No running daemon found.
282
+ `),await r.shutdown(),process.exit(0)};process.on("SIGINT",()=>{i()}),process.on("SIGTERM",()=>{i()}),process.on("SIGHUP",()=>{});return}Ko(),await Vo(e);let s=await gr();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
283
+ `)}async function up(){let t=await gr();if(!t){process.stdout.write(`No running daemon found.
284
284
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
285
285
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
286
- `)}}async function cp(){let t=await G();await Lr();let e=await ur();if(e&&Nd(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
286
+ `)}}async function fp(){let t=await G();await jr();let e=await gr();if(e&&Ud(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
287
287
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
288
- `),process.exit(1)}await _v(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
288
+ `),process.exit(1)}await Ov(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
289
289
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
290
- `);if(Wo(),await zo(t),await ri(t)){let n=await ur();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
291
- `)}}async function _v(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Nd(t))return!0;await $v(50)}return!1}async function lp(t){await zn(P.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function up(){let t=await ur();if(!t){process.stdout.write(`Daemon: not running
292
- `),process.stdout.write(`CLI version: ${ce}
293
- `);return}let e=Nd(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
294
- `);let n,s;if(e)try{let o=await G();n=await ar(o),s=nr(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${ce}
290
+ `);if(Ko(),await Vo(t),await li(t)){let n=await gr();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
291
+ `)}}async function Ov(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Ud(t))return!0;await _v(50)}return!1}async function pp(t){await Yn(E.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function mp(){let t=await gr();if(!t){process.stdout.write(`Daemon: not running
292
+ `),process.stdout.write(`CLI version: ${pe}
293
+ `);return}let e=Ud(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
294
+ `);let n,s;if(e)try{let o=await G();n=await fr(o),s=ar(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${pe}
295
295
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
296
- `);return}let r=n.version===ce,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${ce}
297
- `);return}process.stdout.write(`CLI version: ${ce}
296
+ `);return}let r=n.version===pe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${pe}
297
+ `);return}process.stdout.write(`CLI version: ${pe}
298
298
  `),process.stdout.write(`Daemon version: ${n.version}
299
- `),r||process.stdout.write(ip.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(ip.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function ur(){try{let t=await op.readFile(P.pidFile(),"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return;throw t}}function Nd(t){try{return process.kill(t,0),!0}catch{return!1}}wn();Zd();Qo();Yd();Oe();ft();ue();import*as ta from"fs/promises";wn();async function zp(){let t=await G(),e=await de(),n=fe(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/extensions`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
299
+ `),r||process.stdout.write(dp.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(dp.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function gr(){try{let t=await cp.readFile(E.pidFile(),"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return;throw t}}function Ud(t){try{return process.kill(t,0),!0}catch{return!1}}In();nc();Zo();Xd();Oe();mt();me();import*as ra from"fs/promises";In();async function Vp(){let t=await G(),e=await fe(),n=he(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/extensions`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
300
300
  `),process.exit(1)),s=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${n}: ${d.message}
301
301
  `),process.exit(1);return}if(s.extensions.length===0){process.stdout.write(`No extensions configured.
302
- `);return}let r=s.extensions.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?$I(d.startedAt):"-",log:d.logPath})),i={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},o={name:wr(i.name,r.map(d=>d.name)),status:wr(i.status,r.map(d=>d.status)),version:wr(i.version,r.map(d=>d.version)),pid:wr(i.pid,r.map(d=>d.pid)),restarts:wr(i.restarts,r.map(d=>d.restarts)),started:wr(i.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(o.name),d.status.padEnd(o.status),d.version.padEnd(o.version),d.pid.padStart(o.pid),d.restarts.padStart(o.restarts),d.started.padEnd(o.started),d.log].join(" ");process.stdout.write(a(i)+`
302
+ `);return}let r=s.extensions.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?_I(d.startedAt):"-",log:d.logPath})),i={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},o={name:kr(i.name,r.map(d=>d.name)),status:kr(i.status,r.map(d=>d.status)),version:kr(i.version,r.map(d=>d.version)),pid:kr(i.pid,r.map(d=>d.pid)),restarts:kr(i.restarts,r.map(d=>d.restarts)),started:kr(i.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(o.name),d.status.padEnd(o.status),d.version.padEnd(o.version),d.pid.padStart(o.pid),d.restarts.padStart(o.restarts),d.started.padEnd(o.started),d.log].join(" ");process.stdout.write(a(i)+`
303
303
  `);for(let d of r)process.stdout.write(a(d)+`
304
304
  `);for(let d of s.extensions)d.failureReason&&process.stdout.write(` \u21B3 ${d.name}: ${d.failureReason}
305
- `)}async function Jp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
305
+ `)}async function Yp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
306
306
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid extension name '${t}': must match [A-Za-z0-9._-]+
307
- `),process.exit(2);return}await G();let n=await Vp();(!n.extensions||typeof n.extensions!="object")&&(n.extensions={});let s=n.extensions;if(s[t]){process.stderr.write(`Extension '${t}' already exists in config.
308
- `),process.exit(1);return}let{command:r,args:i,env:o,enabled:a}=PI(e),d={};r.length>0&&(d.command=r),i.length>0&&(d.args=i),Object.keys(o).length>0&&(d.env=o),a||(d.enabled=!1),s[t]=d,await Yp(n),process.stdout.write(`Added extension '${t}' to ${P.config()}
309
- `);let c=await G(),l=await de(),f=fe(c.daemon.host,c.daemon.port,!!c.daemon.tls),u={name:t,...d};try{let p=await fetch(`${f}/v1/extensions`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(u)});if(p.ok){let h=await p.json(),y=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${y}
307
+ `),process.exit(2);return}await G();let n=await Gp();(!n.extensions||typeof n.extensions!="object")&&(n.extensions={});let s=n.extensions;if(s[t]){process.stderr.write(`Extension '${t}' already exists in config.
308
+ `),process.exit(1);return}let{command:r,args:i,env:o,enabled:a}=MI(e),d={};r.length>0&&(d.command=r),i.length>0&&(d.args=i),Object.keys(o).length>0&&(d.env=o),a||(d.enabled=!1),s[t]=d,await Xp(n),process.stdout.write(`Added extension '${t}' to ${E.config()}
309
+ `);let c=await G(),l=await fe(),u=he(c.daemon.host,c.daemon.port,!!c.daemon.tls),f={name:t,...d};try{let p=await fetch(`${u}/v1/extensions`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(p.ok){let h=await p.json(),y=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${y}
310
310
  `);return}let g="";try{let h=await p.json();h.error&&(g=`: ${h.error}`)}catch{}process.stderr.write(`Daemon refused to register ${t} (HTTP ${p.status}${g}). Restart the daemon to apply.
311
- `)}catch{}}async function Kp(t){if(!t){process.stderr.write(`Usage: hydra-acp extensions remove <name>
312
- `),process.exit(2);return}await G();let e=await Vp(),n=e.extensions??{};if(!n[t]){process.stderr.write(`Extension '${t}' not found in config.
313
- `),process.exit(1);return}delete n[t],e.extensions=n,await Yp(e),process.stdout.write(`Removed extension '${t}' from ${P.config()}
314
- `);let s=await G(),r=await de(),i=fe(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let o=await fetch(`${i}/v1/extensions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(o.status===204||o.status===404){process.stdout.write(`${t}: stopped
311
+ `)}catch{}}async function Qp(t){if(!t){process.stderr.write(`Usage: hydra-acp extensions remove <name>
312
+ `),process.exit(2);return}await G();let e=await Gp(),n=e.extensions??{};if(!n[t]){process.stderr.write(`Extension '${t}' not found in config.
313
+ `),process.exit(1);return}delete n[t],e.extensions=n,await Xp(e),process.stdout.write(`Removed extension '${t}' from ${E.config()}
314
+ `);let s=await G(),r=await fe(),i=he(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let o=await fetch(`${i}/v1/extensions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(o.status===204||o.status===404){process.stdout.write(`${t}: stopped
315
315
  `);return}let a="";try{let d=await o.json();d.error&&(a=`: ${d.error}`)}catch{}process.stderr.write(`Daemon refused to unregister ${t} (HTTP ${o.status}${a}).
316
316
  `)}catch(o){process.stderr.write(`Daemon not reachable (${o.message}). Config saved.
317
- `)}}async function Vp(){let t=await ta.readFile(P.config(),"utf8");return JSON.parse(t)}async function Yp(t){await ta.writeFile(P.config(),JSON.stringify(t,null,2)+`
318
- `,{encoding:"utf8",mode:384})}async function Qp(t){await ec(t,"start")}async function Gp(t){await ec(t,"stop")}async function Xp(t){await ec(t,"restart")}async function ec(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions ${e} <name|all>
319
- `),process.exit(2);return}if(t==="all"){await EI(e);return}let n=await G(),s=await de(),r=fe(n.daemon.host,n.daemon.port,!!n.daemon.tls),i;try{i=await fetch(`${r}/v1/extensions/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
317
+ `)}}async function Gp(){let t=await ra.readFile(E.config(),"utf8");return JSON.parse(t)}async function Xp(t){await ra.writeFile(E.config(),JSON.stringify(t,null,2)+`
318
+ `,{encoding:"utf8",mode:384})}async function Zp(t){await sc(t,"start")}async function em(t){await sc(t,"stop")}async function tm(t){await sc(t,"restart")}async function sc(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions ${e} <name|all>
319
+ `),process.exit(2);return}if(t==="all"){await PI(e);return}let n=await G(),s=await fe(),r=he(n.daemon.host,n.daemon.port,!!n.daemon.tls),i;try{i=await fetch(`${r}/v1/extensions/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
320
320
  `),process.exit(1);return}if(!i.ok){let d="";try{let c=await i.json();c.error&&(d=`: ${c.error}`)}catch{}process.stderr.write(`HTTP ${i.status}${d}
321
321
  `),process.exit(1);return}let o=await i.json(),a=o.pid!=null?` pid=${o.pid}`:"";process.stdout.write(`${t}: ${o.status}${a}
322
- `)}async function EI(t){let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},i;try{let d=await fetch(`${s}/v1/extensions`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
322
+ `)}async function PI(t){let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},i;try{let d=await fetch(`${s}/v1/extensions`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
323
323
  `),process.exit(1)),i=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${s}: ${d.message}
324
324
  `),process.exit(1);return}let o=i.extensions.filter(d=>t==="start"?d.enabled&&d.status!=="running":d.status==="running");if(o.length===0){let d=t==="start"?"no enabled extensions are stopped":"no extensions are running";process.stdout.write(`Nothing to ${t}: ${d}.
325
- `);return}let a=0;for(let d of o)try{let c=await fetch(`${s}/v1/extensions/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let u="";try{let p=await c.json();p.error&&(u=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${u}
326
- `),a+=1;continue}let l=await c.json(),f=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${f}
325
+ `);return}let a=0;for(let d of o)try{let c=await fetch(`${s}/v1/extensions/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let f="";try{let p=await c.json();p.error&&(f=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${f}
326
+ `),a+=1;continue}let l=await c.json(),u=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${u}
327
327
  `)}catch(c){process.stdout.write(`${d.name}: ERROR ${c.message}
328
- `),a+=1}a>0&&process.exit(1)}async function Zp(t){let{name:e,rest:n}=lr(t);if(!e){process.stderr.write(`Usage: hydra-acp extensions log <name> [--tail N] [--follow]
329
- `),process.exit(2);return}let s=P.extensionLogFile(e);await zn(s,n,"No log file (extension never ran?)")}function PI(t){let e=[],n=[],s={},r=!0,i=0;for(;i<t.length;){let o=t[i];if(o==="--command"){let a=t[i+1];a===void 0&&(process.stderr.write(`--command requires a value
330
- `),process.exit(2)),e=MI(a),i+=2;continue}if(o==="--args"){let a=t[i+1];a===void 0&&(process.stderr.write(`--args requires a value
328
+ `),a+=1}a>0&&process.exit(1)}async function nm(t){let{name:e,rest:n}=hr(t);if(!e){process.stderr.write(`Usage: hydra-acp extensions log <name> [--tail N] [--follow]
329
+ `),process.exit(2);return}let s=E.extensionLogFile(e);await Yn(s,n,"No log file (extension never ran?)")}function MI(t){let e=[],n=[],s={},r=!0,i=0;for(;i<t.length;){let o=t[i];if(o==="--command"){let a=t[i+1];a===void 0&&(process.stderr.write(`--command requires a value
330
+ `),process.exit(2)),e=$I(a),i+=2;continue}if(o==="--args"){let a=t[i+1];a===void 0&&(process.stderr.write(`--args requires a value
331
331
  `),process.exit(2)),n=a.split(",").filter(d=>d.length>0),i+=2;continue}if(o==="--env"){let a=t[i+1];a===void 0&&(process.stderr.write(`--env requires KEY=VALUE
332
332
  `),process.exit(2));let d=a.indexOf("=");d<=0&&(process.stderr.write(`Invalid --env value '${a}': expected KEY=VALUE
333
333
  `),process.exit(2)),s[a.slice(0,d)]=a.slice(d+1),i+=2;continue}if(o==="--disabled"){r=!1,i+=1;continue}return process.stderr.write(`Unknown flag: ${o}
334
- `),process.exit(2),{command:[],args:[],env:{},enabled:!0}}return{command:e,args:n,env:s,enabled:r}}function MI(t){return t.split(/\s+/).filter(e=>e.length>0)}function $I(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function wr(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();ft();ue();import*as na from"fs/promises";wn();async function em(){let t=await G(),e=await de(),n=fe(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/transformers`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
334
+ `),process.exit(2),{command:[],args:[],env:{},enabled:!0}}return{command:e,args:n,env:s,enabled:r}}function $I(t){return t.split(/\s+/).filter(e=>e.length>0)}function _I(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function kr(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();mt();me();import*as ia from"fs/promises";In();async function sm(){let t=await G(),e=await fe(),n=he(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/transformers`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
335
335
  `),process.exit(1)),s=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${n}: ${d.message}
336
336
  `),process.exit(1);return}if(s.transformers.length===0){process.stdout.write(`No transformers configured.
337
- `);return}let r=s.transformers.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?LI(d.startedAt):"-",log:d.logPath})),i={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},o={name:br(i.name,r.map(d=>d.name)),status:br(i.status,r.map(d=>d.status)),version:br(i.version,r.map(d=>d.version)),pid:br(i.pid,r.map(d=>d.pid)),restarts:br(i.restarts,r.map(d=>d.restarts)),started:br(i.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(o.name),d.status.padEnd(o.status),d.version.padEnd(o.version),d.pid.padStart(o.pid),d.restarts.padStart(o.restarts),d.started.padEnd(o.started),d.log].join(" ");process.stdout.write(a(i)+`
337
+ `);return}let r=s.transformers.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?BI(d.startedAt):"-",log:d.logPath})),i={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},o={name:xr(i.name,r.map(d=>d.name)),status:xr(i.status,r.map(d=>d.status)),version:xr(i.version,r.map(d=>d.version)),pid:xr(i.pid,r.map(d=>d.pid)),restarts:xr(i.restarts,r.map(d=>d.restarts)),started:xr(i.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(o.name),d.status.padEnd(o.status),d.version.padEnd(o.version),d.pid.padStart(o.pid),d.restarts.padStart(o.restarts),d.started.padEnd(o.started),d.log].join(" ");process.stdout.write(a(i)+`
338
338
  `);for(let d of r)process.stdout.write(a(d)+`
339
339
  `);for(let d of s.transformers)d.failureReason&&process.stdout.write(` \u21B3 ${d.name}: ${d.failureReason}
340
- `)}async function tm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
340
+ `)}async function rm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
341
341
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid transformer name '${t}': must match [A-Za-z0-9._-]+
342
- `),process.exit(2);return}await G();let n=await am();(!n.transformers||typeof n.transformers!="object")&&(n.transformers={});let s=n.transformers;if(s[t]){process.stderr.write(`Transformer '${t}' already exists in config.
343
- `),process.exit(1);return}let{command:r,args:i,env:o,enabled:a}=OI(e),d={};r.length>0&&(d.command=r),i.length>0&&(d.args=i),Object.keys(o).length>0&&(d.env=o),a||(d.enabled=!1),s[t]=d,await dm(n),process.stdout.write(`Added transformer '${t}' to ${P.config()}
344
- `);let c=await G(),l=await de(),f=fe(c.daemon.host,c.daemon.port,!!c.daemon.tls),u={name:t,...d};try{let p=await fetch(`${f}/v1/transformers`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(u)});if(p.ok){let h=await p.json(),y=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${y}
342
+ `),process.exit(2);return}await G();let n=await lm();(!n.transformers||typeof n.transformers!="object")&&(n.transformers={});let s=n.transformers;if(s[t]){process.stderr.write(`Transformer '${t}' already exists in config.
343
+ `),process.exit(1);return}let{command:r,args:i,env:o,enabled:a}=FI(e),d={};r.length>0&&(d.command=r),i.length>0&&(d.args=i),Object.keys(o).length>0&&(d.env=o),a||(d.enabled=!1),s[t]=d,await um(n),process.stdout.write(`Added transformer '${t}' to ${E.config()}
344
+ `);let c=await G(),l=await fe(),u=he(c.daemon.host,c.daemon.port,!!c.daemon.tls),f={name:t,...d};try{let p=await fetch(`${u}/v1/transformers`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(p.ok){let h=await p.json(),y=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${y}
345
345
  `);return}let g="";try{let h=await p.json();h.error&&(g=`: ${h.error}`)}catch{}process.stderr.write(`Daemon refused to register ${t} (HTTP ${p.status}${g}). Restart the daemon to apply.
346
- `)}catch{}}async function nm(t){if(!t){process.stderr.write(`Usage: hydra-acp transformers remove <name>
347
- `),process.exit(2);return}await G();let e=await am(),n=e.transformers??{};if(!n[t]){process.stderr.write(`Transformer '${t}' not found in config.
348
- `),process.exit(1);return}delete n[t],e.transformers=n,await dm(e),process.stdout.write(`Removed transformer '${t}' from ${P.config()}
349
- `);let s=await G(),r=await de(),i=fe(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let o=await fetch(`${i}/v1/transformers/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(o.status===204||o.status===404){process.stdout.write(`${t}: stopped
346
+ `)}catch{}}async function im(t){if(!t){process.stderr.write(`Usage: hydra-acp transformers remove <name>
347
+ `),process.exit(2);return}await G();let e=await lm(),n=e.transformers??{};if(!n[t]){process.stderr.write(`Transformer '${t}' not found in config.
348
+ `),process.exit(1);return}delete n[t],e.transformers=n,await um(e),process.stdout.write(`Removed transformer '${t}' from ${E.config()}
349
+ `);let s=await G(),r=await fe(),i=he(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let o=await fetch(`${i}/v1/transformers/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(o.status===204||o.status===404){process.stdout.write(`${t}: stopped
350
350
  `);return}let a="";try{let d=await o.json();d.error&&(a=`: ${d.error}`)}catch{}process.stderr.write(`Daemon refused to unregister ${t} (HTTP ${o.status}${a}).
351
351
  `)}catch(o){process.stderr.write(`Daemon not reachable (${o.message}). Config saved.
352
- `)}}async function sm(t){await tc(t,"start")}async function rm(t){await tc(t,"stop")}async function im(t){await tc(t,"restart")}async function tc(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers ${e} <name|all>
353
- `),process.exit(2);return}if(t==="all"){await _I(e);return}let n=await G(),s=await de(),r=fe(n.daemon.host,n.daemon.port,!!n.daemon.tls),i;try{i=await fetch(`${r}/v1/transformers/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
352
+ `)}}async function om(t){await rc(t,"start")}async function am(t){await rc(t,"stop")}async function dm(t){await rc(t,"restart")}async function rc(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers ${e} <name|all>
353
+ `),process.exit(2);return}if(t==="all"){await OI(e);return}let n=await G(),s=await fe(),r=he(n.daemon.host,n.daemon.port,!!n.daemon.tls),i;try{i=await fetch(`${r}/v1/transformers/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
354
354
  `),process.exit(1);return}if(!i.ok){let d="";try{let c=await i.json();c.error&&(d=`: ${c.error}`)}catch{}process.stderr.write(`HTTP ${i.status}${d}
355
355
  `),process.exit(1);return}let o=await i.json(),a=o.pid!=null?` pid=${o.pid}`:"";process.stdout.write(`${t}: ${o.status}${a}
356
- `)}async function _I(t){let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},i;try{let d=await fetch(`${s}/v1/transformers`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
356
+ `)}async function OI(t){let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},i;try{let d=await fetch(`${s}/v1/transformers`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
357
357
  `),process.exit(1)),i=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${s}: ${d.message}
358
358
  `),process.exit(1);return}let o=i.transformers.filter(d=>t==="start"?d.enabled&&d.status!=="running":d.status==="running");if(o.length===0){let d=t==="start"?"no enabled transformers are stopped":"no transformers are running";process.stdout.write(`Nothing to ${t}: ${d}.
359
- `);return}let a=0;for(let d of o)try{let c=await fetch(`${s}/v1/transformers/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let u="";try{let p=await c.json();p.error&&(u=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${u}
360
- `),a+=1;continue}let l=await c.json(),f=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${f}
359
+ `);return}let a=0;for(let d of o)try{let c=await fetch(`${s}/v1/transformers/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let f="";try{let p=await c.json();p.error&&(f=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${f}
360
+ `),a+=1;continue}let l=await c.json(),u=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${u}
361
361
  `)}catch(c){process.stdout.write(`${d.name}: ERROR ${c.message}
362
- `),a+=1}a>0&&process.exit(1)}async function om(t){let{name:e,rest:n}=lr(t);if(!e){process.stderr.write(`Usage: hydra-acp transformers log <name> [--tail N] [--follow]
363
- `),process.exit(2);return}let s=P.transformerLogFile(e);await zn(s,n,"No log file (transformer never ran?)")}async function am(){let t=await na.readFile(P.config(),"utf8");return JSON.parse(t)}async function dm(t){await na.writeFile(P.config(),JSON.stringify(t,null,2)+`
364
- `,{encoding:"utf8",mode:384})}function OI(t){let e=[],n=[],s={},r=!0,i=0;for(;i<t.length;){let o=t[i];if(o==="--command"){let a=t[i+1];a===void 0&&(process.stderr.write(`--command requires a value
365
- `),process.exit(2)),e=FI(a),i+=2;continue}if(o==="--args"){let a=t[i+1];a===void 0&&(process.stderr.write(`--args requires a value
362
+ `),a+=1}a>0&&process.exit(1)}async function cm(t){let{name:e,rest:n}=hr(t);if(!e){process.stderr.write(`Usage: hydra-acp transformers log <name> [--tail N] [--follow]
363
+ `),process.exit(2);return}let s=E.transformerLogFile(e);await Yn(s,n,"No log file (transformer never ran?)")}async function lm(){let t=await ia.readFile(E.config(),"utf8");return JSON.parse(t)}async function um(t){await ia.writeFile(E.config(),JSON.stringify(t,null,2)+`
364
+ `,{encoding:"utf8",mode:384})}function FI(t){let e=[],n=[],s={},r=!0,i=0;for(;i<t.length;){let o=t[i];if(o==="--command"){let a=t[i+1];a===void 0&&(process.stderr.write(`--command requires a value
365
+ `),process.exit(2)),e=LI(a),i+=2;continue}if(o==="--args"){let a=t[i+1];a===void 0&&(process.stderr.write(`--args requires a value
366
366
  `),process.exit(2)),n=a.split(",").filter(d=>d.length>0),i+=2;continue}if(o==="--env"){let a=t[i+1];a===void 0&&(process.stderr.write(`--env requires KEY=VALUE
367
367
  `),process.exit(2));let d=a.indexOf("=");d<=0&&(process.stderr.write(`Invalid --env value '${a}': expected KEY=VALUE
368
368
  `),process.exit(2)),s[a.slice(0,d)]=a.slice(d+1),i+=2;continue}if(o==="--disabled"){r=!1,i+=1;continue}return process.stderr.write(`Unknown flag: ${o}
369
- `),process.exit(2),{command:[],args:[],env:{},enabled:!1}}return{command:e,args:n,env:s,enabled:r}}function FI(t){return t.split(/\s+/).filter(e=>e.length>0)}function LI(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function br(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();ft();ue();import*as fm from"fs/promises";wn();async function pm(){let t=await G(),e=await de(),n=fe(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let c=await fetch(`${n}/v1/agents`,{headers:{Authorization:`Bearer ${e}`}});c.ok||(process.stderr.write(`Daemon returned HTTP ${c.status}
369
+ `),process.exit(2),{command:[],args:[],env:{},enabled:!1}}return{command:e,args:n,env:s,enabled:r}}function LI(t){return t.split(/\s+/).filter(e=>e.length>0)}function BI(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function xr(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();mt();me();import*as hm from"fs/promises";In();async function gm(){let t=await G(),e=await fe(),n=he(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let c=await fetch(`${n}/v1/agents`,{headers:{Authorization:`Bearer ${e}`}});c.ok||(process.stderr.write(`Daemon returned HTTP ${c.status}
370
370
  `),process.exit(1)),s=await c.json()}catch(c){process.stderr.write(`Could not reach daemon at ${n}: ${c.message}
371
371
  `),process.exit(1);return}if(s.agents.length===0){process.stdout.write(`No agents in registry.
372
- `);return}let r=s.agents.map(c=>({id:c.id,name:c.name,version:c.version,source:c.source??"registry",distributions:c.distributions.join(","),installed:c.installed,description:c.description??""})),i={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},o={id:bn(i.id,r.map(c=>c.id)),name:bn(i.name,r.map(c=>c.name)),version:bn(i.version,r.map(c=>c.version)),source:bn(i.source,r.map(c=>c.source)),distributions:bn(i.distributions,r.map(c=>c.distributions)),installed:bn(i.installed,r.map(c=>c.installed))},a=c=>[c.id.padEnd(o.id),c.name.padEnd(o.name),c.version.padEnd(o.version),c.source.padEnd(o.source),c.distributions.padEnd(o.distributions),c.installed.padEnd(o.installed),c.description].join(" ");process.stdout.write(a(i)+`
372
+ `);return}let r=s.agents.map(c=>({id:c.id,name:c.name,version:c.version,source:c.source??"registry",distributions:c.distributions.join(","),installed:c.installed,description:c.description??""})),i={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},o={id:Sn(i.id,r.map(c=>c.id)),name:Sn(i.name,r.map(c=>c.name)),version:Sn(i.version,r.map(c=>c.version)),source:Sn(i.source,r.map(c=>c.source)),distributions:Sn(i.distributions,r.map(c=>c.distributions)),installed:Sn(i.installed,r.map(c=>c.installed))},a=c=>[c.id.padEnd(o.id),c.name.padEnd(o.name),c.version.padEnd(o.version),c.source.padEnd(o.source),c.distributions.padEnd(o.distributions),c.installed.padEnd(o.installed),c.description].join(" ");process.stdout.write(a(i)+`
373
373
  `);for(let c of r)process.stdout.write(a(c)+`
374
- `);let d=s.fetchedAt!==void 0?` (synced ${BI(Date.now()-s.fetchedAt)} ago)`:"";process.stdout.write(`
374
+ `);let d=s.fetchedAt!==void 0?` (synced ${NI(Date.now()-s.fetchedAt)} ago)`:"";process.stdout.write(`
375
375
  Registry version: ${s.version}${d}
376
- `)}function BI(t){if(t<0)return"just now";let e=Math.floor(t/1e3);if(e<60)return"just now";let n=Math.floor(e/60);if(n<60)return`${n} minute${n===1?"":"s"}`;let s=Math.floor(n/60);if(s<24)return`${s} hour${s===1?"":"s"}`;let r=Math.floor(s/24);return`${r} day${r===1?"":"s"}`}async function sc(t){let e=await G();if(e.agents[t]!==void 0)return;let n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let i=await fetch(`${s}/v1/agents`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)return;r=(await i.json()).agents.map(a=>a.id)}catch{return}r.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
377
- `),process.exit(2))}async function mm(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
378
- `),process.exit(2);return}let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls);process.stdout.write(`Installing ${t}\u2026
376
+ `)}function NI(t){if(t<0)return"just now";let e=Math.floor(t/1e3);if(e<60)return"just now";let n=Math.floor(e/60);if(n<60)return`${n} minute${n===1?"":"s"}`;let s=Math.floor(n/60);if(s<24)return`${s} hour${s===1?"":"s"}`;let r=Math.floor(s/24);return`${r} day${r===1?"":"s"}`}async function oc(t){let e=await G();if(e.agents[t]!==void 0)return;let n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let i=await fetch(`${s}/v1/agents`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)return;r=(await i.json()).agents.map(a=>a.id)}catch{return}r.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
377
+ `),process.exit(2))}async function ym(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
378
+ `),process.exit(2);return}let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls);process.stdout.write(`Installing ${t}\u2026
379
379
  `);let r;try{let i=await fetch(`${s}/v1/agents/${encodeURIComponent(t)}/install`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!i.ok){let o=`HTTP ${i.status}`;try{let a=await i.json();a.error&&(o=a.error)}catch{}process.stderr.write(`hydra agent install ${t}: ${o}
380
380
  `),process.exit(1)}r=await i.json()}catch(i){process.stderr.write(`Could not reach daemon at ${s}: ${i.message}
381
381
  `),process.exit(1);return}if(!r.installed){process.stdout.write(`${r.agentId} (${r.version}, ${r.distribution}): ${r.message??"nothing to install"}
382
382
  `);return}process.stdout.write(`Installed ${r.agentId} (${r.version}, ${r.distribution})
383
383
  `),r.command&&process.stdout.write(` \u2192 ${r.command}
384
- `)}async function hm(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
385
- `),process.exit(2);return}let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let c=await fetch(`${s}/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!c.ok){let l=`HTTP ${c.status}`;try{let f=await c.json();f.error&&(l=f.error)}catch{}process.stderr.write(`hydra agent sync ${t}: ${l}
384
+ `)}async function wm(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
385
+ `),process.exit(2);return}let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let c=await fetch(`${s}/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!c.ok){let l=`HTTP ${c.status}`;try{let u=await c.json();u.error&&(l=u.error)}catch{}process.stderr.write(`hydra agent sync ${t}: ${l}
386
386
  `),process.exit(1)}r=await c.json()}catch(c){process.stderr.write(`Could not reach daemon at ${s}: ${c.message}
387
387
  `),process.exit(1);return}if(r.synced.length===0){process.stdout.write(`Nothing new to sync (${r.skipped} already tracked).
388
- `);return}let i=r.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),o={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},a={id:bn(o.id,i.map(c=>c.id)),upstream:bn(o.upstream,i.map(c=>c.upstream)),cwd:bn(o.cwd,i.map(c=>c.cwd))},d=c=>[c.id.padEnd(a.id),c.upstream.padEnd(a.upstream),c.cwd.padEnd(a.cwd),c.title].join(" ");process.stdout.write(d(o)+`
388
+ `);return}let i=r.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),o={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},a={id:Sn(o.id,i.map(c=>c.id)),upstream:Sn(o.upstream,i.map(c=>c.upstream)),cwd:Sn(o.cwd,i.map(c=>c.cwd))},d=c=>[c.id.padEnd(a.id),c.upstream.padEnd(a.upstream),c.cwd.padEnd(a.cwd),c.title].join(" ");process.stdout.write(d(o)+`
389
389
  `);for(let c of i)process.stdout.write(d(c)+`
390
390
  `);process.stdout.write(`
391
391
  Synced ${r.synced.length} session(s); skipped ${r.skipped} already tracked.
392
- `)}async function gm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
393
- `),process.exit(2);return}let n=P.agentLogFile(t);await zn(n,e,"No log file (agent never ran?)")}async function ym(t,e){let n=await G(),s=await de(),r=fe(n.daemon.host,n.daemon.port,!!n.daemon.tls);if(!t){let l=await lm(r,s)??nc(await um());process.stdout.write(`${cm(l)}
394
- `);return}let i;try{let c=await fetch(`${r}/v1/agents`,{headers:{Authorization:`Bearer ${s}`}});c.ok&&(i=(await c.json()).agents.map(f=>f.id))}catch{}if(!(n.agents[t]!==void 0)&&i!==void 0&&!i.includes(t)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${i.join(", ")}
395
- `),process.exit(1);return}e!==void 0?await bl(t,e):await Ui(t);let a=nc(await um());e!==void 0&&t!==a.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
396
- `),process.stdout.write(`${cm(a)}
397
- `);let d=await lm(r,s);d!==void 0&&(d.agent===a.agent&&d.model===a.model||process.stdout.write(`Daemon still has ${wm(d)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
398
- `))}function cm(t){return`Default agent is ${wm(t)}`}function wm(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function nc(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function lm(t,e){try{let n=await fetch(`${t}/v1/config`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return;let s=await n.json();return nc(s)}catch{return}}async function um(){let t=await fm.readFile(P.config(),"utf8");return JSON.parse(t)}async function rc(){let t=await G(),e=await de(),n=fe(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let r=await fetch(`${n}/v1/registry/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});r.ok||(process.stderr.write(`Daemon returned HTTP ${r.status}
392
+ `)}async function bm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
393
+ `),process.exit(2);return}let n=E.agentLogFile(t);await Yn(n,e,"No log file (agent never ran?)")}async function vm(t,e){let n=await G(),s=await fe(),r=he(n.daemon.host,n.daemon.port,!!n.daemon.tls);if(!t){let l=await pm(r,s)??ic(await mm());process.stdout.write(`${fm(l)}
394
+ `);return}let i;try{let c=await fetch(`${r}/v1/agents`,{headers:{Authorization:`Bearer ${s}`}});c.ok&&(i=(await c.json()).agents.map(u=>u.id))}catch{}if(!(n.agents[t]!==void 0)&&i!==void 0&&!i.includes(t)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${i.join(", ")}
395
+ `),process.exit(1);return}e!==void 0?await Sl(t,e):await Wi(t);let a=ic(await mm());e!==void 0&&t!==a.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
396
+ `),process.stdout.write(`${fm(a)}
397
+ `);let d=await pm(r,s);d!==void 0&&(d.agent===a.agent&&d.model===a.model||process.stdout.write(`Daemon still has ${Im(d)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
398
+ `))}function fm(t){return`Default agent is ${Im(t)}`}function Im(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function ic(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function pm(t,e){try{let n=await fetch(`${t}/v1/config`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return;let s=await n.json();return ic(s)}catch{return}}async function mm(){let t=await hm.readFile(E.config(),"utf8");return JSON.parse(t)}async function ac(){let t=await G(),e=await fe(),n=he(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let r=await fetch(`${n}/v1/registry/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});r.ok||(process.stderr.write(`Daemon returned HTTP ${r.status}
399
399
  `),process.exit(1)),s=await r.json()}catch(r){process.stderr.write(`Could not reach daemon at ${n}: ${r.message}
400
400
  `),process.exit(1);return}process.stdout.write(`Refreshed registry: ${s.agentCount} agents (version ${s.version})
401
- `)}async function bm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
402
- `),process.exit(2);return}await vl(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
401
+ `)}async function Sm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
402
+ `),process.exit(2);return}await kl(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
403
403
  `):process.stdout.write(`Pinned ${t} to ${e}.
404
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function vm(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
404
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function km(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
405
405
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
406
- `),process.exit(2);return}let{command:n,args:s,env:r}=NI(e),i={};n!==void 0&&(i.command=n),s.length>0&&(i.args=s),Object.keys(r).length>0&&(i.env=r),await Oa(t,i);let o=n??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${o}${s.length>0?" "+s.join(" "):""}
407
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Im(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
408
- `),process.exit(2);return}await Oa(t,void 0),process.stdout.write(`Removed local agent ${t}.
409
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}function NI(t){let e,n=[],s={},r=0;for(;r<t.length;){let i=t[r];if(i==="--command"){let o=t[r+1];o===void 0&&(process.stderr.write(`--command requires a value
406
+ `),process.exit(2);return}let{command:n,args:s,env:r}=DI(e),i={};n!==void 0&&(i.command=n),s.length>0&&(i.args=s),Object.keys(r).length>0&&(i.env=r),await Ba(t,i);let o=n??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${o}${s.length>0?" "+s.join(" "):""}
407
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function xm(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
408
+ `),process.exit(2);return}await Ba(t,void 0),process.stdout.write(`Removed local agent ${t}.
409
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}function DI(t){let e,n=[],s={},r=0;for(;r<t.length;){let i=t[r];if(i==="--command"){let o=t[r+1];o===void 0&&(process.stderr.write(`--command requires a value
410
410
  `),process.exit(2)),e=o,r+=2;continue}if(i==="--args"){let o=t[r+1];o===void 0&&(process.stderr.write(`--args requires a value
411
411
  `),process.exit(2)),n=o.split(",").filter(a=>a.length>0),r+=2;continue}if(i==="--env"){let o=t[r+1];o===void 0&&(process.stderr.write(`--env requires KEY=VALUE
412
412
  `),process.exit(2));let a=o.indexOf("=");a<=0&&(process.stderr.write(`Invalid --env value '${o}': expected KEY=VALUE
413
413
  `),process.exit(2)),s[o.slice(0,a)]=o.slice(a+1),r+=2;continue}return process.stderr.write(`Unknown flag: ${i}
414
- `),process.exit(2),{command:void 0,args:[],env:{}}}return{command:e,args:n,env:s}}async function ic(t){await Il(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
415
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function bn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();ft();Da();wn();async function Sm(t){let e=Os(t,"force");if(await Lo()&&!e){let r=await Us("Current password: ");await Bo(r)||(process.stderr.write(`Wrong password.
416
- `),process.exit(1))}let n=await Us("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
- `),process.exit(2));let s=await Us("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
- `),process.exit(1)),await Jf(n),process.stdout.write(`Password set.
419
- `)}async function km(){let t=await G(),e=await de(),n=fe(t.daemon.host,t.daemon.port,!!t.daemon.tls),s=await fetch(`${n}/v1/auth/sessions`,{headers:{Authorization:`Bearer ${e}`}});s.ok||(process.stderr.write(`Daemon returned HTTP ${s.status}
414
+ `),process.exit(2),{command:void 0,args:[],env:{}}}return{command:e,args:n,env:s}}async function dc(t){await xl(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
415
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Sn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Oe();mt();ja();In();async function Am(t){let e=Ds(t,"force");if(await Do()&&!e){let r=await Js("Current password: ");await Ho(r)||(process.stderr.write(`Wrong password.
416
+ `),process.exit(1))}let n=await Js("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
+ `),process.exit(2));let s=await Js("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
+ `),process.exit(1)),await Yf(n),process.stdout.write(`Password set.
419
+ `)}async function Cm(){let t=await G(),e=await fe(),n=he(t.daemon.host,t.daemon.port,!!t.daemon.tls),s=await fetch(`${n}/v1/auth/sessions`,{headers:{Authorization:`Bearer ${e}`}});s.ok||(process.stderr.write(`Daemon returned HTTP ${s.status}
420
420
  `),process.exit(1));let r=await s.json();if(r.sessions.length===0){process.stdout.write(`No active session tokens.
421
- `);return}let i={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},o=r.sessions.map(c=>({id:c.id,label:c.label??"-",createdAt:c.createdAt,expiresAt:c.expiresAt,lastUsedAt:c.lastUsedAt})),a={id:sa(i.id,o.map(c=>c.id)),label:sa(i.label,o.map(c=>c.label)),createdAt:sa(i.createdAt,o.map(c=>c.createdAt)),expiresAt:sa(i.expiresAt,o.map(c=>c.expiresAt))},d=c=>[c.id.padEnd(a.id),c.label.padEnd(a.label),c.createdAt.padEnd(a.createdAt),c.expiresAt.padEnd(a.expiresAt),c.lastUsedAt].join(" ");process.stdout.write(d(i)+`
421
+ `);return}let i={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},o=r.sessions.map(c=>({id:c.id,label:c.label??"-",createdAt:c.createdAt,expiresAt:c.expiresAt,lastUsedAt:c.lastUsedAt})),a={id:oa(i.id,o.map(c=>c.id)),label:oa(i.label,o.map(c=>c.label)),createdAt:oa(i.createdAt,o.map(c=>c.createdAt)),expiresAt:oa(i.expiresAt,o.map(c=>c.expiresAt))},d=c=>[c.id.padEnd(a.id),c.label.padEnd(a.label),c.createdAt.padEnd(a.createdAt),c.expiresAt.padEnd(a.expiresAt),c.lastUsedAt].join(" ");process.stdout.write(d(i)+`
422
422
  `);for(let c of o)process.stdout.write(d(c)+`
423
- `)}async function xm(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
424
- `),process.exit(2));let e=await G(),n=await de(),s=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/auth/sessions/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(r.status===204){process.stdout.write(`Revoked ${t}
423
+ `)}async function Rm(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
424
+ `),process.exit(2));let e=await G(),n=await fe(),s=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/auth/sessions/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(r.status===204){process.stdout.write(`Revoked ${t}
425
425
  `);return}r.status===404&&(process.stderr.write(`No session token with id ${t}
426
426
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${r.status}
427
- `),process.exit(1)}function sa(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Kn from"fs";Oe();js();dr();oc();nt();var ra=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(dc(e)){let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(ac(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!ac(e)&&!dc(e)&&"method"in e){if(e.method==="session/update"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0,p=typeof f.update?.messageId=="string"?f.update.messageId:void 0;u&&p&&this.lastMessageIds.set(u,p)}return}if(ac(e)){if(e.method==="session/request_permission"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0;if(u){let p=f.toolCall,g=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:u,toolCallId:g,params:f};this.pendingPermissions.set(e.id,h),g&&this.pendingPermissionsByToolCall.set(g,h)}}return}if(!dc(e))return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=kt(i),a=o.upstreamSessionId,d=o.agentId,c="";(n.kind==="new"||n.kind==="load")&&(c=n.data.cwd);let l=o.cwd??c;!a||!d||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:d,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);return n&&this.deletePendingPermission(n),n}deletePendingPermission(e){this.pendingPermissions.delete(e.requestId),e.toolCallId&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}};function ac(t){return"method"in t&&"id"in t&&t.id!==void 0}function dc(t){return!("method"in t)&&"id"in t}oa();$t();ue();Wi();import{writeFileSync as KI}from"fs";var VI=t=>{KI("/proc/self/comm",t)};function Ir(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??VI;try{s(e.commName??Fn())}catch{}}function Sr(t,e=Fn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function da(t){Ir(Sr(process.argv.slice(2)),{commName:"hydra-shim"});let e=await G(),n=t.target??await Qt(e);n.isLocal&&!t.target&&await or(e);let s=new ra,r=eo(process.stdin,process.stdout),i=n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new vr({url:i,subprotocols:o,onConnect:async d=>{if(d)return;s.clearPending(),await eS(s,r);let c=s.list();if(c.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${c.length} session(s)
428
- `);for(let l of c)await tS(a,l,s.lastMessageId(l.sessionId))}}});YI({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(d=>{d&&process.stderr.write(`hydra-acp: ${d.message}
429
- `),r.close(),process.exit(d?1:0)}),r.onClose(()=>{a.close(),process.exit(0)}),await a.start()}function YI({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(Pm("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&iS(i)){e.send({jsonrpc:"2.0",id:i.id,result:ws(i.params)});return}QI(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(Pm("client\u2192daemon",i),s.observeFromClient(i),sS(i)){e.send(rS(i));return}if(nS(i)){if(t.sessionId){e.send(oS(i,t.sessionId));return}let o=i;t.agentId&&(o=aa(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=aa(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=aa(o,{title:r.name}),r.used=!0),t.model&&(o=aa(o,{model:t.model})),e.send(o);return}e.send(i)})}function QI(t,e,n){let s=GI(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=ZI(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function GI(t){if(!XI(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function XI(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function ZI(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function eS(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
430
- `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function tS(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
427
+ `),process.exit(1)}function oa(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Gn from"fs";Oe();Ks();pr();cc();st();var aa=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(uc(e)){let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(lc(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!lc(e)&&!uc(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(lc(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,g=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:f,toolCallId:g,params:u};this.pendingPermissions.set(e.id,h),g&&this.pendingPermissionsByToolCall.set(g,h)}}return}if(!uc(e))return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=xt(i),a=o.upstreamSessionId,d=o.agentId,c="";(n.kind==="new"||n.kind==="load")&&(c=n.data.cwd);let l=o.cwd??c;!a||!d||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:d,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);return n&&this.deletePendingPermission(n),n}deletePendingPermission(e){this.pendingPermissions.delete(e.requestId),e.toolCallId&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}};function lc(t){return"method"in t&&"id"in t&&t.id!==void 0}function uc(t){return!("method"in t)&&"id"in t}ca();Mt();me();Ki();import{writeFileSync as VI}from"fs";var YI=t=>{VI("/proc/self/comm",t)};function Cr(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??YI;try{s(e.commName??Dn())}catch{}}function Rr(t,e=Dn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function ua(t){Cr(Rr(process.argv.slice(2)),{commName:"hydra-shim"});let e=await G(),n=t.target??await Xt(e);n.isLocal&&!t.target&&await ur(e);let s=new aa,r=so(process.stdin,process.stdout),i=n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new Ar({url:i,subprotocols:o,onConnect:async d=>{if(d)return;s.clearPending(),await tS(s,r);let c=s.list();if(c.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${c.length} session(s)
428
+ `);for(let l of c)await nS(a,l,s.lastMessageId(l.sessionId))}}});QI({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(d=>{d&&process.stderr.write(`hydra-acp: ${d.message}
429
+ `),r.close(),process.exit(d?1:0)}),r.onClose(()=>{a.close(),process.exit(0)}),await a.start()}function QI({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(_m("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&oS(i)){e.send({jsonrpc:"2.0",id:i.id,result:Ss(i.params)});return}GI(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(_m("client\u2192daemon",i),s.observeFromClient(i),rS(i)){e.send(iS(i));return}if(sS(i)){if(t.sessionId){e.send(aS(i,t.sessionId));return}let o=i;t.agentId&&(o=la(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=la(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=la(o,{title:r.name}),r.used=!0),t.model&&(o=la(o,{model:t.model})),e.send(o);return}e.send(i)})}function GI(t,e,n){let s=XI(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=eS(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function XI(t){if(!ZI(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function ZI(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function eS(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function tS(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
430
+ `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function nS(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
431
431
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
432
- `)}}function nS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function sS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function rS(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:ce}}}}function iS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function oS(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var aS=25*1024*1024,Em=!1,bs=null;function Pm(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Em){Em=!0;try{bs=P.shimWireLogFile(),Kn.mkdirSync(P.home(),{recursive:!0});let n=Kn.statSync(bs,{throwIfNoEntry:!1});n&&n.size>aS&&Kn.renameSync(bs,`${bs}.1`)}catch{bs=null}}if(bs)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
433
- `;Kn.appendFile(bs,n,()=>{})}catch{}}}function aa(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Ks();si();Oe();js();dr();Un();nt();$t();oa();import{mkdtempSync as wS,rmSync as bS}from"fs";import{tmpdir as vS}from"os";import{join as IS}from"path";import{WebSocket as SS}from"ws";function Mm(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}yr();import dS from"chalk";import cS from"strip-ansi";var ca=new dS.Instance({level:3});function $m(t,e){if(t.length===0)return"";let n=gr(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(lS(i,e));let r=s.join(`
432
+ `)}}function sS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function rS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function iS(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:pe}}}}function oS(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function aS(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var dS=25*1024*1024,$m=!1,ks=null;function _m(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!$m){$m=!0;try{ks=E.shimWireLogFile(),Gn.mkdirSync(E.home(),{recursive:!0});let n=Gn.statSync(ks,{throwIfNoEntry:!1});n&&n.size>dS&&Gn.renameSync(ks,`${ks}.1`)}catch{ks=null}}if(ks)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
433
+ `;Gn.appendFile(ks,n,()=>{})}catch{}}}function la(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Xs();ci();Oe();Ks();pr();zn();st();Mt();ca();import{mkdtempSync as bS,rmSync as vS}from"fs";import{tmpdir as IS}from"os";import{join as SS}from"path";import{WebSocket as kS}from"ws";function Om(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}Sr();import cS from"chalk";import lS from"strip-ansi";var fa=new cS.Instance({level:3});function Fm(t,e){if(t.length===0)return"";let n=Ir(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(uS(i,e));let r=s.join(`
434
434
  `);return r.endsWith(`
435
435
  `)||(r+=`
436
- `),r}function lS(t,e){let n=gS(t.body,e);return e==="ansi"?n=yS(n,t.bodyStyle):n=cS(n),n}var uS="\x1B[1m",fS="\x1B[96m",pS="\x1B[93m",mS="\x1B[0m",hS="\0";function gS(t,e){let n=t.replace(/\^\^/g,hS);return e==="ansi"&&(n=n.replace(/\^\+/g,uS).replace(/\^C/g,fS).replace(/\^Y/g,pS).replace(/\^:/g,mS)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function yS(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return ca.bold.yellowBright(t);case"heading-2":return ca.bold.cyanBright(t);case"heading-3":return ca.bold(t);case"dim":return ca.dim(t);default:return t}}var kS=1*1024*1024,_m="mcp__hydra-acp-stdin__";function Om(t,e){return{sessionId:t,prompt:e,_meta:{[pt]:{ancillary:!0}}}}function xS(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function AS(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(_m))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(_m))}async function Fm(t){if(Ir(Sr(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
437
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let d=wS(IS(vS(),"hydra-cat-"));t.cwd=d,t.detach||process.on("exit",()=>{try{bS(d,{recursive:!0,force:!0})}catch{}})}let e=await G(),n=t.target??await Qt(e);n.isLocal&&!t.target&&await or(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await MS(n.wsUrl,s),i=qn(r),o=new Mt(i),a=await RS({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:d=>process.stdout.write(d),stderr:d=>{process.stderr.write(d)},streamClient:CS(n.baseUrl,n.token)});process.exit(a.exitCode)}function CS(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function RS(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,d=i?"ansi":"plain",c=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async te=>n.dangerouslySkipPermissions?ws(te):AS(te)?ws(te):Cm(te));try{await e.request("initialize",{protocolVersion:tt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:ps,version:ce}})}catch{}let f=await PS(e,n,l),u=!1,p=!0,g="",h=0,y=te=>{te.length!==0&&(o(te),p=te.charCodeAt(te.length-1)===10,u=!0)},v=()=>{if(c||g.length===0)return;let te=$m(g,d);if(g="",te.length===0)return;let pe=h>0?`
438
- `:"";y(pe+te),h+=1},b=()=>{v(),u&&!p&&y(`
439
- `),u=!1};e.onNotification("session/update",te=>{let pe=te?.update,H=gn(pe,{cwd:n.cwd});if(H){if(H.kind==="agent-text"){c?y(H.text):g+=H.text;return}if(H.kind==="turn-complete"){b();return}switch(H.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":v();return;default:return}}});let x=!1,C=async te=>{let pe=[];if(n.prompt&&!x&&pe.push({type:"text",text:n.prompt}),te.length>0&&pe.push({type:"text",text:te}),pe.length!==0){try{await e.request("session/prompt",Om(f,pe)),x=!0}catch(H){a(`hydra-acp cat: prompt failed: ${H.message}
440
- `);return}b()}},F=0,z,J=new Promise(te=>{z=te}),X=!1,D=async te=>{X||(X=!0,b(),n.detach||e.request("session/detach",{sessionId:f}).catch(()=>{}),await e.close().catch(()=>{}),z({exitCode:te}))};e.onClose(te=>{te&&(a(`hydra-acp cat: ${te.message}
441
- `),F=1),X||(X=!0,b(),z({exitCode:F}))});let $=[],W=!1,K=!1,ee=async()=>{if(!W){W=!0;try{for(;$.length>0;){let te=$.shift();if(te===void 0)break;await C(te)}}finally{W=!1,K&&$.length===0&&await D(F)}}};if(r&&!n.sessionId)return n.prompt&&await C(""),await D(0),J;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),TS({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:C,onEof:()=>{K=!0,!W&&$.length===0&&D(F)},onError:te=>{a(`hydra-acp cat: stdin error: ${te.message}
442
- `),F=1,K=!0,!W&&$.length===0&&D(F)},onPromptFailed:te=>{a(`hydra-acp cat: ${te.message}
443
- `),F=1,K=!0,!W&&$.length===0&&D(F)}}),J;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let te=Mm({scheduleFlushCheck:pe=>{let H=setImmediate(pe);return()=>clearImmediate(H)},onChunk:pe=>{$.push(pe),ee()}});return s.on("data",pe=>{te.feed(typeof pe=="string"?pe:pe.toString("utf8"))}),s.on("end",()=>{te.eof(),K=!0,!W&&$.length===0&&D(F)}),s.on("error",pe=>{a(`hydra-acp cat: stdin error: ${pe.message}
444
- `),F=1,K=!0,!W&&$.length===0&&D(F)}),J}let ke="";return s.on("data",te=>{ke+=typeof te=="string"?te:te.toString("utf8")}),s.on("end",()=>{K=!0,ke.length>0&&$.push(ke),ee()}),s.on("error",te=>{a(`hydra-acp cat: stdin error: ${te.message}
445
- `),F=1,K=!0,!W&&$.length===0&&D(F)}),J}function TS(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,d=r.streamThreshold??kS,c="undecided",l=Buffer.alloc(0),f=!1,u=Promise.resolve(),p=(y,v)=>{let b=y.toString("base64");u=u.then(()=>n.write(s,b,v)).catch(x=>{o(`hydra-acp cat: stdin write failed: ${x.message}
446
- `)})},g=async()=>{c="inline";let y=l.toString("utf8");l=Buffer.alloc(0);try{await a(y)}catch(v){t.onPromptFailed(v);return}t.onEof()},h=async()=>{c="file";let y;try{let x={mode:"memory"};r.streamBufferBytes!==void 0&&(x.capacityBytes=r.streamBufferBytes),y=await n.open(s,x)}catch(x){t.onPromptFailed(new Error(`stdin/open failed: ${x.message}`));return}l.length>0&&(p(l,!1),l=Buffer.alloc(0)),await u.catch(()=>{});let v=ES(r.prompt,y.capacityBytes);e.request("session/prompt",Om(s,[{type:"text",text:v}])).catch(x=>{t.onPromptFailed(new Error(`prompt failed: ${x.message}`))}).then(()=>{f||p(Buffer.alloc(0),!0),t.onEof()})};i.on("data",y=>{let v=typeof y=="string"?Buffer.from(y,"utf8"):y;if(c==="undecided"){l=Buffer.concat([l,v]),l.length>d&&h();return}if(c==="file"){p(v,!1);return}l=Buffer.concat([l,v])}),i.on("end",()=>{if(f=!0,c==="undecided"){g();return}c==="file"&&p(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function ES(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
436
+ `),r}function uS(t,e){let n=yS(t.body,e);return e==="ansi"?n=wS(n,t.bodyStyle):n=lS(n),n}var fS="\x1B[1m",pS="\x1B[96m",mS="\x1B[93m",hS="\x1B[0m",gS="\0";function yS(t,e){let n=t.replace(/\^\^/g,gS);return e==="ansi"&&(n=n.replace(/\^\+/g,fS).replace(/\^C/g,pS).replace(/\^Y/g,mS).replace(/\^:/g,hS)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function wS(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return fa.bold.yellowBright(t);case"heading-2":return fa.bold.cyanBright(t);case"heading-3":return fa.bold(t);case"dim":return fa.dim(t);default:return t}}var xS=1*1024*1024,Lm="mcp__hydra-acp-stdin__";function Bm(t,e){return{sessionId:t,prompt:e,_meta:{[ht]:{ancillary:!0}}}}function AS(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function CS(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(Lm))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Lm))}async function Nm(t){if(Cr(Rr(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
437
+ `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let d=bS(SS(IS(),"hydra-cat-"));t.cwd=d,t.detach||process.on("exit",()=>{try{vS(d,{recursive:!0,force:!0})}catch{}})}let e=await G(),n=t.target??await Xt(e);n.isLocal&&!t.target&&await ur(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await $S(n.wsUrl,s),i=Kn(r),o=new Pt(i),a=await TS({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:d=>process.stdout.write(d),stderr:d=>{process.stderr.write(d)},streamClient:RS(n.baseUrl,n.token)});process.exit(a.exitCode)}function RS(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function TS(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,d=i?"ansi":"plain",c=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async K=>n.dangerouslySkipPermissions?Ss(K):CS(K)?Ss(K):Em(K));try{await e.request("initialize",{protocolVersion:nt,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:ys,version:pe}})}catch{}let u=await MS(e,n,l),f=!1,p=!0,g="",h=0,y=K=>{K.length!==0&&(o(K),p=K.charCodeAt(K.length-1)===10,f=!0)},I=()=>{if(c||g.length===0)return;let K=Fm(g,d);if(g="",K.length===0)return;let Ce=h>0?`
438
+ `:"";y(Ce+K),h+=1},b=()=>{I(),f&&!p&&y(`
439
+ `),f=!1};e.onNotification("session/update",K=>{let Ce=K?.update,X=bn(Ce,{cwd:n.cwd});if(X){if(X.kind==="agent-text"){c?y(X.text):g+=X.text;return}if(X.kind==="turn-complete"){b();return}switch(X.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":I();return;default:return}}});let x=!1,M=async K=>{let Ce=[];if(n.prompt&&!x&&Ce.push({type:"text",text:n.prompt}),K.length>0&&Ce.push({type:"text",text:K}),Ce.length!==0){try{await e.request("session/prompt",Bm(u,Ce)),x=!0}catch(X){a(`hydra-acp cat: prompt failed: ${X.message}
440
+ `);return}b()}},_=0,Q,W=new Promise(K=>{Q=K}),z=!1,$=async K=>{z||(z=!0,b(),n.detach||e.request("session/detach",{sessionId:u}).catch(()=>{}),await e.close().catch(()=>{}),Q({exitCode:K}))};e.onClose(K=>{K&&(a(`hydra-acp cat: ${K.message}
441
+ `),_=1),z||(z=!0,b(),Q({exitCode:_}))});let D=[],j=!1,Z=!1,ie=async()=>{if(!j){j=!0;try{for(;D.length>0;){let K=D.shift();if(K===void 0)break;await M(K)}}finally{j=!1,Z&&D.length===0&&await $(_)}}};if(r&&!n.sessionId)return n.prompt&&await M(""),await $(0),W;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),ES({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:M,onEof:()=>{Z=!0,!j&&D.length===0&&$(_)},onError:K=>{a(`hydra-acp cat: stdin error: ${K.message}
442
+ `),_=1,Z=!0,!j&&D.length===0&&$(_)},onPromptFailed:K=>{a(`hydra-acp cat: ${K.message}
443
+ `),_=1,Z=!0,!j&&D.length===0&&$(_)}}),W;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let K=Om({scheduleFlushCheck:Ce=>{let X=setImmediate(Ce);return()=>clearImmediate(X)},onChunk:Ce=>{D.push(Ce),ie()}});return s.on("data",Ce=>{K.feed(typeof Ce=="string"?Ce:Ce.toString("utf8"))}),s.on("end",()=>{K.eof(),Z=!0,!j&&D.length===0&&$(_)}),s.on("error",Ce=>{a(`hydra-acp cat: stdin error: ${Ce.message}
444
+ `),_=1,Z=!0,!j&&D.length===0&&$(_)}),W}let Ee="";return s.on("data",K=>{Ee+=typeof K=="string"?K:K.toString("utf8")}),s.on("end",()=>{Z=!0,Ee.length>0&&D.push(Ee),ie()}),s.on("error",K=>{a(`hydra-acp cat: stdin error: ${K.message}
445
+ `),_=1,Z=!0,!j&&D.length===0&&$(_)}),W}function ES(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,d=r.streamThreshold??xS,c="undecided",l=Buffer.alloc(0),u=!1,f=Promise.resolve(),p=(y,I)=>{let b=y.toString("base64");f=f.then(()=>n.write(s,b,I)).catch(x=>{o(`hydra-acp cat: stdin write failed: ${x.message}
446
+ `)})},g=async()=>{c="inline";let y=l.toString("utf8");l=Buffer.alloc(0);try{await a(y)}catch(I){t.onPromptFailed(I);return}t.onEof()},h=async()=>{c="file";let y;try{let x={mode:"memory"};r.streamBufferBytes!==void 0&&(x.capacityBytes=r.streamBufferBytes),y=await n.open(s,x)}catch(x){t.onPromptFailed(new Error(`stdin/open failed: ${x.message}`));return}l.length>0&&(p(l,!1),l=Buffer.alloc(0)),await f.catch(()=>{});let I=PS(r.prompt,y.capacityBytes);e.request("session/prompt",Bm(s,[{type:"text",text:I}])).catch(x=>{t.onPromptFailed(new Error(`prompt failed: ${x.message}`))}).then(()=>{u||p(Buffer.alloc(0),!0),t.onEof()})};i.on("data",y=>{let I=typeof y=="string"?Buffer.from(y,"utf8"):y;if(c==="undecided"){l=Buffer.concat([l,I]),l.length>d&&h();return}if(c==="file"){p(I,!1);return}l=Buffer.concat([l,I])}),i.on("end",()=>{if(u=!0,c==="undecided"){g();return}c==="file"&&p(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function PS(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
447
447
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
448
448
  - \`grep({pattern, regex?, case_insensitive?, context_before?, context_after?, cursor?})\` \u2014 server-side line filter; returns matching lines as decoded strings (not base64). Prefer this for "find lines that mention X" questions on multi-MB inputs.
449
449
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -458,36 +458,36 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
458
458
  User's question:
459
459
  ${t}`:`${s}
460
460
 
461
- Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function PS(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:ps,version:ce}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=xS(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[pt]:s});let o=await t.request("session/new",i);return kt(o._meta),o.sessionId}async function MS(t,e){return new Promise((n,s)=>{let r=new SS(t,e),i=()=>{r.off("error",o),n(r)},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}Oe();ft();dr();$t();wn();async function Nm(t={}){let{report:e,configLoaded:n}=await $S();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
461
+ Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function MS(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:ys,version:pe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=AS(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[ht]:s});let o=await t.request("session/new",i);return xt(o._meta),o.sessionId}async function $S(t,e){return new Promise((n,s)=>{let r=new kS(t,e),i=()=>{r.off("error",o),n(r)},o=a=>{r.off("open",i),s(a)};r.once("open",i),r.once("error",o)})}Oe();mt();pr();Mt();In();async function Um(t={}){let{report:e,configLoaded:n}=await _S();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
462
462
  `);return}process.stdout.write(`CLI: ${e.cli}
463
463
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
464
- `),e.daemonReachable&&(Lm("Extensions",e.extensions),Lm("Transformers",e.transformers)))}function Lm(t,e){if(process.stdout.write(`
464
+ `),e.daemonReachable&&(Dm("Extensions",e.extensions),Dm("Transformers",e.transformers)))}function Dm(t,e){if(process.stdout.write(`
465
465
  ${t}:
466
466
  `),e.length===0){process.stdout.write(` (none)
467
467
  `);return}let n=Math.max(...e.map(r=>r.name.length)),s=Math.max(...e.map(r=>(r.version??"-").length),7);for(let r of e){let i=r.version??"-";process.stdout.write(` ${r.name.padEnd(n)} ${i.padEnd(s)} ${r.status}
468
- `)}}async function $S(){let t={cli:ce,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await G()}catch{return{report:t,configLoaded:!1}}let n=await ar(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await de()}catch{return{report:t,configLoaded:!0}}let r=fe(e.daemon.host,e.daemon.port,!!e.daemon.tls),i={Authorization:`Bearer ${s}`};return t.extensions=await Bm(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Bm(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Bm(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as _S}from"child_process";import{accessSync as OS,constants as FS,statSync as LS}from"fs";import{delimiter as BS,join as NS}from"path";var DS=new Set(["agent","agents","auth","cat","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function HS(t){return DS.has(t)}function US(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function jS(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function qS(t){try{if(!LS(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return OS(t,FS.X_OK),!0}catch{return!1}}function WS(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(BS).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let d=NS(o,r+a);if(qS(d))return d}}function zS(t,e){let n=_S(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
469
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function Dm(t){let e=US(t);if(e===void 0||HS(e))return!1;let n=WS(e);if(n===void 0)return!1;zS(n,jS(t))}cc();var Gn=!1,Qh=!1;function Gh(t){!t||Qh||(Qh=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
470
- `))}async function Cx(){let t=process.argv.slice(2),e=t.indexOf("launch");if(e!==-1){let y=t.slice(0,e),v=t.slice(e+1),b=v[0],x=v.slice(1),{flags:C}=Ma(y);if(Zh(C),C.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
471
- `),process.exit(2);return}let F=b??Ve(C,"agent");if(!F){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
472
- `),process.exit(2);return}let z=await eg(ja(C),{allowPrompt:!1}),J=Ve(C,"name"),X=Ve(C,"model");Gn=!0;let D=C["dangerously-skip-permissions"]===!0;Gh(D);let $={agentId:F,agentArgs:x,name:J,model:X,dangerouslySkipPermissions:D};z?.sessionId!==void 0&&($.sessionId=z.sessionId),z?.target!==void 0&&z.fromUrl&&($.target=z.target),await da($);return}jc(t)===void 0&&!t.some(y=>y==="--prompt"||y.startsWith("--prompt="))&&Dm(t);let{positional:n,flags:s}=Ma(t);if(Zh(s),s.version===!0||n[0]==="--version"){process.stdout.write(`hydra-acp ${Rx()}
473
- `);return}if(s.help===!0){Wc();return}let r=jc(t)!==void 0||typeof s.prompt=="string",i=n[0],o=i!==void 0&&!i.startsWith("-")?i:r?"cat":i,a=Ve(s,"name"),d=Ve(s,"agent"),c=Ve(s,"model"),l=s["dangerously-skip-permissions"]===!0;Gh(l);let f=ja(s),u=o==="tui"||o===void 0&&process.stdout.isTTY,p=await eg(f,{allowPrompt:u});p!==void 0&&p.sessionId!==void 0&&s.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
474
- `),process.exit(2));let g=p?.sessionId,h=p?.fromUrl?p.target:void 0;if(!o){if(process.stdout.isTTY){Gn=!0,await Xh(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return}Gn=!0;let y={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(y.sessionId=g),h!==void 0&&(y.target=h),await da(y);return}switch(o){case"shim":{Gn=!0;let y={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(y.sessionId=g),h!==void 0&&(y.target=h),await da(y);return}case"cat":{let y=jc(t),v=typeof s.prompt=="string"?s.prompt:void 0,b=y??v,x=Ve(s,"cwd"),C={prompt:b,sessionId:g,name:a,model:c,agentId:d,detach:s.detach===!0,follow:s.follow===!0,raw:s.raw===!0,dangerouslySkipPermissions:l};x!==void 0&&(C.cwd=x),h!==void 0&&(C.target=h);let F=qc(s,"stream-threshold");F!==void 0&&(C.streamThreshold=F);let z=qc(s,"stream-bytes");z!==void 0&&(C.streamBufferBytes=z),d!==void 0&&await sc(d),Gn=!0,await Fm(C);return}case"version":{Gn=!0,await Nm({json:s.json===!0});return}case"init":await _l(s);return;case"daemon":{let y=t.indexOf("daemon"),v=t.slice(y+1),b=v[0];if(b===void 0||b==="status"){await up();return}if(b==="start"){await ap(s);return}if(b==="stop"){await dp();return}if(b==="restart"){await cp();return}if(b==="log"||b==="logs"){await lp(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${b}
475
- `),process.exit(2);return}case"session":case"sessions":{let y=n[1];if(y===void 0||y==="list"){let v=Ve(s,"columns"),b;if(v!==void 0)try{b=Sp(v)}catch(x){process.stderr.write(`${x.message}
476
- `),process.exit(2);return}await xp({all:s.all===!0,json:s.json===!0,host:typeof s.host=="string"?s.host:void 0,includeNonInteractive:s["include-non-interactive"]===!0,columns:b});return}if(y==="info"){await Wp(n[2],{verbose:s.verbose===!0,json:s.json===!0,diff:s.diff===!0,fold:s.fold===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0});return}if(y==="diff"){await qp(n[2],{json:s.json===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0,fold:s.fold===!0});return}if(y==="kill"){await Ap(n[2]);return}if(y==="remove"){await Cp(n[2]);return}if(y==="collect"){let v=Ve(s,"max-age-days"),b=Ve(s,"limit"),x={json:s.json===!0,keepUndecided:s["keep-undecided"]===!0};if(v!==void 0){let C=Number(v);if(!Number.isFinite(C)||C<0){process.stderr.write(`--max-age-days must be a non-negative number
477
- `),process.exit(2);return}x.maxAgeDays=C}if(b!==void 0){let C=Number(b);if(!Number.isFinite(C)||C<=0){process.stderr.write(`--limit must be a positive number
478
- `),process.exit(2);return}x.limit=C}await Rp(x);return}if(y==="export"){let v=Ve(s,"out"),b=Ve(s,"tools");await Tp(n[2],v,b);return}if(y==="transcript"){let v=Ve(s,"out");await Ep(n[2],v);return}if(y==="import"){let v=Ve(s,"cwd");await Pp(n[2],{replace:s.replace===!0,info:s.info===!0,...v!==void 0?{cwd:v}:{}});return}if(y==="share"){let v=Ve(s,"host"),b=Ve(s,"cwd");await Mp(n[2],{...v!==void 0?{host:v}:{},...b!==void 0?{cwd:b}:{}});return}process.stderr.write(`Unknown session subcommand: ${y}
479
- `),process.exit(2);return}case"extension":case"extensions":{let y=t.indexOf(o),v=t.slice(y+1),b=v[0],x=v[1],C=v.slice(2);if(b===void 0||b==="list"){await zp();return}if(b==="add"){await Jp(x,C);return}if(b==="remove"){await Kp(x);return}if(b==="start"){await Qp(x);return}if(b==="stop"){await Gp(x);return}if(b==="restart"){await Xp(x);return}if(b==="log"||b==="logs"){await Zp(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${b}
480
- `),process.exit(2);return}case"transformer":case"transformers":{let y=t.indexOf(o),v=t.slice(y+1),b=v[0],x=v[1],C=v.slice(2);if(b===void 0||b==="list"){await em();return}if(b==="add"){await tm(x,C);return}if(b==="remove"){await nm(x);return}if(b==="start"){await sm(x);return}if(b==="stop"){await rm(x);return}if(b==="restart"){await im(x);return}if(b==="log"||b==="logs"){await om(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${b}
481
- `),process.exit(2);return}case"agent":case"agents":{let y=n[1];if(y===void 0||y==="list"){await pm();return}if(y==="refresh"){await rc();return}if(y==="install"){await mm(n[2]);return}if(y==="sync"){await hm(n[2]);return}if(y==="set"){await ym(n[2],n[3]);return}if(y==="pin"){await bm(n[2],n[3]);return}if(y==="add"){let v=t.indexOf(o),b=t.slice(v+1);await vm(b[1],b.slice(2));return}if(y==="remove"){await Im(n[2]);return}if(y==="log"||y==="logs"){let v=t.indexOf(o),b=t.slice(v+2),{name:x,rest:C}=lr(b);await gm(x,C);return}process.stderr.write(`Unknown agent subcommand: ${y}
482
- `),process.exit(2);return}case"registry":{let y=n[1];if(y==="refresh"){await rc();return}if(y==="pin"){await ic(!0);return}if(y==="unpin"){await ic(!1);return}process.stderr.write(`Unknown registry subcommand: ${y}
483
- `),process.exit(2);return}case"auth":{let y=n[1];if(y==="password"){let v=n[2];if(v===void 0||v==="set"){await Sm(s);return}process.stderr.write(`Unknown auth password action: ${v}
484
- `),process.exit(2);return}if(y===void 0||y==="list"){await km();return}if(y==="revoke"){await xm(n[2]);return}process.stderr.write(`Unknown auth subcommand: ${y}
485
- `),process.exit(2);return}case"tui":Gn=!0,await Xh(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return;default:process.stderr.write(`Unknown command: ${o}
486
- `),Wc(),process.exit(2)}}async function Xh(t,e){let n=Ve(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await sc(e.agentId),Ir(Sr(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Yh(),Vh)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
487
- `),process.exit(2)),a.drip=!0;let d=qc(t,"drip-speed");d!==void 0&&d>0&&(a.dripSpeed=d)}await o(a)}function qc(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function Zh(t){let e=ll(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
468
+ `)}}async function _S(){let t={cli:pe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await G()}catch{return{report:t,configLoaded:!1}}let n=await fr(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await fe()}catch{return{report:t,configLoaded:!0}}let r=he(e.daemon.host,e.daemon.port,!!e.daemon.tls),i={Authorization:`Bearer ${s}`};return t.extensions=await Hm(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Hm(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Hm(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as OS}from"child_process";import{accessSync as FS,constants as LS,statSync as BS}from"fs";import{delimiter as NS,join as DS}from"path";var HS=new Set(["agent","agents","auth","cat","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function US(t){return HS.has(t)}function jS(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function qS(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function WS(t){try{if(!BS(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return FS(t,LS.X_OK),!0}catch{return!1}}function zS(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(NS).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let d=DS(o,r+a);if(WS(d))return d}}function JS(t,e){let n=OS(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
469
+ `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function jm(t){let e=jS(t);if(e===void 0||US(e))return!1;let n=zS(e);if(n===void 0)return!1;JS(n,qS(t))}fc();var ts=!1,Xh=!1;function Zh(t){!t||Xh||(Xh=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
470
+ `))}async function Rx(){let t=process.argv.slice(2),e=t.indexOf("launch");if(e!==-1){let y=t.slice(0,e),I=t.slice(e+1),b=I[0],x=I.slice(1),{flags:M}=Oa(y);if(tg(M),M.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
471
+ `),process.exit(2);return}let _=b??Ve(M,"agent");if(!_){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
472
+ `),process.exit(2);return}let Q=await ng(za(M),{allowPrompt:!1}),W=Ve(M,"name"),z=Ve(M,"model");ts=!0;let $=M["dangerously-skip-permissions"]===!0;Zh($);let D={agentId:_,agentArgs:x,name:W,model:z,dangerouslySkipPermissions:$};Q?.sessionId!==void 0&&(D.sessionId=Q.sessionId),Q?.target!==void 0&&Q.fromUrl&&(D.target=Q.target),await ua(D);return}zc(t)===void 0&&!t.some(y=>y==="--prompt"||y.startsWith("--prompt="))&&jm(t);let{positional:n,flags:s}=Oa(t);if(tg(s),s.version===!0||n[0]==="--version"){process.stdout.write(`hydra-acp ${Tx()}
473
+ `);return}if(s.help===!0){Kc();return}let r=zc(t)!==void 0||typeof s.prompt=="string",i=n[0],o=i!==void 0&&!i.startsWith("-")?i:r?"cat":i,a=Ve(s,"name"),d=Ve(s,"agent"),c=Ve(s,"model"),l=s["dangerously-skip-permissions"]===!0;Zh(l);let u=za(s),f=o==="tui"||o===void 0&&process.stdout.isTTY,p=await ng(u,{allowPrompt:f});p!==void 0&&p.sessionId!==void 0&&s.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
474
+ `),process.exit(2));let g=p?.sessionId,h=p?.fromUrl?p.target:void 0;if(!o){if(process.stdout.isTTY){ts=!0,await eg(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return}ts=!0;let y={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(y.sessionId=g),h!==void 0&&(y.target=h),await ua(y);return}switch(o){case"shim":{ts=!0;let y={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(y.sessionId=g),h!==void 0&&(y.target=h),await ua(y);return}case"cat":{let y=zc(t),I=typeof s.prompt=="string"?s.prompt:void 0,b=y??I,x=Ve(s,"cwd"),M={prompt:b,sessionId:g,name:a,model:c,agentId:d,detach:s.detach===!0,follow:s.follow===!0,raw:s.raw===!0,dangerouslySkipPermissions:l};x!==void 0&&(M.cwd=x),h!==void 0&&(M.target=h);let _=Jc(s,"stream-threshold");_!==void 0&&(M.streamThreshold=_);let Q=Jc(s,"stream-bytes");Q!==void 0&&(M.streamBufferBytes=Q),d!==void 0&&await oc(d),ts=!0,await Nm(M);return}case"version":{ts=!0,await Um({json:s.json===!0});return}case"init":await Ll(s);return;case"daemon":{let y=t.indexOf("daemon"),I=t.slice(y+1),b=I[0];if(b===void 0||b==="status"){await mp();return}if(b==="start"){await lp(s);return}if(b==="stop"){await up();return}if(b==="restart"){await fp();return}if(b==="log"||b==="logs"){await pp(I.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${b}
475
+ `),process.exit(2);return}case"session":case"sessions":{let y=n[1];if(y===void 0||y==="list"){let I=Ve(s,"columns"),b;if(I!==void 0)try{b=Ap(I)}catch(x){process.stderr.write(`${x.message}
476
+ `),process.exit(2);return}await Rp({all:s.all===!0,json:s.json===!0,host:typeof s.host=="string"?s.host:void 0,includeNonInteractive:s["include-non-interactive"]===!0,columns:b});return}if(y==="info"){await Kp(n[2],{verbose:s.verbose===!0,json:s.json===!0,diff:s.diff===!0,fold:s.fold===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0});return}if(y==="diff"){await Jp(n[2],{json:s.json===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0,fold:s.fold===!0});return}if(y==="kill"){await Tp(n[2]);return}if(y==="remove"){await Ep(n[2]);return}if(y==="collect"){let I=Ve(s,"max-age-days"),b=Ve(s,"limit"),x={json:s.json===!0,keepUndecided:s["keep-undecided"]===!0};if(I!==void 0){let M=Number(I);if(!Number.isFinite(M)||M<0){process.stderr.write(`--max-age-days must be a non-negative number
477
+ `),process.exit(2);return}x.maxAgeDays=M}if(b!==void 0){let M=Number(b);if(!Number.isFinite(M)||M<=0){process.stderr.write(`--limit must be a positive number
478
+ `),process.exit(2);return}x.limit=M}await Pp(x);return}if(y==="export"){let I=Ve(s,"out"),b=Ve(s,"tools");await Mp(n[2],I,b);return}if(y==="transcript"){let I=Ve(s,"out");await $p(n[2],I);return}if(y==="import"){let I=Ve(s,"cwd");await _p(n[2],{replace:s.replace===!0,info:s.info===!0,...I!==void 0?{cwd:I}:{}});return}if(y==="share"){let I=Ve(s,"host"),b=Ve(s,"cwd");await Op(n[2],{...I!==void 0?{host:I}:{},...b!==void 0?{cwd:b}:{}});return}process.stderr.write(`Unknown session subcommand: ${y}
479
+ `),process.exit(2);return}case"extension":case"extensions":{let y=t.indexOf(o),I=t.slice(y+1),b=I[0],x=I[1],M=I.slice(2);if(b===void 0||b==="list"){await Vp();return}if(b==="add"){await Yp(x,M);return}if(b==="remove"){await Qp(x);return}if(b==="start"){await Zp(x);return}if(b==="stop"){await em(x);return}if(b==="restart"){await tm(x);return}if(b==="log"||b==="logs"){await nm(I.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${b}
480
+ `),process.exit(2);return}case"transformer":case"transformers":{let y=t.indexOf(o),I=t.slice(y+1),b=I[0],x=I[1],M=I.slice(2);if(b===void 0||b==="list"){await sm();return}if(b==="add"){await rm(x,M);return}if(b==="remove"){await im(x);return}if(b==="start"){await om(x);return}if(b==="stop"){await am(x);return}if(b==="restart"){await dm(x);return}if(b==="log"||b==="logs"){await cm(I.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${b}
481
+ `),process.exit(2);return}case"agent":case"agents":{let y=n[1];if(y===void 0||y==="list"){await gm();return}if(y==="refresh"){await ac();return}if(y==="install"){await ym(n[2]);return}if(y==="sync"){await wm(n[2]);return}if(y==="set"){await vm(n[2],n[3]);return}if(y==="pin"){await Sm(n[2],n[3]);return}if(y==="add"){let I=t.indexOf(o),b=t.slice(I+1);await km(b[1],b.slice(2));return}if(y==="remove"){await xm(n[2]);return}if(y==="log"||y==="logs"){let I=t.indexOf(o),b=t.slice(I+2),{name:x,rest:M}=hr(b);await bm(x,M);return}process.stderr.write(`Unknown agent subcommand: ${y}
482
+ `),process.exit(2);return}case"registry":{let y=n[1];if(y==="refresh"){await ac();return}if(y==="pin"){await dc(!0);return}if(y==="unpin"){await dc(!1);return}process.stderr.write(`Unknown registry subcommand: ${y}
483
+ `),process.exit(2);return}case"auth":{let y=n[1];if(y==="password"){let I=n[2];if(I===void 0||I==="set"){await Am(s);return}process.stderr.write(`Unknown auth password action: ${I}
484
+ `),process.exit(2);return}if(y===void 0||y==="list"){await Cm();return}if(y==="revoke"){await Rm(n[2]);return}process.stderr.write(`Unknown auth subcommand: ${y}
485
+ `),process.exit(2);return}case"tui":ts=!0,await eg(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return;default:process.stderr.write(`Unknown command: ${o}
486
+ `),Kc(),process.exit(2)}}async function eg(t,e){let n=Ve(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await oc(e.agentId),Cr(Rr(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Gh(),Qh)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
487
+ `),process.exit(2)),a.drip=!0;let d=Jc(t,"drip-speed");d!==void 0&&d>0&&(a.dripSpeed=d)}await o(a)}function Jc(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function tg(t){let e=pl(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
488
488
 
489
- `),Wc(),process.exit(2))}function jc(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function eg(t,e){try{return await Ml(t,e)}catch(n){process.stderr.write(`${n.message}
490
- `),process.exit(1)}}function Rx(){try{let t=xx(kx(import.meta.url));return JSON.parse(Sx(Ax(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Wc(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
491
- `))}async function tg(){if(!Gn)try{let t=await fi();t&&process.stderr.write(`\u2728 ${pi(t)}
492
- `)}catch{}}Cx().then(tg).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
493
- `),await tg(),process.exit(1)});
489
+ `),Kc(),process.exit(2))}function zc(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function ng(t,e){try{return await Ol(t,e)}catch(n){process.stderr.write(`${n.message}
490
+ `),process.exit(1)}}function Tx(){try{let t=Ax(xx(import.meta.url));return JSON.parse(kx(Cx(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Kc(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
491
+ `))}async function sg(){if(!ts)try{let t=await yi();t&&process.stderr.write(`\u2728 ${wi(t)}
492
+ `)}catch{}}Rx().then(sg).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
493
+ `),await sg(),process.exit(1)});