@hydra-acp/cli 0.1.112 → 0.1.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- var Xv=Object.defineProperty;var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var _l=(t,e)=>{for(var n in e)Xv(t,n,{get:e[n],enumerable:!0})};import*as me from"path";import*as Fl from"os";function dt(t){let e=Fl.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function rS(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function Ie(){let t=process.env[sS];if(t&&t.length>0)return me.resolve(t);let e=rS();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return me.join(Fl.homedir(),".hydra-acp")}var sS,O,we=V(()=>{"use strict";sS="HYDRA_ACP_HOME";O={home:Ie,config:()=>me.join(Ie(),"config.json"),authToken:()=>me.join(Ie(),"auth-token"),remotes:()=>me.join(Ie(),"remotes.json"),pidFile:()=>me.join(Ie(),"daemon.pid"),logFile:()=>me.join(Ie(),"daemon.log"),currentLogFile:()=>me.join(Ie(),"current.log"),registryCache:()=>me.join(Ie(),"registry.json"),ttySessionDir:()=>me.join(Ie(),"tty"),ttySessionFile:t=>me.join(Ie(),"tty",t),agentsDir:()=>me.join(Ie(),"agents"),agentLogFile:t=>me.join(Ie(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>me.join(Ie(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>me.join(Ie(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>me.join(Ie(),"sessions"),sessionDir:t=>me.join(Ie(),"sessions",t),sessionFile:t=>me.join(Ie(),"sessions",t,"meta.json"),historyFile:t=>me.join(Ie(),"sessions",t,"history.jsonl"),historyArchiveFile:(t,e)=>me.join(Ie(),"sessions",t,`history.jsonl.${e}`),toolsDir:t=>me.join(Ie(),"sessions",t,"tools"),toolBlobFile:(t,e)=>me.join(Ie(),"sessions",t,"tools",e),queueFile:t=>me.join(Ie(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>me.join(Ie(),"sessions",".tombstones"),tombstoneAgentDir:t=>me.join(Ie(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>me.join(Ie(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>me.join(Ie(),"extensions"),extensionLogDir:t=>me.join(Ie(),"extensions",t),extensionLogFile:t=>me.join(Ie(),"extensions",t,"current.log"),extensionPidFile:t=>me.join(Ie(),"extensions",t,"extension.pid"),transformersDir:()=>me.join(Ie(),"transformers"),transformerLogDir:t=>me.join(Ie(),"transformers",t),transformerLogFile:t=>me.join(Ie(),"transformers",t,"current.log"),transformerPidFile:t=>me.join(Ie(),"transformers",t,"transformer.pid"),transformerState:(t,e)=>me.join(Ie(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>me.join(Ie(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>me.join(Ie(),"prompt-history"),tuiLogFile:()=>me.join(Ie(),"tui.log"),shimWireLogFile:()=>me.join(Ie(),"shim-wire.log")}});import*as _i from"fs/promises";function $i(){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 Fi(){try{let e=(await _i.readFile(O.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function Fr(){let t=await Fi();if(!t)throw new Error(`No service token found at ${O.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Oi(t){await _i.mkdir(O.home(),{recursive:!0}),await _i.writeFile(O.authToken(),t+`
2
+ var Zv=Object.defineProperty;var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var $l=(t,e)=>{for(var n in e)Zv(t,n,{get:e[n],enumerable:!0})};import*as me from"path";import*as Ol from"os";function dt(t){let e=Ol.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function iS(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function Ie(){let t=process.env[rS];if(t&&t.length>0)return me.resolve(t);let e=iS();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return me.join(Ol.homedir(),".hydra-acp")}var rS,O,we=V(()=>{"use strict";rS="HYDRA_ACP_HOME";O={home:Ie,config:()=>me.join(Ie(),"config.json"),authToken:()=>me.join(Ie(),"auth-token"),remotes:()=>me.join(Ie(),"remotes.json"),pidFile:()=>me.join(Ie(),"daemon.pid"),logFile:()=>me.join(Ie(),"daemon.log"),currentLogFile:()=>me.join(Ie(),"current.log"),registryCache:()=>me.join(Ie(),"registry.json"),ttySessionDir:()=>me.join(Ie(),"tty"),ttySessionFile:t=>me.join(Ie(),"tty",t),agentsDir:()=>me.join(Ie(),"agents"),agentLogFile:t=>me.join(Ie(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>me.join(Ie(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>me.join(Ie(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>me.join(Ie(),"sessions"),sessionDir:t=>me.join(Ie(),"sessions",t),sessionFile:t=>me.join(Ie(),"sessions",t,"meta.json"),historyFile:t=>me.join(Ie(),"sessions",t,"history.jsonl"),historyArchiveFile:(t,e)=>me.join(Ie(),"sessions",t,`history.jsonl.${e}`),toolsDir:t=>me.join(Ie(),"sessions",t,"tools"),toolBlobFile:(t,e)=>me.join(Ie(),"sessions",t,"tools",e),queueFile:t=>me.join(Ie(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>me.join(Ie(),"sessions",".tombstones"),tombstoneAgentDir:t=>me.join(Ie(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>me.join(Ie(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>me.join(Ie(),"extensions"),extensionLogDir:t=>me.join(Ie(),"extensions",t),extensionLogFile:t=>me.join(Ie(),"extensions",t,"current.log"),extensionPidFile:t=>me.join(Ie(),"extensions",t,"extension.pid"),transformersDir:()=>me.join(Ie(),"transformers"),transformerLogDir:t=>me.join(Ie(),"transformers",t),transformerLogFile:t=>me.join(Ie(),"transformers",t,"current.log"),transformerPidFile:t=>me.join(Ie(),"transformers",t,"transformer.pid"),transformerState:(t,e)=>me.join(Ie(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>me.join(Ie(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>me.join(Ie(),"prompt-history"),tuiLogFile:()=>me.join(Ie(),"tui.log"),shimWireLogFile:()=>me.join(Ie(),"shim-wire.log")}});import*as _i from"fs/promises";function $i(){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 Fi(){try{let e=(await _i.readFile(O.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function Fr(){let t=await Fi();if(!t)throw new Error(`No service token found at ${O.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Oi(t){await _i.mkdir(O.home(),{recursive:!0}),await _i.writeFile(O.authToken(),t+`
3
3
  `,{encoding:"utf8",mode:384})}async function Vo(){let t=await Fi();if(t)return t;let e=$i();return await Oi(e),process.stderr.write(`hydra-acp: initialized ${O.authToken()} with a fresh service token.
4
- `),e}var xs=V(()=>{"use strict";we()});import*as _t from"fs/promises";import*as zp from"fs";import*as _n from"path";import{randomBytes as iS}from"crypto";async function nn(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await oS(t,r,n)}async function oS(t,e,n={}){let s=await aS(t),r=dS(s);await _t.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${cS()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await _t.writeFile(i,e,o),await _t.rename(i,s)}catch(o){throw await _t.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{zp.chmodSync(s,n.mode)}catch{}}async function aS(t){let e;try{e=await _t.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await _t.readlink(t),s=_n.isAbsolute(n)?n:_n.resolve(_n.dirname(t),n);try{let r=await _t.realpath(_n.dirname(s));return _n.join(r,_n.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(t){let e;try{e=await _t.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 dS(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function cS(){return iS(4).toString("hex")}var Or=V(()=>{"use strict"});import*as Zs from"fs/promises";import{homedir as Ol}from"os";import{z as q}from"zod";function Yp(t){return t.tui.inAppSelection??t.tui.mouse}function Vp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Qp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function fd(){return await bS(),await yn(O.config())??{}}async function bS(){let t;try{t=await Zs.lstat(O.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Zs.stat(O.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Zs.readlink(O.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${O.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function pd(){let t=await fd(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Zs.access(O.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${O.authToken()} and ${O.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Oi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await nn(O.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${O.config()} to ${O.authToken()}.
6
- `)}async function Ae(){return await pd(),Ll.parse(await fd())}async function As(t){await pd();let e=await fd();t(e),Ll.parse(e),await nn(O.config(),e,{mode:384})}async function Qo(t,e){await As(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Li(t){await As(e=>{e.defaultAgent=t})}async function Gp(t,e){await As(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Xp(t,e){await As(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 Bl(t,e){await As(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 Zp(t){await As(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function eh(){let t=await fd();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function tt(t){return t==="~"||t==="$HOME"?Ol():t.startsWith("~/")?Ol()+t.slice(1):t.startsWith("$HOME/")?Ol()+t.slice(5):t}var Jp,lS,$n,uS,fS,pS,hS,mS,gS,Kp,yS,wS,Ll,Qe=V(()=>{"use strict";we();xs();Or();Jp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",lS=q.object({cert:q.string(),key:q.string()}),$n=55514,uS=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default($n),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:lS.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:q.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:q.number().int().positive().default(10),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),fS=q.object({url:q.string().url().default(Jp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),pS=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),hS=q.object({packageSpec:q.string().optional()}),mS=q.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),gS=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:q.record(mS,q.object({command:q.union([q.string(),q.array(q.string())])})).default({})}),Kp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),yS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),wS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Ll=q.object({daemon:uS.default({}),registry:fS.default({url:Jp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),pS).default({}),agentOverrides:q.record(q.string(),hS).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(Kp,yS).default({}),transformers:q.record(Kp,wS).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:gS.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function Lr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Nl(t){return{httpScheme:"https",wsScheme:"wss"}}function Dl(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 ${hd(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${hd(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=vS(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${hd(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${hd(t)}`);let i=Lr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=$n;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function th(t){let e=t.port!==void 0&&t.port!==$n?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function vS(t){try{return new URL(t)}catch{return null}}function hd(t){return t.length>80?`${t.slice(0,77)}...`:t}var Go=V(()=>{"use strict";Qe()});function Br(t,e){return`${t}:${e}`}function nh(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function SS(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 kS(){let t=await yn(O.remotes());return t===void 0?{version:1,entries:{}}:IS(t)}function IS(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),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function Hl(t){await nn(O.remotes(),t,{mode:384})}var md,Ul=V(()=>{"use strict";we();Or();md=class t{data;constructor(e){this.data=e}static async load(){let e=await kS(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(nh(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Hl(i),new t(i)}get(e,n){let s=this.data.entries[Br(e,n)];if(s&&!nh(s,Date.now()))return s}async set(e,n,s){this.data.entries[Br(e,n)]=s,await Hl(this.data)}async delete(e,n){let s=Br(e,n);return s in this.data.entries?(delete this.data.entries[s],await Hl(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=SS(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Bi(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",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){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)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):xS()}function xS(){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 jl=V(()=>{"use strict"});import*as sh from"path";function Gn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=sh.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Xo=V(()=>{"use strict"});import*as gd from"fs/promises";async function Cs(){try{let t=await gd.readFile(O.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function rh(t){await gd.writeFile(O.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function Fn(t){try{return process.kill(t,0),!0}catch{return!1}}var Ni=V(()=>{"use strict";we()});var lh={};_l(lh,{_resetForTests:()=>$S,clearPin:()=>MS,fetchPeerFingerprint:()=>Kl,formatFingerprint:()=>yd,getPin:()=>Wl,installGlobalTlsTrust:()=>Yl,loadPinsFromStore:()=>zl,setPin:()=>Zo,sha256Hex:()=>Jl,wsTlsOptions:()=>ea});import{createHash as AS}from"crypto";import*as ih from"tls";import{Agent as CS,Dispatcher as RS,buildConnector as TS,getGlobalDispatcher as ES,setGlobalDispatcher as PS}from"undici";function Zo(t,e,n){Nr.set(Br(t,e),oh(n))}function MS(t,e){Nr.delete(Br(t,e))}function Wl(t,e){return Nr.get(Br(t,e))}function zl(t){Nr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Zo(e.host,e.port,e.entry.pinnedFingerprint)}async function Kl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=ih.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,f)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):f&&r(f)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,Jl(l.raw))}),o.once("error",l=>c(l))})}function Jl(t){return AS("sha256").update(t).digest("hex")}function yd(t){let e=oh(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function oh(t){return t.replace(/:/g,"").toLowerCase()}function Yl(){if(ql)return;ql=!0;let t=ES(),e=new CS({connect:TS({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>dh(s,r)})}),n=new RS;n.dispatch=(s,r)=>{let i=_S(s.origin);return(i&&ah(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),PS(n)}function _S(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function ah(t){for(let e of Nr.keys())if(ch(e)?.host===t)return!0;return!1}function dh(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=Jl(e.raw);for(let[s,r]of Nr.entries()){let i=ch(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${yd(n)})`)}function ch(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}function ea(t){return ah(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>dh(e,n)}:{autoSelectFamily:!0}}function $S(){Nr.clear(),ql=!1}var Nr,ql,ta=V(()=>{"use strict";Ul();Nr=new Map,ql=!1});import*as hh from"os";async function Ht(t){let e=await Vo(),n=await Cs();if(n&&Fn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Lr(r)}}function uh(t,e){let{httpScheme:n,wsScheme:s}=Nl(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:gh(t),isLocal:t.isLoopback}}async function mh(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Bi,r=e.confirmImpl??BS,i=e.tlsHandshakeImpl??FS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let w=await Fi();if(w)return LS(t,w)}let c=e.store??await md.load();zl(c),Yl();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Zo(t.host,t.port,d.pinnedFingerprint),uh(t,d.token);if(!a)throw new Vl(t.host,t.port);let l=gh(t),{httpScheme:f}=Nl(t.host),u;if(f==="https"&&Wl(t.host,t.port)===void 0){let w=await i(t.host,t.port);if(w.kind==="untrusted"){let b=w.subject||w.issuer?`
4
+ `),e}var xs=V(()=>{"use strict";we()});import*as _t from"fs/promises";import*as zp from"fs";import*as _n from"path";import{randomBytes as oS}from"crypto";async function nn(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await aS(t,r,n)}async function aS(t,e,n={}){let s=await dS(t),r=cS(s);await _t.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${lS()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await _t.writeFile(i,e,o),await _t.rename(i,s)}catch(o){throw await _t.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{zp.chmodSync(s,n.mode)}catch{}}async function dS(t){let e;try{e=await _t.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await _t.readlink(t),s=_n.isAbsolute(n)?n:_n.resolve(_n.dirname(t),n);try{let r=await _t.realpath(_n.dirname(s));return _n.join(r,_n.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(t){let e;try{e=await _t.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 cS(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function lS(){return oS(4).toString("hex")}var Or=V(()=>{"use strict"});import*as er from"fs/promises";import{homedir as Ll}from"os";import{z as q}from"zod";function Yp(t){return t.tui.inAppSelection??t.tui.mouse}function Vp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Qp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function fd(){return await vS(),await yn(O.config())??{}}async function vS(){let t;try{t=await er.lstat(O.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await er.stat(O.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await er.readlink(O.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${O.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function pd(){let t=await fd(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await er.access(O.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${O.authToken()} and ${O.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Oi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await nn(O.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${O.config()} to ${O.authToken()}.
6
+ `)}async function Ae(){return await pd(),Bl.parse(await fd())}async function As(t){await pd();let e=await fd();t(e),Bl.parse(e),await nn(O.config(),e,{mode:384})}async function Qo(t,e){await As(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Li(t){await As(e=>{e.defaultAgent=t})}async function Gp(t,e){await As(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Xp(t,e){await As(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 Nl(t,e){await As(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 Zp(t){await As(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function eh(){let t=await fd();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function tt(t){return t==="~"||t==="$HOME"?Ll():t.startsWith("~/")?Ll()+t.slice(1):t.startsWith("$HOME/")?Ll()+t.slice(5):t}var Jp,uS,$n,fS,pS,hS,mS,gS,yS,Kp,wS,bS,Bl,Ge=V(()=>{"use strict";we();xs();Or();Jp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",uS=q.object({cert:q.string(),key:q.string()}),$n=55514,fS=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default($n),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:uS.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:q.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:q.number().int().positive().default(10),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),pS=q.object({url:q.string().url().default(Jp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),hS=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),mS=q.object({packageSpec:q.string().optional()}),gS=q.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),yS=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:q.record(gS,q.object({command:q.union([q.string(),q.array(q.string())])})).default({})}),Kp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),wS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),bS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Bl=q.object({daemon:fS.default({}),registry:pS.default({url:Jp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),hS).default({}),agentOverrides:q.record(q.string(),mS).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(Kp,wS).default({}),transformers:q.record(Kp,bS).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:yS.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function Lr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Dl(t){return{httpScheme:"https",wsScheme:"wss"}}function Hl(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 ${hd(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${hd(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=SS(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${hd(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${hd(t)}`);let i=Lr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=$n;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function th(t){let e=t.port!==void 0&&t.port!==$n?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function SS(t){try{return new URL(t)}catch{return null}}function hd(t){return t.length>80?`${t.slice(0,77)}...`:t}var Go=V(()=>{"use strict";Ge()});function Br(t,e){return`${t}:${e}`}function nh(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function kS(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 IS(){let t=await yn(O.remotes());return t===void 0?{version:1,entries:{}}:xS(t)}function xS(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),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function Ul(t){await nn(O.remotes(),t,{mode:384})}var md,jl=V(()=>{"use strict";we();Or();md=class t{data;constructor(e){this.data=e}static async load(){let e=await IS(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(nh(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Ul(i),new t(i)}get(e,n){let s=this.data.entries[Br(e,n)];if(s&&!nh(s,Date.now()))return s}async set(e,n,s){this.data.entries[Br(e,n)]=s,await Ul(this.data)}async delete(e,n){let s=Br(e,n);return s in this.data.entries?(delete this.data.entries[s],await Ul(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=kS(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Bi(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",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){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)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):AS()}function AS(){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 ql=V(()=>{"use strict"});import*as sh from"path";function Gn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=sh.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Xo=V(()=>{"use strict"});import*as gd from"fs/promises";async function Cs(){try{let t=await gd.readFile(O.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function rh(t){await gd.writeFile(O.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function Fn(t){try{return process.kill(t,0),!0}catch{return!1}}var Ni=V(()=>{"use strict";we()});var lh={};$l(lh,{_resetForTests:()=>FS,clearPin:()=>_S,fetchPeerFingerprint:()=>Jl,formatFingerprint:()=>yd,getPin:()=>zl,installGlobalTlsTrust:()=>Vl,loadPinsFromStore:()=>Kl,setPin:()=>Zo,sha256Hex:()=>Yl,wsTlsOptions:()=>ea});import{createHash as CS}from"crypto";import*as ih from"tls";import{Agent as RS,Dispatcher as TS,buildConnector as ES,getGlobalDispatcher as PS,setGlobalDispatcher as MS}from"undici";function Zo(t,e,n){Nr.set(Br(t,e),oh(n))}function _S(t,e){Nr.delete(Br(t,e))}function zl(t,e){return Nr.get(Br(t,e))}function Kl(t){Nr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Zo(e.host,e.port,e.entry.pinnedFingerprint)}async function Jl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=ih.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,f)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):f&&r(f)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,Yl(l.raw))}),o.once("error",l=>c(l))})}function Yl(t){return CS("sha256").update(t).digest("hex")}function yd(t){let e=oh(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function oh(t){return t.replace(/:/g,"").toLowerCase()}function Vl(){if(Wl)return;Wl=!0;let t=PS(),e=new RS({connect:ES({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>dh(s,r)})}),n=new TS;n.dispatch=(s,r)=>{let i=$S(s.origin);return(i&&ah(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),MS(n)}function $S(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function ah(t){for(let e of Nr.keys())if(ch(e)?.host===t)return!0;return!1}function dh(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=Yl(e.raw);for(let[s,r]of Nr.entries()){let i=ch(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${yd(n)})`)}function ch(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}function ea(t){return ah(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>dh(e,n)}:{autoSelectFamily:!0}}function FS(){Nr.clear(),Wl=!1}var Nr,Wl,ta=V(()=>{"use strict";jl();Nr=new Map,Wl=!1});import*as hh from"os";async function Ht(t){let e=await Vo(),n=await Cs();if(n&&Fn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Lr(r)}}function uh(t,e){let{httpScheme:n,wsScheme:s}=Dl(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:gh(t),isLocal:t.isLoopback}}async function mh(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Bi,r=e.confirmImpl??NS,i=e.tlsHandshakeImpl??OS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let w=await Fi();if(w)return BS(t,w)}let c=e.store??await md.load();Kl(c),Vl();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Zo(t.host,t.port,d.pinnedFingerprint),uh(t,d.token);if(!a)throw new Ql(t.host,t.port);let l=gh(t),{httpScheme:f}=Dl(t.host),u;if(f==="https"&&zl(t.host,t.port)===void 0){let w=await i(t.host,t.port);if(w.kind==="untrusted"){let b=w.subject||w.issuer?`
10
10
  subject: ${w.subject??"(unknown)"}
11
11
  issuer: ${w.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
12
  sha256: ${yd(w.fingerprint)}${b}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Zo(t.host,t.port,w.fingerprint),u=w.fingerprint}else if(w.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${w.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${f}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:ph()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:ph(),...u?{pinnedFingerprint:u,pinnedAt:new Date().toISOString()}:{}}),uh(t,y.session_token)}async function FS(t,e){let n=await OS(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Kl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function OS(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?fh(p.subject):void 0,issuer:p?.issuer?fh(p.issuer):void 0});return}let u=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:u.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function fh(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function LS(t,e){let n=await Cs(),r=n&&Fn(n.pid)?n.loopbackPort:t.port,i=t.port===$n?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function BS(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
- `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function ph(){try{let t=hh.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function gh(t){return t.port===$n?t.host:`${t.host}:${t.port}`}var Vl,Dr=V(()=>{"use strict";Qe();xs();Go();Ul();jl();Xo();Ni();ta();Go();Vl=class extends Error{host;port;constructor(e,n){let s=n===$n?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Gn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as NS,renameSync as DS,statSync as HS}from"fs";function bh(t){wh=t}function oe(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?O.tuiLogFile():e;if(n.length!==0)try{US(n);let s=JSON.stringify({t:new Date().toISOString(),...t});NS(n,`${s}
15
- `)}catch{}}function US(t){try{if(HS(t).size<wh)return;DS(t,`${t}.0`)}catch{}}var wh,Hr=V(()=>{"use strict";we();wh=5*1024*1024});import*as _h from"fs";import*as Ut from"fs/promises";import*as er from"path";import{spawn as $h}from"child_process";import{Readable as JS}from"stream";function wn(){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 tu(t,e=wn()){if(e)return t[e]}function nu(t){Di=t??(e=>process.stderr.write(e+`
16
- `))}async function Fh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${wn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=wn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=O.agentInstallDir(t.agentId,e,t.version),s=er.resolve(n,t.target.cmd);if(await eu(s))return s;if(await YS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await eu(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await Ut.chmod(s,493).catch(()=>{}),s}async function YS(t){await Ut.mkdir(er.dirname(t.installDir),{recursive:!0});let e=await Ut.mkdtemp(`${t.installDir}.partial-`);try{Di(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await VS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Di(`hydra-acp: extracting ${t.agentId}`),Hi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await GS(n,e),await Ut.unlink(n).catch(()=>{});try{await Ut.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await eu(t.installDir)){await Ut.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Di(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Ut.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Hi(t,e){if(t)try{t(e)}catch{}}async function VS(t){let e=QS(t.url),n=er.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=_h.createWriteStream(n),o=JS.fromWeb(s.body);Hi(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-d>=f&&(d=p,Hi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Di(Mh(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),Di(Mh(t.agentId,a,r,!0)),Hi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Mh(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 QS(t){let e=new URL(t);return er.posix.basename(e.pathname)||"archive"}async function GS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Zl("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await XS("unzip")){await Zl("unzip",["-q",t,"-d",e]);return}await Zl("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Zl(t,e){return new Promise((n,s)=>{let r=$h(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 XS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=$h(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function eu(t){try{return await Ut.access(t),!0}catch{return!1}}var Di,Ui=V(()=>{"use strict";we();Di=t=>{process.stderr.write(t+`
17
- `)}});var j,Id=V(()=>{"use strict";j={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as Be}from"zod";var jh,hk,qh,Wh,zh,du=V(()=>{"use strict";jh=Be.object({protocolVersion:Be.number().optional(),clientCapabilities:Be.record(Be.unknown()).optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional()}),hk=Be.enum(["full","pending_only","none","after_message"]),qh=Be.object({cwd:Be.string(),mcpServers:Be.array(Be.unknown()).optional(),_meta:Be.record(Be.unknown()).optional()}),Wh=Be.object({upstreamSessionId:Be.string(),agentId:Be.string(),cwd:Be.string(),title:Be.string().optional(),agentArgs:Be.array(Be.string()).optional()}),zh=Be.object({sessionId:Be.string(),historyPolicy:hk.default("full"),afterMessageId:Be.string().optional(),clientId:Be.string().optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional(),_meta:Be.record(Be.unknown()).optional()})});import{z as pe}from"zod";function xd(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),t.compactionState!==void 0&&(n.compactionState=t.compactionState),t.forkSynthesisState!==void 0&&(n.forkSynthesisState=t.forkSynthesisState),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),e.resurrected===!0&&(n.resurrected=!0)),n}function Yh(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:na(t._meta,xd(t))};return t.title!==void 0&&(e.title=t.title),e}var Kh,Jh,cu,oM,mk,aM,lu=V(()=>{"use strict";Ad();Kh=pe.object({sessionId:pe.string()}),Jh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),cu=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),oM=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:cu.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),mk=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),aM=pe.object({sessions:pe.array(mk),nextCursor:pe.string().optional()})});function gk(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function rn(t){if(!t)return{};let e=t[Ft];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=Wh.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=cu.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 c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,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==="warm"||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.resurrected=="boolean"&&(s.resurrected=n.resurrected),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}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=gk(n.env);r!==void 0&&(s.env=r)}return s}function na(t,e){return{...t??{},[Ft]:e}}var Ft,Ad=V(()=>{"use strict";du();lu();Ft="hydra-acp"});import{z as te}from"zod";var Vh,Cd,Qh,pM,hM,mM,Gh,gM,Xh,yM,Zh,wM,bM,em=V(()=>{"use strict";Vh=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),Cd=te.object({sessionId:te.string()}),Qh=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),pM=te.object({sessionId:te.string(),messageId:te.string(),originator:Qh,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),hM=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),mM=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),Gh=te.object({sessionId:te.string(),messageId:te.string()}),gM=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Xh=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),yM=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Zh=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),wM=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),bM=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:Qh,amendedAt:te.number()})});import{z as tr}from"zod";var tm,Rd,Wi,nm=V(()=>{"use strict";tm=tr.object({agentId:tr.string(),version:tr.string(),source:tr.enum(["binary","npm"]),phase:tr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:tr.number().optional(),totalBytes:tr.number().optional(),packageSpec:tr.string().optional()}),Rd="hydra-acp/agents/install_progress",Wi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Ot=V(()=>{"use strict";Id();du();Ad();lu();em();nm()});import{nanoid as yk}from"nanoid";var uu,Kt,jr=V(()=>{"use strict";Ot();uu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Kt=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;static MAX_BUFFERED_METHODS=256;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)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new uu;let s=yk(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});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:j.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??j.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);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0: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)}}}});async function zi(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(c=>c.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 Ki(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}}var fu=V(()=>{"use strict"});import*as im from"fs/promises";function Ek(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var kk,Ik,Ji,xk,Ak,Ck,Rk,Tk,rm,Pd,om=V(()=>{"use strict";kk=64*1024*1024,Ik=1*1024*1024,Ji=64*1024,xk=6e4,Ak=100,Ck=1e3,Rk=64*1024,Tk=256*1024,rm=20;Pd=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??kk,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ik,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,Ji));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 c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Ji)),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,Ji)),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,xk));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,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Ek(e.pattern),c),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Ak,Ck)),u=Math.max(1,Math.min(e.maxBytes??Rk,Tk)),p=Math.max(0,Math.min(e.contextBefore??0,rm)),h=Math.max(0,Math.min(e.contextAfter??0,rm)),m=[],y=[],w=[],b=0,S=!1,k=0,A=0,E=(_,D)=>{for(let X of w)X.remaining>0&&(X.match.after===void 0&&(X.match.after=[]),X.match.after.push({cursor:_,line:D}),X.remaining--,b+=D.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(d.test(D)!==l&&m.length<f){let X={cursor:_,line:D};if(p>0&&y.length>0){X.before=y.slice();for(let Z of X.before)b+=Z.line.length}b+=D.length,m.push(X),h>0&&w.push({match:X,remaining:h})}if(p>0)for(y.push({cursor:_,line:D});y.length>p;)y.shift();let L=m.length>=f&&w.length===0,K=b>=u;return L||K};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let D=o.subarray(k,_).toString("utf8"),N=r+k;if(k=_+1,A=k,E(N,D)){S=!0;break}}if(!S&&k<o.length&&this.closed){let _=o.subarray(k).toString("utf8"),D=r+k;E(D,_)&&(S=!0),A=o.length}let P=Math.min(r+A,this.writeCursor),B={matches:m,truncated:S,nextCursor:P,scannedBytes:A};return i>0&&(B.gap=i),this.closed&&P>=this.writeCursor&&(B.eof=!0),B}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(()=>im.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Yi,jM,am=V(()=>{"use strict";Yi=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],jM=new Map(Yi.map(t=>[t.verb,t]))});function dm(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Vi(t,e){return pu(t,e.map(n=>n.modelId))}function pu(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=dm(t),s=e.filter(i=>dm(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var Md=V(()=>{"use strict"});function cm(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 c=t[a];if(c===void 0)continue;let d=hu(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let f=n.get(l);f?f.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=hu(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Mk(r,i.outIndex,Pk(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?_k(c,n.get(f)??[]):c;f!==void 0&&s.has(f)&&!$k(u)&&(u=Fk(u,s.get(f))),r.push(u);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function hu(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Pk(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Mk(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 _k(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function $k(t){let n=hu(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Fk(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var lm=V(()=>{"use strict"});function Qi(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 c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=gu(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=yu(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(mu(c))):d==="turn_complete"&&i()}return i(),Dk(s.join(`
18
- `),n)}function mu(t){let e=Lk(t),n=Bk(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function Lk(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Bk(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of Ok){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${Nk(r,200)}`)}return n}function gu(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 yu(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function Nk(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Dk(t,e){if(t.length<=e)return t;let n=t.split(`
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Zo(t.host,t.port,w.fingerprint),u=w.fingerprint}else if(w.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${w.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${f}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:ph()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:ph(),...u?{pinnedFingerprint:u,pinnedAt:new Date().toISOString()}:{}}),uh(t,y.session_token)}async function OS(t,e){let n=await LS(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Jl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function LS(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?fh(p.subject):void 0,issuer:p?.issuer?fh(p.issuer):void 0});return}let u=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:u.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function fh(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function BS(t,e){let n=await Cs(),r=n&&Fn(n.pid)?n.loopbackPort:t.port,i=t.port===$n?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function NS(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function ph(){try{let t=hh.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function gh(t){return t.port===$n?t.host:`${t.host}:${t.port}`}var Ql,Dr=V(()=>{"use strict";Ge();xs();Go();jl();ql();Xo();Ni();ta();Go();Ql=class extends Error{host;port;constructor(e,n){let s=n===$n?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Gn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as DS,renameSync as HS,statSync as US}from"fs";function bh(t){wh=t}function oe(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?O.tuiLogFile():e;if(n.length!==0)try{jS(n);let s=JSON.stringify({t:new Date().toISOString(),...t});DS(n,`${s}
15
+ `)}catch{}}function jS(t){try{if(US(t).size<wh)return;HS(t,`${t}.0`)}catch{}}var wh,Hr=V(()=>{"use strict";we();wh=5*1024*1024});import*as _h from"fs";import*as Ut from"fs/promises";import*as tr from"path";import{spawn as $h}from"child_process";import{Readable as YS}from"stream";function wn(){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 nu(t,e=wn()){if(e)return t[e]}function su(t){Di=t??(e=>process.stderr.write(e+`
16
+ `))}async function Fh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${wn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=wn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=O.agentInstallDir(t.agentId,e,t.version),s=tr.resolve(n,t.target.cmd);if(await tu(s))return s;if(await VS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await tu(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await Ut.chmod(s,493).catch(()=>{}),s}async function VS(t){await Ut.mkdir(tr.dirname(t.installDir),{recursive:!0});let e=await Ut.mkdtemp(`${t.installDir}.partial-`);try{Di(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await QS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Di(`hydra-acp: extracting ${t.agentId}`),Hi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await XS(n,e),await Ut.unlink(n).catch(()=>{});try{await Ut.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await tu(t.installDir)){await Ut.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Di(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Ut.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Hi(t,e){if(t)try{t(e)}catch{}}async function QS(t){let e=GS(t.url),n=tr.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=_h.createWriteStream(n),o=YS.fromWeb(s.body);Hi(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-d>=f&&(d=p,Hi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Di(Mh(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),Di(Mh(t.agentId,a,r,!0)),Hi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Mh(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 GS(t){let e=new URL(t);return tr.posix.basename(e.pathname)||"archive"}async function XS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await eu("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await ZS("unzip")){await eu("unzip",["-q",t,"-d",e]);return}await eu("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function eu(t,e){return new Promise((n,s)=>{let r=$h(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 ZS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=$h(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function tu(t){try{return await Ut.access(t),!0}catch{return!1}}var Di,Ui=V(()=>{"use strict";we();Di=t=>{process.stderr.write(t+`
17
+ `)}});var j,Id=V(()=>{"use strict";j={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as Ne}from"zod";var jh,mk,qh,Wh,zh,cu=V(()=>{"use strict";jh=Ne.object({protocolVersion:Ne.number().optional(),clientCapabilities:Ne.record(Ne.unknown()).optional(),clientInfo:Ne.object({name:Ne.string(),version:Ne.string().optional()}).optional()}),mk=Ne.enum(["full","pending_only","none","after_message"]),qh=Ne.object({cwd:Ne.string(),mcpServers:Ne.array(Ne.unknown()).optional(),_meta:Ne.record(Ne.unknown()).optional()}),Wh=Ne.object({upstreamSessionId:Ne.string(),agentId:Ne.string(),cwd:Ne.string(),title:Ne.string().optional(),agentArgs:Ne.array(Ne.string()).optional()}),zh=Ne.object({sessionId:Ne.string(),historyPolicy:mk.default("full"),afterMessageId:Ne.string().optional(),clientId:Ne.string().optional(),clientInfo:Ne.object({name:Ne.string(),version:Ne.string().optional()}).optional(),_meta:Ne.record(Ne.unknown()).optional()})});import{z as pe}from"zod";function xd(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),t.compactionState!==void 0&&(n.compactionState=t.compactionState),t.forkSynthesisState!==void 0&&(n.forkSynthesisState=t.forkSynthesisState),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),e.resurrected===!0&&(n.resurrected=!0)),n}function Yh(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:na(t._meta,xd(t))};return t.title!==void 0&&(e.title=t.title),e}var Kh,Jh,lu,pM,gk,hM,uu=V(()=>{"use strict";Ad();Kh=pe.object({sessionId:pe.string()}),Jh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),lu=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),pM=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:lu.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),gk=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),hM=pe.object({sessions:pe.array(gk),nextCursor:pe.string().optional()})});function yk(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function rn(t){if(!t)return{};let e=t[Ft];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=Wh.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=lu.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 c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,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==="warm"||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.resurrected=="boolean"&&(s.resurrected=n.resurrected),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}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=yk(n.env);r!==void 0&&(s.env=r)}return s}function na(t,e){return{...t??{},[Ft]:e}}var Ft,Ad=V(()=>{"use strict";cu();uu();Ft="hydra-acp"});import{z as te}from"zod";var Vh,Cd,Qh,vM,SM,kM,Gh,IM,Xh,xM,Zh,AM,CM,em=V(()=>{"use strict";Vh=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),Cd=te.object({sessionId:te.string()}),Qh=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),vM=te.object({sessionId:te.string(),messageId:te.string(),originator:Qh,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),SM=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),kM=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),Gh=te.object({sessionId:te.string(),messageId:te.string()}),IM=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Xh=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),xM=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Zh=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),AM=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),CM=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:Qh,amendedAt:te.number()})});import{z as nr}from"zod";var tm,Rd,Wi,nm=V(()=>{"use strict";tm=nr.object({agentId:nr.string(),version:nr.string(),source:nr.enum(["binary","npm"]),phase:nr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:nr.number().optional(),totalBytes:nr.number().optional(),packageSpec:nr.string().optional()}),Rd="hydra-acp/agents/install_progress",Wi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Ot=V(()=>{"use strict";Id();cu();Ad();uu();em();nm()});import{nanoid as wk}from"nanoid";var fu,Kt,jr=V(()=>{"use strict";Ot();fu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Kt=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;static MAX_BUFFERED_METHODS=256;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)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new fu;let s=wk(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});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:j.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??j.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);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0: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)}}}});async function zi(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(c=>c.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 Ki(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}}var pu=V(()=>{"use strict"});import*as im from"fs/promises";function Pk(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ik,xk,Ji,Ak,Ck,Rk,Tk,Ek,rm,Pd,om=V(()=>{"use strict";Ik=64*1024*1024,xk=1*1024*1024,Ji=64*1024,Ak=6e4,Ck=100,Rk=1e3,Tk=64*1024,Ek=256*1024,rm=20;Pd=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??Ik,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(xk,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,Ji));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 c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Ji)),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,Ji)),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,Ak));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,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Pk(e.pattern),c),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Ck,Rk)),u=Math.max(1,Math.min(e.maxBytes??Tk,Ek)),p=Math.max(0,Math.min(e.contextBefore??0,rm)),h=Math.max(0,Math.min(e.contextAfter??0,rm)),m=[],y=[],w=[],b=0,S=!1,k=0,A=0,E=(_,D)=>{for(let X of w)X.remaining>0&&(X.match.after===void 0&&(X.match.after=[]),X.match.after.push({cursor:_,line:D}),X.remaining--,b+=D.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(d.test(D)!==l&&m.length<f){let X={cursor:_,line:D};if(p>0&&y.length>0){X.before=y.slice();for(let Z of X.before)b+=Z.line.length}b+=D.length,m.push(X),h>0&&w.push({match:X,remaining:h})}if(p>0)for(y.push({cursor:_,line:D});y.length>p;)y.shift();let L=m.length>=f&&w.length===0,K=b>=u;return L||K};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let D=o.subarray(k,_).toString("utf8"),N=r+k;if(k=_+1,A=k,E(N,D)){S=!0;break}}if(!S&&k<o.length&&this.closed){let _=o.subarray(k).toString("utf8"),D=r+k;E(D,_)&&(S=!0),A=o.length}let P=Math.min(r+A,this.writeCursor),B={matches:m,truncated:S,nextCursor:P,scannedBytes:A};return i>0&&(B.gap=i),this.closed&&P>=this.writeCursor&&(B.eof=!0),B}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(()=>im.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Yi,VM,am=V(()=>{"use strict";Yi=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],VM=new Map(Yi.map(t=>[t.verb,t]))});function dm(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Vi(t,e){return hu(t,e.map(n=>n.modelId))}function hu(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=dm(t),s=e.filter(i=>dm(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var Md=V(()=>{"use strict"});function cm(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 c=t[a];if(c===void 0)continue;let d=mu(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let f=n.get(l);f?f.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=mu(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?_k(r,i.outIndex,Mk(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?$k(c,n.get(f)??[]):c;f!==void 0&&s.has(f)&&!Fk(u)&&(u=Ok(u,s.get(f))),r.push(u);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function mu(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Mk(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function _k(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 $k(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function Fk(t){let n=mu(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Ok(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var lm=V(()=>{"use strict"});function Qi(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 c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=yu(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=wu(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(gu(c))):d==="turn_complete"&&i()}return i(),Hk(s.join(`
18
+ `),n)}function gu(t){let e=Bk(t),n=Nk(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function Bk(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Nk(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of Lk){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${Dk(r,200)}`)}return n}function yu(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 wu(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function Dk(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Hk(t,e){if(t.length<=e)return t;let n=t.split(`
19
19
  `);for(;n.length>0;){let s=um+n.join(`
20
- `);if(s.length<=e)return s;n.shift()}return um}var um,Ok,_d=V(()=>{"use strict";um=`[older history truncated]
21
- `,Ok=["file_path","filePath","path","command","pattern","query"]});function wu(t){let e=[],n=t.synopsis;if(n!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??fm}`),n.goal!==void 0&&n.goal.trim().length>0&&e.push(`[Goal] ${n.goal}`),n.outcome!==void 0&&n.outcome.trim().length>0&&e.push(`[Outcome] ${n.outcome}`);let o=sa("Open threads",n.open_threads);o.length>0&&e.push(o);let a=sa("Decisions",n.decisions);a.length>0&&e.push(a);let c=sa("File edit intentions",n.file_edit_intentions);c.length>0&&e.push(c);let d=sa("Unresolved errors",n.unresolved_errors);d.length>0&&e.push(d);let l=sa("Tool state",n.tool_state);l.length>0&&e.push(l);let f=pm(n.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let u=pm(n.tools_used);u.length>0&&e.push(`[Tools previously used] ${u}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${t.title??fm}`);let{closedText:s,openText:r,keptCount:i}=Hk(t.tail,t.tailK,t.watermark??0,t.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),n!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
20
+ `);if(s.length<=e)return s;n.shift()}return um}var um,Lk,_d=V(()=>{"use strict";um=`[older history truncated]
21
+ `,Lk=["file_path","filePath","path","command","pattern","query"]});function bu(t){let e=[],n=t.synopsis;if(n!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??fm}`),n.goal!==void 0&&n.goal.trim().length>0&&e.push(`[Goal] ${n.goal}`),n.outcome!==void 0&&n.outcome.trim().length>0&&e.push(`[Outcome] ${n.outcome}`);let o=sa("Open threads",n.open_threads);o.length>0&&e.push(o);let a=sa("Decisions",n.decisions);a.length>0&&e.push(a);let c=sa("File edit intentions",n.file_edit_intentions);c.length>0&&e.push(c);let d=sa("Unresolved errors",n.unresolved_errors);d.length>0&&e.push(d);let l=sa("Tool state",n.tool_state);l.length>0&&e.push(l);let f=pm(n.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let u=pm(n.tools_used);u.length>0&&e.push(`[Tools previously used] ${u}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${t.title??fm}`);let{closedText:s,openText:r,keptCount:i}=Uk(t.tail,t.tailK,t.watermark??0,t.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),n!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
22
22
  `)}function sa(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
23
- `)}`}function pm(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function Hk(t,e,n,s){if(t.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Uk(t),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=n).length,f=Math.max(l,s),u=Math.min(f,e,r.length);o=u,a=u>0?r.slice(-u):[]}let c=a.length>0?hm(a):"",d=i?hm([i]):"";return{closedText:c,openText:d,keptCount:o}}function hm(t){let e=[];for(let n of t){n.user.length>0&&e.push("User: "+n.user),n.agent.length>0&&e.push("Assistant: "+n.agent);for(let s of n.tools)e.push(s)}return e.join(`
24
- `)}function Uk(t){let e=[],n=null;for(let r=0;r<t.length;r++){let i=t[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let c=a.sessionUpdate;if(c==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:gu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&n!==null){let d=yu(a.content);d.length>0&&(n.agent+=d)}else c==="tool_call"&&n!==null?n.tools.push(mu(a)):c==="turn_complete"&&n!==null&&(e.push(n),n=null)}let s=n!==null&&n.user.length>0?n:null;return{closed:e,open:s}}var fm,mm=V(()=>{"use strict";_d();fm="(untitled)"});import*as Zn from"fs/promises";async function ra(t,e){let n=O.queueFile(t);if(e.length===0){await Zn.unlink(n).catch(()=>{});return}await Zn.mkdir(O.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
23
+ `)}`}function pm(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function Uk(t,e,n,s){if(t.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=jk(t),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=n).length,f=Math.max(l,s),u=Math.min(f,e,r.length);o=u,a=u>0?r.slice(-u):[]}let c=a.length>0?hm(a):"",d=i?hm([i]):"";return{closedText:c,openText:d,keptCount:o}}function hm(t){let e=[];for(let n of t){n.user.length>0&&e.push("User: "+n.user),n.agent.length>0&&e.push("Assistant: "+n.agent);for(let s of n.tools)e.push(s)}return e.join(`
24
+ `)}function jk(t){let e=[],n=null;for(let r=0;r<t.length;r++){let i=t[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let c=a.sessionUpdate;if(c==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:yu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&n!==null){let d=wu(a.content);d.length>0&&(n.agent+=d)}else c==="tool_call"&&n!==null?n.tools.push(gu(a)):c==="turn_complete"&&n!==null&&(e.push(n),n=null)}let s=n!==null&&n.user.length>0?n:null;return{closed:e,open:s}}var fm,mm=V(()=>{"use strict";_d();fm="(untitled)"});import*as Zn from"fs/promises";async function ra(t,e){let n=O.queueFile(t);if(e.length===0){await Zn.unlink(n).catch(()=>{});return}await Zn.mkdir(O.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
25
25
  `)+`
26
26
  `;await Zn.writeFile(n,s,"utf8")}async function gm(t){let e=O.queueFile(t),n;try{n=await Zn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
27
- `))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 ym(t){let e=O.queueFile(t);await Zn.unlink(e).catch(()=>{})}var bu=V(()=>{"use strict";we()});import{customAlphabet as Sm}from"nanoid";import*as xm from"fs/promises";function sr(){return`m_${Im()}`}function pt(t){return t.startsWith(jt)?t.slice(jt.length):t}function on(t,e){return t.code=e,t}function wm(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Jk.has(s)}function Yk(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 Vk(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 Qk(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 Xi(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 ia(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 Gk(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 Xk(t,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.chunks.push(i.text),t.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.thinkingChars+=i.text.length);return}if(r==="tool_call"){t.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(t.lastUsed=s.used),typeof s.size=="number"&&(t.lastSize=s.size);return}}function Zk(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 eI(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:sr()}}}function ku(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 bm(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 tI(t){let e=nI(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=sI(t.resolver),n}function nI(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 sI(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 Gi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Su(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function rI(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function vm(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}
27
+ `))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 ym(t){let e=O.queueFile(t);await Zn.unlink(e).catch(()=>{})}var vu=V(()=>{"use strict";we()});import{customAlphabet as Sm}from"nanoid";import*as xm from"fs/promises";function rr(){return`m_${Im()}`}function pt(t){return t.startsWith(jt)?t.slice(jt.length):t}function on(t,e){return t.code=e,t}function wm(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Yk.has(s)}function Vk(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 Qk(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 Gk(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 Xi(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 ia(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 Xk(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 Zk(t,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.chunks.push(i.text),t.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.thinkingChars+=i.text.length);return}if(r==="tool_call"){t.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(t.lastUsed=s.used),typeof s.size=="number"&&(t.lastSize=s.size);return}}function eI(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 tI(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:rr()}}}function Iu(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 bm(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 nI(t){let e=sI(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=rI(t.resolver),n}function sI(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 rI(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 Gi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function ku(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function iI(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function vm(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}
28
28
  ${s.join(`
29
- `)}`}function Iu(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 km,Im,vu,jk,qk,Wk,jt,zk,$d,Kk,Zi,Jk,es=V(()=>{"use strict";fu();om();am();Md();lm();mm();bu();Ot();km="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Im=Sm(km,16),vu=Sm(km,16),jk=20,qk=20,Wk=5,jt="hydra_session_";zk=1e3,$d=300*1e3,Kk=64,Zi=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;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){if(this.sessionId=e.sessionId??`${jt}${Im()}`,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.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(n=>n.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let n of e.attentionFlags)this.attentionFlags.set(`${n.source}::${n.reason}`,n);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??zk,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){Xk(this.internalPromptCapture,n);return}this.maybeEmitToolEdges(n),this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>{let s=await this.runAgentRequestChain("session/request_permission",n),r=bm(s.shortCircuit?n:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let 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,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let f=this.transformChain[l];if(n.has(f.name)||!f.intercepts.has(a))continue;let u=`t_${vu()}`,p;try{p=await f.connection.request("hydra-acp/transformer/message",{token:u,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,w=new Set(n),b=r;await new Promise(S=>{let k=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:f.name}),this.runResponseChain(y,new Set([...w,f.name]),m+1,b).then(()=>S()).catch(()=>S()))},$d);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(u,{resolve:()=>S(),timer:k,transformerName:f.name,method:b,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(f.name)}if(r!=="session/update")return;let c=Zk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=Gk(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let 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.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=this.currentModel,l=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let u=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await f({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:u});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Ki({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await zi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let m=wu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let b=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...w!==void 0?{previousSummarizedThroughEntry:w}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await b.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
29
+ `)}`}function xu(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 km,Im,Su,qk,Wk,zk,jt,Kk,$d,Jk,Zi,Yk,es=V(()=>{"use strict";pu();om();am();Md();lm();mm();vu();Ot();km="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Im=Sm(km,16),Su=Sm(km,16),qk=20,Wk=20,zk=5,jt="hydra_session_";Kk=1e3,$d=300*1e3,Jk=64,Zi=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;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){if(this.sessionId=e.sessionId??`${jt}${Im()}`,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.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(n=>n.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let n of e.attentionFlags)this.attentionFlags.set(`${n.source}::${n.reason}`,n);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Kk,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){Zk(this.internalPromptCapture,n);return}this.maybeEmitToolEdges(n),this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>{let s=await this.runAgentRequestChain("session/request_permission",n),r=bm(s.shortCircuit?n:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let 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,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let f=this.transformChain[l];if(n.has(f.name)||!f.intercepts.has(a))continue;let u=`t_${Su()}`,p;try{p=await f.connection.request("hydra-acp/transformer/message",{token:u,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,w=new Set(n),b=r;await new Promise(S=>{let k=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:f.name}),this.runResponseChain(y,new Set([...w,f.name]),m+1,b).then(()=>S()).catch(()=>S()))},$d);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(u,{resolve:()=>S(),timer:k,transformerName:f.name,method:b,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(f.name)}if(r!=="session/update")return;let c=eI(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=Xk(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let 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.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=this.currentModel,l=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let u=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await f({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:u});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Ki({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await zi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let m=bu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let b=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...w!==void 0?{previousSummarizedThroughEntry:w}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await b.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
30
30
  Switched to ${r}.
31
31
  `:`
32
32
  Compaction completed.
33
- `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await Ki({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await zi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=jk){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let f=c.status;(f==="completed"||f==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastClientUpdate(e){let n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",n).catch(()=>{})}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,n,s={}){if(this.closed)throw on(new Error("session is closed"),j.SessionNotFound);if(this.clients.has(e.clientId))throw on(new Error(`client ${e.clientId} is already attached`),j.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=a=>n.raw?a:cm(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!wm(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?ku(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],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 this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.attentionFlags.values()){if(n.source!=="daemon"||!n.reason.startsWith("permission:"))continue;let s=n.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(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 on(new Error("client not attached"),j.SessionNotFound);if(this.closing)throw on(new Error("session is closing; new prompts cannot be accepted"),j.SessionClosing);let r=sr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(rn((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=Gi(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}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:sr()};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.recordCurrentUsageSnapshot(),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>Kk;){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 on(new Error("client not attached"),j.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 c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=sr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId: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=sr(),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 on(new Error("client not attached"),j.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 c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${vu()}`,f;try{f=await c.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 ${c.name} error on ${d}: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??Su(e);if(u==="continue"){f?.payload&&typeof f.payload=="object"&&(o=f.payload),s.add(c.name);continue}if(u==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:Su(e))))},$d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,n,s=new Set,r=0){let i=n,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${vu()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(u){this.logger?.warn(`transformer ${c.name} error on ${o}: ${u.message}`);continue}let f=l?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:l?.payload??rI(e)};if(f==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(f==="processing"){let u=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),u+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},$d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(d,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:c.name,method:m,envelope:p,chainIdx:u,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}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):$d,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));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:Su(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)}async emitToQueue(e,n){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(n??{}).prompt??[],o=sr(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let f={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},u=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{position:u}),this.drainQueue()})}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(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}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=Gi((e??{}).prompt),r=Iu(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=Xi(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=Xi(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=ia(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=Xi(o.options);if(c.length>0){let d=ia(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.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,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:h,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;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}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(Yk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Vk(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(",")}]`),Qk(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){this.modelChangeInFlight=!0;try{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()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{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()}finally{this.modeChangeInFlight=!1}}}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=this.daemonTopLevelCommands(),n=this.aliasableBareVerbs();for(let s of Yi){if(n.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let d=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,f={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(f.description=r.description),e.push(f)}if(c.length>0&&n.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,f={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(f.description=r.description),e.push(f)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,n=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=n(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=n(o.name);a&&e.add(a)}let s=new Map;for(let o of Yi)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,o):c!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,a);return s}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(Yi.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();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=j.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=Yi.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(d.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=j.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(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let f,u=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.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:`
33
+ `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await Ki({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await zi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=qk){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let f=c.status;(f==="completed"||f==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastClientUpdate(e){let n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",n).catch(()=>{})}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,n,s={}){if(this.closed)throw on(new Error("session is closed"),j.SessionNotFound);if(this.clients.has(e.clientId))throw on(new Error(`client ${e.clientId} is already attached`),j.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=a=>n.raw?a:cm(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!wm(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Iu(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],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 this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.attentionFlags.values()){if(n.source!=="daemon"||!n.reason.startsWith("permission:"))continue;let s=n.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(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 on(new Error("client not attached"),j.SessionNotFound);if(this.closing)throw on(new Error("session is closing; new prompts cannot be accepted"),j.SessionClosing);let r=rr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(rn((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=Gi(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}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:rr()};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.recordCurrentUsageSnapshot(),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>Jk;){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 on(new Error("client not attached"),j.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 c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=rr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId: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=rr(),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 on(new Error("client not attached"),j.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 c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Su()}`,f;try{f=await c.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 ${c.name} error on ${d}: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??ku(e);if(u==="continue"){f?.payload&&typeof f.payload=="object"&&(o=f.payload),s.add(c.name);continue}if(u==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:ku(e))))},$d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,n,s=new Set,r=0){let i=n,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${Su()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(u){this.logger?.warn(`transformer ${c.name} error on ${o}: ${u.message}`);continue}let f=l?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:l?.payload??iI(e)};if(f==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(f==="processing"){let u=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),u+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},$d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(d,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:c.name,method:m,envelope:p,chainIdx:u,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}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):$d,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));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:ku(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)}async emitToQueue(e,n){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(n??{}).prompt??[],o=rr(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let f={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},u=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{position:u}),this.drainQueue()})}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(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}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=Gi((e??{}).prompt),r=xu(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=Xi(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=Xi(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=ia(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=Xi(o.options);if(c.length>0){let d=ia(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.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,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:h,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;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}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(Vk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Qk(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(",")}]`),Gk(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){this.modelChangeInFlight=!0;try{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()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{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()}finally{this.modeChangeInFlight=!1}}}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=this.daemonTopLevelCommands(),n=this.aliasableBareVerbs();for(let s of Yi){if(n.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let d=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,f={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(f.description=r.description),e.push(f)}if(c.length>0&&n.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,f={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(f.description=r.description),e.push(f)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,n=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=n(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=n(o.name);a&&e.add(a)}let s=new Map;for(let o of Yi)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,o):c!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,a);return s}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(Yi.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();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=j.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=Yi.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(d.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=j.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(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let f,u=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.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:`
34
34
  ${e}
35
35
  `},_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":"",c=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${c}`});e=`Sessions (${n.length}):
36
36
  ${s.join(`
@@ -64,15 +64,15 @@ Available options:
64
64
  ${l}
65
65
  `},_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:`
66
66
  ${vm(o)}
67
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=pu(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(m=>m.toLowerCase().includes(l)),u=f.length>0?f:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
67
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=hu(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(m=>m.toLowerCase().includes(l)),u=f.length>0?f:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
68
68
  ${p}.
69
69
  ${h}:
70
70
  ${u.join(`
71
71
  `)}
72
72
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};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==="status")return this.runAgentStatusCommandInline();let n=e;if(!n)throw on(new Error("/hydra agent requires an agent id"),j.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(n):void 0)??n;if(r===this.agentId)throw on(new Error(`already on agent ${r}`),j.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw on(new Error("agent restart not configured for this session"),j.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),n=this._summarizedThroughEntry;if(e==null&&n==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${n}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${n??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
73
73
  `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw on(new Error("session is closing"),j.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.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(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 d of r){if(d.method!=="session/update")continue;let f=(d.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let h=Gi(f.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=f.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=f.status,m=f.title;(h==="completed"||h==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${h}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.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.`,c=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,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
74
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let n=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=wu({synopsis:e,title:n,tail:s,tailK:qk,tailFloor:Wk,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let 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 Pd(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??Ji,Ji)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="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=j.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"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 s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ym(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>xm.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,n,s){this._setAttentionFlag(e,n,s,!0)}_setAttentionFlag(e,n,s,r){let i=`${e}::${n}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:n,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,n){this._clearAttentionFlag(e,n,!0)}_clearAttentionFlag(e,n,s){let r=`${e}::${n}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,n)=>e.raisedAt-n.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(n=>n.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let n of this.attentionFlagsChangeHandlers)try{n(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||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.disposeIdleHandlers()}onIdle(e,n){let s={fn:e,once:!!n?.once,debounceMs:n?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let n=[...this.idleHandlers];for(let s of n){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let n=e.update;if(!n||typeof n!="object")return;let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let f=l.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let u=l.line,p={path:f,toolCallId:i};typeof u=="number"&&(p.line=u),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}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(typeof n.sessionId=="string"&&n.sessionId!==this.sessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!wm(e,r),o=i?eI(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 c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}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 on(new Error("no clients attached to handle permission request"),j.PermissionDenied);let s=this.rewriteForClient(e),r=bm(s),i=sr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,f=[],u=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===j.MethodNotFound;function w(b){if(l)return;let S=b.connection.request("session/request_permission",s);f.push({client:b}),u++,S.then(k=>{u--,m(()=>{let A=tI({toolCallId:r,result:k,resolver:b});for(let E of f)E.client.clientId!==b.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:A}).catch(()=>{});c(k)})}).catch(k=>{if(u--,y(k)||(p=k),u===0&&!l){let A=p??on(new Error("no client handled permission request"),j.PermissionDenied);m(()=>d(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,w);for(let b of n)w(b)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:sr(),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,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{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(()=>ra(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,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Gi(e.prompt).replace(/\s+$/,""),s=!n.includes(`
75
- `)&&n.startsWith("/")?n.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(n);else if(s==="/model")a=await this.handleModelCommand(n);else if(i){let c=n.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(n,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){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),a}return this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};Jk=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"])});import{z as eo}from"zod";var iI,Am,Cm=V(()=>{"use strict";iI=eo.object({source:eo.string(),reason:eo.string(),raisedAt:eo.number(),payload:eo.unknown()}),Am=eo.array(iI)});import{z as Ne}from"zod";function Em(t){let e=t.trim();if(e.length===0)return;let n=to(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=to(e.slice(i,o+1)))}if(n===void 0){let i=Mm(e);i!==void 0&&(n=to(i))}if(n===void 0||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,Tm))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=oa.safeParse(s.synopsis);i.success&&oI(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Pm(t){let e=t.trim();if(e.length===0)return;let n=to(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=to(e.slice(d,l+1)))}if(n===void 0){let d=Mm(e);d!==void 0&&(n=to(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Tm))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],f=Ne.array(Ne.string()).safeParse(l);f.success&&l.length>0&&(i[d]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function to(t){try{return JSON.parse(t)}catch{return}}function Mm(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function oI(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||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var Rm,oa,Tm,xu,Au,Fd=V(()=>{"use strict";Rm=Ne.object({status:Ne.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Ne.number(),iter:Ne.number().int().nonnegative().optional(),attempts:Ne.number().int().nonnegative().optional(),lastError:Ne.string().optional(),worker:Ne.object({upstreamSessionId:Ne.string(),pid:Ne.number().int().nonnegative()}).optional()}),oa=Ne.object({goal:Ne.string().optional(),outcome:Ne.string().optional(),files_touched:Ne.array(Ne.string()).optional(),tools_used:Ne.array(Ne.string()).optional(),rejected_approaches:Ne.array(Ne.string()).optional(),open_threads:Ne.array(Ne.string()).optional(),decisions:Ne.array(Ne.string()).optional(),file_edit_intentions:Ne.array(Ne.string()).optional(),unresolved_errors:Ne.array(Ne.string()).optional(),tool_state:Ne.array(Ne.string()).optional()}),Tm=200,xu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
74
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let n=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=bu({synopsis:e,title:n,tail:s,tailK:Wk,tailFloor:zk,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let 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 Pd(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??Ji,Ji)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="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=j.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"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 s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ym(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>xm.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,n,s){this._setAttentionFlag(e,n,s,!0)}_setAttentionFlag(e,n,s,r){let i=`${e}::${n}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:n,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,n){this._clearAttentionFlag(e,n,!0)}_clearAttentionFlag(e,n,s){let r=`${e}::${n}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,n)=>e.raisedAt-n.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(n=>n.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let n of this.attentionFlagsChangeHandlers)try{n(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||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.disposeIdleHandlers()}onIdle(e,n){let s={fn:e,once:!!n?.once,debounceMs:n?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let n=[...this.idleHandlers];for(let s of n){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let n=e.update;if(!n||typeof n!="object")return;let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let f=l.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let u=l.line,p={path:f,toolCallId:i};typeof u=="number"&&(p.line=u),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}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(typeof n.sessionId=="string"&&n.sessionId!==this.sessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!wm(e,r),o=i?tI(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 c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}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 on(new Error("no clients attached to handle permission request"),j.PermissionDenied);let s=this.rewriteForClient(e),r=bm(s),i=rr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,f=[],u=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===j.MethodNotFound;function w(b){if(l)return;let S=b.connection.request("session/request_permission",s);f.push({client:b}),u++,S.then(k=>{u--,m(()=>{let A=nI({toolCallId:r,result:k,resolver:b});for(let E of f)E.client.clientId!==b.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:A}).catch(()=>{});c(k)})}).catch(k=>{if(u--,y(k)||(p=k),u===0&&!l){let A=p??on(new Error("no client handled permission request"),j.PermissionDenied);m(()=>d(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,w);for(let b of n)w(b)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:rr(),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,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{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(()=>ra(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,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Gi(e.prompt).replace(/\s+$/,""),s=!n.includes(`
75
+ `)&&n.startsWith("/")?n.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(n);else if(s==="/model")a=await this.handleModelCommand(n);else if(i){let c=n.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(n,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){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),a}return this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};Yk=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"])});import{z as eo}from"zod";var oI,Am,Cm=V(()=>{"use strict";oI=eo.object({source:eo.string(),reason:eo.string(),raisedAt:eo.number(),payload:eo.unknown()}),Am=eo.array(oI)});import{z as De}from"zod";function Em(t){let e=t.trim();if(e.length===0)return;let n=to(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=to(e.slice(i,o+1)))}if(n===void 0){let i=Mm(e);i!==void 0&&(n=to(i))}if(n===void 0||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,Tm))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=oa.safeParse(s.synopsis);i.success&&aI(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Pm(t){let e=t.trim();if(e.length===0)return;let n=to(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=to(e.slice(d,l+1)))}if(n===void 0){let d=Mm(e);d!==void 0&&(n=to(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Tm))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],f=De.array(De.string()).safeParse(l);f.success&&l.length>0&&(i[d]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function to(t){try{return JSON.parse(t)}catch{return}}function Mm(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function aI(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||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var Rm,oa,Tm,Au,Cu,Fd=V(()=>{"use strict";Rm=De.object({status:De.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:De.number(),iter:De.number().int().nonnegative().optional(),attempts:De.number().int().nonnegative().optional(),lastError:De.string().optional(),worker:De.object({upstreamSessionId:De.string(),pid:De.number().int().nonnegative()}).optional()}),oa=De.object({goal:De.string().optional(),outcome:De.string().optional(),files_touched:De.array(De.string()).optional(),tools_used:De.array(De.string()).optional(),rejected_approaches:De.array(De.string()).optional(),open_threads:De.array(De.string()).optional(),decisions:De.array(De.string()).optional(),file_edit_intentions:De.array(De.string()).optional(),unresolved_errors:De.array(De.string()).optional(),tool_state:De.array(De.string()).optional()}),Tm=200,Au=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
76
76
  {
77
77
  "title": "short summary, max 80 chars",
78
78
  "synopsis": {
@@ -82,7 +82,7 @@ ${h}:
82
82
  "open_threads": ["work started but not finished"]
83
83
  }
84
84
  }
85
- Use empty arrays/strings where a field doesn't apply.`;Au=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
85
+ Use empty arrays/strings where a field doesn't apply.`;Cu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
86
86
  {
87
87
  "title": "short summary, max 80 chars",
88
88
  "goal": "the user's original ask",
@@ -94,302 +94,302 @@ Use empty arrays/strings where a field doesn't apply.`;Au=`Reply with ONLY a JSO
94
94
  "unresolved_errors": ["errors left open at session end"],
95
95
  "tool_state": ["runtime state relevant for recall"]
96
96
  }
97
- Use empty arrays/strings where a field doesn't apply.`});import*as no from"fs/promises";import*as u_ from"path";import{customAlphabet as aI}from"nanoid";import{z as ne}from"zod";function aa(){return`${lI}${cI()}`}function hI(t){if(!Cu.test(t))throw new Error(`unsafe session id: ${t}`)}function Mu(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,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,pendingAgentSwap:t.pendingAgentSwap,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,attentionFlags:t.attentionFlags??[],extensionState:t.extensionState??{},createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var dI,cI,lI,Ru,Tu,uI,Eu,Pu,fI,pI,Cu,Od,_u=V(()=>{"use strict";we();Or();Cm();Fd();dI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cI=aI(dI,16),lI="hydra_lineage_";Ru=ne.object({name:ne.string(),description:ne.string().optional()}),Tu=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),uI=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Eu=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Pu=ne.object({name:ne.string(),version:ne.string().optional()}),fI=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),pI=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:oa.optional(),compactionState:Rm.optional(),rollbackBreadcrumb:fI.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Eu.optional(),agentCommands:ne.array(Ru).optional(),agentModes:ne.array(Tu).optional(),agentModels:ne.array(uI).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Pu.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Am.default([]).optional(),extensionState:ne.record(ne.string(),ne.record(ne.string(),ne.unknown())).default({}).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Cu=/^[A-Za-z0-9_-]+$/;Od=class{async write(e){hI(e.sessionId);let n={version:1,...e};await nn(O.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Cu.test(e))return;let n=await yn(O.sessionFile(e));if(n!==void 0)try{return pI.parse(n)}catch{return}}async delete(e){if(Cu.test(e)){try{await no.unlink(O.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await no.rmdir(O.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 no.readdir(O.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 gI}from"url";import*as da from"path";import*as Bd from"fs";function yI(){try{let t=da.dirname(gI(import.meta.url));for(let e=0;e<8;e+=1){let n=da.join(t,"package.json");if(Bd.existsSync(n)){let r=JSON.parse(Bd.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=da.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var be,qr,an=V(()=>{"use strict";be=yI(),qr="hydra-acp-cat"});function $u(t){let e=new Map;for(let n of Um(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 Nm(t){return $u(t).map(e=>e.name)}function Fu(t){let e=new Map;for(let n of Um(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 Dm(t){return Fu(t).map(e=>e.path)}function Hm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Um(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 c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:Lm(i),paths:new Set},e.set(c,d)):d.toolName=Lm(i);for(let l of Bm(i.rawInput,i.locations))d.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 c of Bm(i.rawInput,i.locations))a.paths.add(c)}return e}function Lm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Bm(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 Ou=V(()=>{"use strict"});import{promises as ca}from"fs";import*as Uu from"path";async function la(t){let e;try{e=await ca.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return PI(e)}function PI(t){let e=[];for(let n of t.split(`
98
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function ua(t,e,n=Xm){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 zr(t,e){await ca.mkdir(Uu.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await ca.writeFile(t,n.length>0?n.join(`
97
+ Use empty arrays/strings where a field doesn't apply.`});import*as no from"fs/promises";import*as w_ from"path";import{customAlphabet as dI}from"nanoid";import{z as ne}from"zod";function aa(){return`${uI}${lI()}`}function mI(t){if(!Ru.test(t))throw new Error(`unsafe session id: ${t}`)}function _u(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,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,pendingAgentSwap:t.pendingAgentSwap,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,attentionFlags:t.attentionFlags??[],extensionState:t.extensionState??{},createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var cI,lI,uI,Tu,Eu,fI,Pu,Mu,pI,hI,Ru,Od,$u=V(()=>{"use strict";we();Or();Cm();Fd();cI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",lI=dI(cI,16),uI="hydra_lineage_";Tu=ne.object({name:ne.string(),description:ne.string().optional()}),Eu=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),fI=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Pu=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Mu=ne.object({name:ne.string(),version:ne.string().optional()}),pI=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),hI=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:oa.optional(),compactionState:Rm.optional(),rollbackBreadcrumb:pI.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Pu.optional(),agentCommands:ne.array(Tu).optional(),agentModes:ne.array(Eu).optional(),agentModels:ne.array(fI).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Mu.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Am.default([]).optional(),extensionState:ne.record(ne.string(),ne.record(ne.string(),ne.unknown())).default({}).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Ru=/^[A-Za-z0-9_-]+$/;Od=class{async write(e){mI(e.sessionId);let n={version:1,...e};await nn(O.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Ru.test(e))return;let n=await yn(O.sessionFile(e));if(n!==void 0)try{return hI.parse(n)}catch{return}}async delete(e){if(Ru.test(e)){try{await no.unlink(O.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await no.rmdir(O.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 no.readdir(O.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 yI}from"url";import*as da from"path";import*as Bd from"fs";function wI(){try{let t=da.dirname(yI(import.meta.url));for(let e=0;e<8;e+=1){let n=da.join(t,"package.json");if(Bd.existsSync(n)){let r=JSON.parse(Bd.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=da.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var be,qr,an=V(()=>{"use strict";be=wI(),qr="hydra-acp-cat"});function Fu(t){let e=new Map;for(let n of Um(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 Nm(t){return Fu(t).map(e=>e.name)}function Ou(t){let e=new Map;for(let n of Um(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 Dm(t){return Ou(t).map(e=>e.path)}function Hm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Um(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 c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:Lm(i),paths:new Set},e.set(c,d)):d.toolName=Lm(i);for(let l of Bm(i.rawInput,i.locations))d.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 c of Bm(i.rawInput,i.locations))a.paths.add(c)}return e}function Lm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Bm(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 Lu=V(()=>{"use strict"});import{promises as ca}from"fs";import*as ju from"path";async function la(t){let e;try{e=await ca.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return OI(e)}function OI(t){let e=[];for(let n of t.split(`
98
+ `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function ua(t,e,n=Zm){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 zr(t,e){await ca.mkdir(ju.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await ca.writeFile(t,n.length>0?n.join(`
99
99
  `)+`
100
- `:"")}async function Zm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await ca.mkdir(Uu.dirname(t),{recursive:!0}),await ca.appendFile(t,JSON.stringify(n)+`
101
- `,{encoding:"utf8"}))}function Ud(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function ju(t,e,n=Xm){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=ua(r,o,n)))}return r}var Xm,jd=V(()=>{"use strict";Xm=500});import{z as _e}from"zod";function fa(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 On(t){return $I.parse(t)}var MI,_I,$I,Kr=V(()=>{"use strict";_u();Fd();MI=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),_I=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:oa.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:Eu.optional(),agentCommands:_e.array(Ru).optional(),agentModes:_e.array(Tu).optional(),interactive:_e.boolean().optional(),originatingClient:Pu.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),$I=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:_I,history:_e.array(MI),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as YI}from"crypto";function Xu(t){if(Array.isArray(t))return t.map(Xu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Xu(t[n]);return e}return t}function ir(t){let{tui:e,...n}=t,s=JSON.stringify(Xu(n));return YI("sha256").update(s).digest("hex").slice(0,16)}var ba=V(()=>{"use strict";Qe()});function Zu(t){return Math.floor(t/4)}function yg(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=Zu(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function wg(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var ef=V(()=>{"use strict"});function va(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var bg=V(()=>{"use strict"});import{posix as ox}from"path";import ax from"strip-ansi";function wt(t){return ax(t).replace(dx,"")}function Pe(t){return wt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ss(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 hx(n);case"agent_thought_chunk":case"agent_thought":return mx(n);case"user_message_chunk":return gx(n);case"prompt_received":return yx(n);case"tool_call":return wx(n,e);case"tool_call_update":return Ix(n,e);case"plan":return Cx(n);case"current_mode_update":return Rx(n);case"current_model_update":return Tx(n);case"turn_complete":return Ex(n);case"usage_update":return px(n);case"available_commands_update":return ux(n);case"available_modes_update":return fx(n);case"session_info_update":return lx(n);case"config_option_update":return cx(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function cx(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 lx(t){let e=ct(t,"title"),n=e!==void 0?Pe(e):void 0,s=t._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(n===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function oc(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:Pe(r)};typeof s.description=="string"&&(i.description=Pe(s.description)),e.push(i)}return e}function ux(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:oc(e)}:null}function fx(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:Pe(r.id)};typeof r.name=="string"&&(i.name=Pe(r.name)),typeof r.description=="string"&&(i.description=Pe(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function px(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 hx(t){let e=Sa(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:va(t)}}function mx(t){let e=typeof t.text=="string"?wt(t.text):Sa(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:va(t)}}function gx(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=Sa(t.content);return n===null?null:{kind:"user-text",text:n}}function yx(t){let e=Px(t.prompt);return e===null?null:{kind:"user-text",text:e}}function kg(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function vg(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 ac(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=vg(r.oldText),o=vg(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 Ig(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:wt(n)}function wx(t,e={}){let n=ct(t,"toolCallId")??ct(t,"id");if(!n)return null;let s=ct(t,"title")??ct(t,"name")??ct(t,"label")??"tool call",r=ct(t,"name")??ct(t,"title");if(kg(r)){let h=Ig(t);if(h!==null){let m=ct(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Cg(Pe(s),t,e),o=ct(t,"status"),a=ct(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=ac(t);d!==null&&(c.editDiff=d);let l=Ag(t);l!==void 0&&(c.detail=l);let f=tf(t);f!==void 0&&(c.detailFull=f);let u=xg(t);u!==void 0&&(c.locations=u);let p=va(t);return p!==void 0&&(c.workerTaskId=p),c}function xg(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function Ag(t){let e=tf(t);if(e===void 0)return;let n=Pe(e),s=t.rawInput;return s&&typeof s.command=="string"?Sx(n,Sg):kx(n,Sg)}function tf(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return wt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");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 dt(Pe(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return dt(Pe(s))}}}function vx(t){for(let e of bx)if(t.startsWith(e))return!0;return!1}function Cg(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return dt(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 dt(o)}return vx(t)?dt(`/${t}`):n.cwd&&n.cwd.length>0?dt(ox.resolve(n.cwd,t)):t}function Sx(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function kx(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 Ix(t,e={}){let n=ct(t,"toolCallId")??ct(t,"id");if(!n)return null;let s=ct(t,"title"),r=s!==void 0?Cg(Pe(s),t,e):void 0,i=ct(t,"status"),o=ac(t),a=Ag(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=ct(t,"name")??s;if(kg(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=Ig(t);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=tf(t);f!==void 0&&(l.detailFull=f);let u=xg(t);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=xx(t);h!==null&&(l.errorText=h),Ax(t,h)&&(l.upstreamInterrupted=!0)}let p=va(t);return p!==void 0&&(l.workerTaskId=p),l}function xx(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Sa(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 wt(s)}return null}function Ax(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 Cx(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"?Pe(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 Rx(t){let e=ct(t,"currentModeId")??ct(t,"currentMode")??ct(t,"mode");return e?{kind:"mode-changed",mode:Pe(e)}:null}function Tx(t){let e=ct(t,"currentModel")??ct(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:Pe(e),...s&&s.length>0?{availableModels:s}:{}}}function Ex(t){let e=ct(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 Sa(t){if(typeof t=="string")return wt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?wt(e.text):null}function Px(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Sa(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function ct(t,e){let n=t[e];return typeof n=="string"?n:void 0}var dx,Sg,bx,or=V(()=>{"use strict";we();bg();dx=/[\x00-\x08\x0b-\x1f\x7f]/g;Sg=64;bx=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function io(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 c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=_x(o);if(d.length===0)continue;let l=d;if(c!==void 0){let f=e.get(c)??[],u=[];for(let p of d)f.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(c,[...f,...u]),l=u}for(let f of l)Mx(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function oo(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 Mx(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 _x(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 c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,f=typeof d.new_string=="string"?d.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 c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=ac(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var dc=V(()=>{"use strict";or()});function rs(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 c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:j.ParseError,message:`Failed to parse WS frame: ${c.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,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var uo=V(()=>{"use strict";Ot()});import{spawn as ZA}from"child_process";import{setTimeout as eC}from"timers/promises";async function hy(){let t=await Cs();if(t&&Fn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function tC(t){let e=await Yr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===ir(t)?"match":"mismatch":"missing"}async function cr(t){let e=await tC(t);if(e!=="match"){if(e==="mismatch"){let n=Gn();throw new Error(`config changed since daemon started \u2014 run \`${n} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
102
- `),Ic(),await xc(t)}}async function kc(t){let e=await hy();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Yr(t,e=1e3){let n=await hy();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function Ic(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");ZA(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function xc(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await kc(t))return;await eC(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Vr=V(()=>{"use strict";Xo();ba();Ni()});import*as my from"fs";import*as ho from"fs/promises";async function mo(t,e,n){let s=sC(e),r;try{r=await ho.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
103
- `),process.exit(1);return}throw c}let i=await nC(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
104
- `);let o=!1,a=my.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await ho.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await ho.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function nC(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await ho.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 d=o.split(`
100
+ `:"")}async function eg(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await ca.mkdir(ju.dirname(t),{recursive:!0}),await ca.appendFile(t,JSON.stringify(n)+`
101
+ `,{encoding:"utf8"}))}function Ud(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function qu(t,e,n=Zm){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=ua(r,o,n)))}return r}var Zm,jd=V(()=>{"use strict";Zm=500});import{z as _e}from"zod";function fa(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 On(t){return NI.parse(t)}var LI,BI,NI,Kr=V(()=>{"use strict";$u();Fd();LI=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),BI=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:oa.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:Pu.optional(),agentCommands:_e.array(Tu).optional(),agentModes:_e.array(Eu).optional(),interactive:_e.boolean().optional(),originatingClient:Mu.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),NI=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:BI,history:_e.array(LI),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as ZI}from"crypto";function Zu(t){if(Array.isArray(t))return t.map(Zu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Zu(t[n]);return e}return t}function or(t){let{tui:e,...n}=t,s=JSON.stringify(Zu(n));return ZI("sha256").update(s).digest("hex").slice(0,16)}var ba=V(()=>{"use strict";Ge()});function ef(t){return Math.floor(t/4)}function wg(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=ef(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function bg(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var tf=V(()=>{"use strict"});function va(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var vg=V(()=>{"use strict"});import{posix as ux}from"path";import fx from"strip-ansi";function wt(t){return fx(t).replace(px,"")}function Pe(t){return wt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ss(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 bx(n);case"agent_thought_chunk":case"agent_thought":return vx(n);case"user_message_chunk":return Sx(n);case"prompt_received":return kx(n);case"tool_call":return Ix(n,e);case"tool_call_update":return Tx(n,e);case"plan":return Mx(n);case"current_mode_update":return _x(n);case"current_model_update":return $x(n);case"turn_complete":return Fx(n);case"usage_update":return wx(n);case"available_commands_update":return gx(n);case"available_modes_update":return yx(n);case"session_info_update":return mx(n);case"config_option_update":return hx(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function hx(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 mx(t){let e=ct(t,"title"),n=e!==void 0?Pe(e):void 0,s=t._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(n===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function oc(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:Pe(r)};typeof s.description=="string"&&(i.description=Pe(s.description)),e.push(i)}return e}function gx(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:oc(e)}:null}function yx(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:Pe(r.id)};typeof r.name=="string"&&(i.name=Pe(r.name)),typeof r.description=="string"&&(i.description=Pe(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function wx(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 bx(t){let e=Sa(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:va(t)}}function vx(t){let e=typeof t.text=="string"?wt(t.text):Sa(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:va(t)}}function Sx(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=Sa(t.content);return n===null?null:{kind:"user-text",text:n}}function kx(t){let e=Ox(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Ig(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Sg(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 ac(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=Sg(r.oldText),o=Sg(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 xg(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:wt(n)}function Ix(t,e={}){let n=ct(t,"toolCallId")??ct(t,"id");if(!n)return null;let s=ct(t,"title")??ct(t,"name")??ct(t,"label")??"tool call",r=ct(t,"name")??ct(t,"title");if(Ig(r)){let h=xg(t);if(h!==null){let m=ct(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Rg(Pe(s),t,e),o=ct(t,"status"),a=ct(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=ac(t);d!==null&&(c.editDiff=d);let l=Cg(t);l!==void 0&&(c.detail=l);let f=nf(t);f!==void 0&&(c.detailFull=f);let u=Ag(t);u!==void 0&&(c.locations=u);let p=va(t);return p!==void 0&&(c.workerTaskId=p),c}function Ag(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function Cg(t){let e=nf(t);if(e===void 0)return;let n=Pe(e),s=t.rawInput;return s&&typeof s.command=="string"?Cx(n,kg):Rx(n,kg)}function nf(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return wt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");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 dt(Pe(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return dt(Pe(s))}}}function Ax(t){for(let e of xx)if(t.startsWith(e))return!0;return!1}function Rg(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return dt(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 dt(o)}return Ax(t)?dt(`/${t}`):n.cwd&&n.cwd.length>0?dt(ux.resolve(n.cwd,t)):t}function Cx(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Rx(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 Tx(t,e={}){let n=ct(t,"toolCallId")??ct(t,"id");if(!n)return null;let s=ct(t,"title"),r=s!==void 0?Rg(Pe(s),t,e):void 0,i=ct(t,"status"),o=ac(t),a=Cg(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=ct(t,"name")??s;if(Ig(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=xg(t);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=nf(t);f!==void 0&&(l.detailFull=f);let u=Ag(t);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=Ex(t);h!==null&&(l.errorText=h),Px(t,h)&&(l.upstreamInterrupted=!0)}let p=va(t);return p!==void 0&&(l.workerTaskId=p),l}function Ex(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Sa(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 wt(s)}return null}function Px(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 Mx(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"?Pe(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 _x(t){let e=ct(t,"currentModeId")??ct(t,"currentMode")??ct(t,"mode");return e?{kind:"mode-changed",mode:Pe(e)}:null}function $x(t){let e=ct(t,"currentModel")??ct(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:Pe(e),...s&&s.length>0?{availableModels:s}:{}}}function Fx(t){let e=ct(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 Sa(t){if(typeof t=="string")return wt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?wt(e.text):null}function Ox(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Sa(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function ct(t,e){let n=t[e];return typeof n=="string"?n:void 0}var px,kg,xx,ar=V(()=>{"use strict";we();vg();px=/[\x00-\x08\x0b-\x1f\x7f]/g;kg=64;xx=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function io(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 c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=Bx(o);if(d.length===0)continue;let l=d;if(c!==void 0){let f=e.get(c)??[],u=[];for(let p of d)f.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(c,[...f,...u]),l=u}for(let f of l)Lx(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function oo(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 Lx(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 Bx(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 c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,f=typeof d.new_string=="string"?d.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 c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=ac(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var dc=V(()=>{"use strict";ar()});function rs(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 c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:j.ParseError,message:`Failed to parse WS frame: ${c.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,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var uo=V(()=>{"use strict";Ot()});import{spawn as rC}from"child_process";import{setTimeout as iC}from"timers/promises";async function my(){let t=await Cs();if(t&&Fn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function oC(t){let e=await Yr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===or(t)?"match":"mismatch":"missing"}async function lr(t){let e=await oC(t);if(e!=="match"){if(e==="mismatch"){let n=Gn();throw new Error(`config changed since daemon started \u2014 run \`${n} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
102
+ `),Ic(),await xc(t)}}async function kc(t){let e=await my();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Yr(t,e=1e3){let n=await my();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function Ic(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");rC(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function xc(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await kc(t))return;await iC(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Vr=V(()=>{"use strict";Xo();ba();Ni()});import*as gy from"fs";import*as ho from"fs/promises";async function mo(t,e,n){let s=dC(e),r;try{r=await ho.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
103
+ `),process.exit(1);return}throw c}let i=await aC(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
104
+ `);let o=!1,a=gy.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await ho.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await ho.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function aC(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await ho.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 d=o.split(`
105
105
  `).slice(-n-1);process.stdout.write(d.join(`
106
106
  `)),o.endsWith(`
107
107
  `)||process.stdout.write(`
108
- `)}finally{await r.close()}return e}function Ac(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 sC(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}
108
+ `)}finally{await r.close()}return e}function Ac(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 dC(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}
109
109
  `),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}
110
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var Aa=V(()=>{"use strict"});import{WebSocket as oC}from"ws";async function Qr(t,e,n=aC){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=ea(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.autoSelectFamily!==void 0&&(s.autoSelectFamily=i.autoSelectFamily),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new oC(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new uf(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=f=>{clearTimeout(c),o.off("open",d),i(f)};o.once("open",d),o.once("error",l)})}var aC,uf,Ca=V(()=>{"use strict";ta();aC=1e4,uf=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as Cc from"fs/promises";function dC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function yo(){let t=await Cs();if(t&&Fn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await Ae();return ky(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function ky(t,e,n){return`${n?"https":"http"}://${dC(t)}:${e}`}async function Fe(t,e={}){let n=await Fr(),s=await yo(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(f){if(e.rethrowNetworkError)throw f;process.stderr.write(`Could not reach daemon at ${s}: ${f.message}
110
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var Aa=V(()=>{"use strict"});import{WebSocket as uC}from"ws";async function Qr(t,e,n=fC){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=ea(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.autoSelectFamily!==void 0&&(s.autoSelectFamily=i.autoSelectFamily),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new uC(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new ff(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=f=>{clearTimeout(c),o.off("open",d),i(f)};o.once("open",d),o.once("error",l)})}var fC,ff,Ca=V(()=>{"use strict";ta();fC=1e4,ff=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as Cc from"fs/promises";function pC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function yo(){let t=await Cs();if(t&&Fn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await Ae();return Iy(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Iy(t,e,n){return`${n?"https":"http"}://${pC(t)}:${e}`}async function Oe(t,e={}){let n=await Fr(),s=await yo(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(f){if(e.rethrowNetworkError)throw f;process.stderr.write(`Could not reach daemon at ${s}: ${f.message}
111
111
  `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let f=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(f=p)}let u=e.errorPrefix??"Daemon returned";process.stderr.write(`${u} ${f}
112
112
  `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function wo(t){let e;t instanceof Date?e=t.getTime():typeof t=="string"?e=Date.parse(t):e=t;let n=Math.max(0,Date.now()-e),s=Math.floor(n/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Rc(t,e){let n=e!=="agent",s=n?[]:void 0,r=[],i={},o=!0,a=0;for(;a<t.length;){let c=t[a];if(c==="--command"){let d=t[a+1];d===void 0&&(process.stderr.write(`--command requires a value
113
- `),process.exit(2)),s=n?cC(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
113
+ `),process.exit(2)),s=n?hC(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
114
114
  `),process.exit(2)),r=d.split(",").filter(l=>l.length>0),a+=2;continue}if(c==="--env"){let d=t[a+1];d===void 0&&(process.stderr.write(`--env requires KEY=VALUE
115
115
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
116
116
  `),process.exit(2)),i[d.slice(0,l)]=d.slice(l+1),a+=2;continue}if(c==="--disabled"&&e!=="agent"){o=!1,a+=1;continue}process.stderr.write(`Unknown flag: ${c}
117
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function cC(t){return t.split(/\s+/).filter(e=>e.length>0)}async function bo(){let t=await Cc.readFile(O.config(),"utf8");return JSON.parse(t)}async function ff(t){await Cc.writeFile(O.config(),JSON.stringify(t,null,2)+`
118
- `,{encoding:"utf8",mode:384})}var lr=V(()=>{"use strict";Qe();xs();we();Ni();Ca()});async function ln(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new pf(t,n):c}finally{clearTimeout(a)}}async function Ln(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 ln(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);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??"warm",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,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function Iy(t,e=fetch){let n=await ln(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await ln(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.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 Gr(t,e=fetch){let n=await ln(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);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,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function Tc(t,e,n={},s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},18e4,s);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 os(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function xy(t,e,n,s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Ay(t,e,n,s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Cy(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);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 Ry(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await ln(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function Ty(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Ec(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="warm"?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 pf,Ra=V(()=>{"use strict";pf=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function hf(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Ey(t,e){let n=t??"?",s=hf(e);return s?`${n}${lC}${s}`:n}function Py(t){return t??"?"}function My(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:mf(e,n)}function mf(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var lC,gf=V(()=>{"use strict";lC="\u2022"});function _y(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(!Mc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Mc.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function ko(t,e=Date.now()){return{session:pt(t.sessionId),upstream:pC(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:hC(t.status,t.busy,t.awaitingInput,fC(t.compactionState),t.forkSynthesisState),agent:Py(t.agentId),model:hf(t.currentModel)??"-",age:mC(t.updatedAt,e),title:t.title??"-",cwd:dt(t.cwd),cost:My(t.currentUsage)}}function fC(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function pC(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function hC(t,e,n,s,r){return t==="cold"?"COLD":n?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function Io(t,e={}){let n=e.columns??vo,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]=gC(So[r],t.map(i=>i[r]));return s}function mC(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 c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function gC(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function ur(t,e,n,s={}){let r=s.columns??vo,i=s.cwdMaxWidth??uC,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((S,k)=>k===r.length-1?t[S]:o(S)).join(Pc);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>yf.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Pc);return b.length>n?b.slice(0,n):b}let d=r.filter(b=>!yf.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),f=n-d-l*Pc.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:b,i:S}of a){if(S===c)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],A=Math.min(k,Math.max(0,p-1));u.set(S,A),p=Math.max(0,p-A)}u.set(c,Math.max(0,p));let h=r.length-1,m=(b,S,k)=>{if(b==="cwd")return Ta(t[b],S).padEnd(S);let A=yC(t[b],S);return k?A:A.padEnd(S)},w=r.map((b,S)=>yf.has(b)?m(b,u.get(S)??0,S===h):o(b)).join(Pc);return w.length>n?w.slice(0,n):w}function yC(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function Ta(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 Mc,vo,yf,So,Pc,uC,_c=V(()=>{"use strict";gf();we();es();Mc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],vo=["session","state","age","cwd","title","agent","cost"],yf=new Set(["cwd","title"]),So={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Pc=" ",uC=32});import{spawn as RC}from"child_process";import{Writable as TC}from"stream";function $c(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=EC(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??RC,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}
119
- `)});let c=new TC({write(l,f,u){if(!a.writable){u();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){u(h);return}u()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
120
- `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function EC(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 wf=V(()=>{"use strict"});import PC from"chalk";import{highlight as MC,supportsLanguage as Fc}from"cli-highlight";import Lc from"string-width";function pr(t,e={}){switch(t.kind){case"user-text":{let n=bf(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 bf(t.text," ","agent");case"agent-thought":return bf(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return eR(t,e.maxPlanItems??XC);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 vf(t,e){return fr(t,e).styled}function fr(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.italicReset??"^:",o=e?.linkOpen??"^C^_",a=e?.linkReset??"^:",c="",d=0,l=!1,f=[],u=0;for(;u<t.length;){let p=t[u];if(p==="\\"&&u+1<t.length){let h=t[u+1];if(h==="*"||h==="_"||h==="`"||h==="["||h==="]"||h==="\\"){c+=h,d+=1,u+=2;continue}}if(p==="^"){c+="^^",d+=1,u+=1;continue}if(p==="*"&&t[u+1]==="*"){let h=t.indexOf("**",u+2);if(h!==-1&&h>u+2){let m=t.slice(u+2,h),y=fr(m,e),w=d;c+=`^+${y.styled}${r}`;for(let b of y.links)f.push({start:w+b.start,end:w+b.end,url:b.url});d+=y.cleanLength,y.ansi&&(l=!0),u=h+2;continue}}if(p==="*"&&t[u+1]!=="*"){let h=u>0?t[u-1]:"",m=t[u+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
117
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function hC(t){return t.split(/\s+/).filter(e=>e.length>0)}async function bo(){let t=await Cc.readFile(O.config(),"utf8");return JSON.parse(t)}async function pf(t){await Cc.writeFile(O.config(),JSON.stringify(t,null,2)+`
118
+ `,{encoding:"utf8",mode:384})}var ur=V(()=>{"use strict";Ge();xs();we();Ni();Ca()});async function ln(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new hf(t,n):c}finally{clearTimeout(a)}}async function Ln(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 ln(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);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??"warm",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,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function xy(t,e=fetch){let n=await ln(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await ln(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.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 Gr(t,e=fetch){let n=await ln(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);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,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function Tc(t,e,n={},s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},18e4,s);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 os(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function Ay(t,e,n,s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Cy(t,e,n,s=fetch){let r=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Ry(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);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 Ty(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await ln(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function Ey(t,e,n=fetch){let s=await ln(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Ec(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="warm"?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 hf,Ra=V(()=>{"use strict";hf=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function mf(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Py(t,e){let n=t??"?",s=mf(e);return s?`${n}${mC}${s}`:n}function My(t){return t??"?"}function _y(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:gf(e,n)}function gf(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var mC,yf=V(()=>{"use strict";mC="\u2022"});function $y(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(!Mc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Mc.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function ko(t,e=Date.now()){return{session:pt(t.sessionId),upstream:wC(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:bC(t.status,t.busy,t.awaitingInput,yC(t.compactionState),t.forkSynthesisState),agent:My(t.agentId),model:mf(t.currentModel)??"-",age:vC(t.updatedAt,e),title:t.title??"-",cwd:dt(t.cwd),cost:_y(t.currentUsage)}}function yC(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function wC(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function bC(t,e,n,s,r){return t==="cold"?"COLD":n?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function Io(t,e={}){let n=e.columns??vo,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]=SC(So[r],t.map(i=>i[r]));return s}function vC(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 c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function SC(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function fr(t,e,n,s={}){let r=s.columns??vo,i=s.cwdMaxWidth??gC,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((S,k)=>k===r.length-1?t[S]:o(S)).join(Pc);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>wf.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Pc);return b.length>n?b.slice(0,n):b}let d=r.filter(b=>!wf.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),f=n-d-l*Pc.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:b,i:S}of a){if(S===c)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],A=Math.min(k,Math.max(0,p-1));u.set(S,A),p=Math.max(0,p-A)}u.set(c,Math.max(0,p));let h=r.length-1,m=(b,S,k)=>{if(b==="cwd")return Ta(t[b],S).padEnd(S);let A=kC(t[b],S);return k?A:A.padEnd(S)},w=r.map((b,S)=>wf.has(b)?m(b,u.get(S)??0,S===h):o(b)).join(Pc);return w.length>n?w.slice(0,n):w}function kC(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function Ta(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 Mc,vo,wf,So,Pc,gC,_c=V(()=>{"use strict";yf();we();es();Mc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],vo=["session","state","age","cwd","title","agent","cost"],wf=new Set(["cwd","title"]),So={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Pc=" ",gC=32});import{spawn as _C}from"child_process";import{Writable as $C}from"stream";function $c(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=FC(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??_C,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}
119
+ `)});let c=new $C({write(l,f,u){if(!a.writable){u();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){u(h);return}u()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
120
+ `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function FC(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 bf=V(()=>{"use strict"});import OC from"chalk";import{highlight as LC,supportsLanguage as Fc}from"cli-highlight";import Lc from"string-width";function hr(t,e={}){switch(t.kind){case"user-text":{let n=vf(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 vf(t.text," ","agent");case"agent-thought":return vf(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return iR(t,e.maxPlanItems??sR);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 Sf(t,e){return pr(t,e).styled}function pr(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.italicReset??"^:",o=e?.linkOpen??"^C^_",a=e?.linkReset??"^:",c="",d=0,l=!1,f=[],u=0;for(;u<t.length;){let p=t[u];if(p==="\\"&&u+1<t.length){let h=t[u+1];if(h==="*"||h==="_"||h==="`"||h==="["||h==="]"||h==="\\"){c+=h,d+=1,u+=2;continue}}if(p==="^"){c+="^^",d+=1,u+=1;continue}if(p==="*"&&t[u+1]==="*"){let h=t.indexOf("**",u+2);if(h!==-1&&h>u+2){let m=t.slice(u+2,h),y=pr(m,e),w=d;c+=`^+${y.styled}${r}`;for(let b of y.links)f.push({start:w+b.start,end:w+b.end,url:b.url});d+=y.cleanLength,y.ansi&&(l=!0),u=h+2;continue}}if(p==="*"&&t[u+1]!=="*"){let h=u>0?t[u-1]:"",m=t[u+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
121
121
  `&&!/[A-Za-z0-9]/.test(h)){let w=-1;for(let b=u+1;b<t.length;b++){let S=t[b];if(S===`
122
- `)break;if(S!=="*"||t[b+1]==="*")continue;let k=t[b-1],A=t[b+1]??"";if(!(k===" "||k===" "||k==="*")&&!/[A-Za-z0-9]/.test(A)){w=b;break}}if(w!==-1&&w>u+1){let b=t.slice(u+1,w),S=fr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)f.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),u=w+1;continue}}}if(p==="_"){let h=u>0?t[u-1]:"",m=t[u+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
122
+ `)break;if(S!=="*"||t[b+1]==="*")continue;let k=t[b-1],A=t[b+1]??"";if(!(k===" "||k===" "||k==="*")&&!/[A-Za-z0-9]/.test(A)){w=b;break}}if(w!==-1&&w>u+1){let b=t.slice(u+1,w),S=pr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)f.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),u=w+1;continue}}}if(p==="_"){let h=u>0?t[u-1]:"",m=t[u+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
123
123
  `&&m!=="_"&&!/[A-Za-z0-9_]/.test(h)){let w=-1;for(let b=u+1;b<t.length;b++){let S=t[b];if(S===`
124
- `)break;if(S!=="_")continue;let k=t[b-1],A=t[b+1]??"";if(!(k===" "||k===" "||k==="_")&&!/[A-Za-z0-9_]/.test(A)){w=b;break}}if(w!==-1&&w>u+1){let b=t.slice(u+1,w),S=fr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)f.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),u=w+1;continue}}}if(p==="`"){let h=t.indexOf("`",u+1);if(h!==-1&&h>u+1){let m=t.slice(u+1,h),y=m.replace(/\^/g,"^^");c+=`${n}${y}${s}`,d+=m.length,u=h+1;continue}}if(p==="["){let h=t.indexOf("]",u+1);if(h!==-1&&t[h+1]==="("&&h>u+1){let m=-1;{let y=1,w=h+2;for(;w<t.length;){let b=t[w];if(b==="\\"&&w+1<t.length){w+=2;continue}if(b==="(")y+=1;else if(b===")"&&(y-=1,y===0)){m=w;break}w+=1}}if(m!==-1&&m>h+2){let y=t.slice(u+1,h),w=t.slice(h+2,m),b=fr(y,e),S=d,k=w.startsWith("file://"),A=_C.test(w),E=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(w),P=!k&&!A&&!E;k||P?c+=`${o}${b.styled}${a}`:(c+=`\x1B]8;;${w}\x1B\\${o}${b.styled}${a}\x1B]8;;\x1B\\`,l=!0);for(let B of b.links)f.push({start:S+B.start,end:S+B.end,url:B.url});d+=b.cleanLength,(k||A||P)&&f.push({start:S,end:d,url:w}),u=m+1;continue}}}c+=p,d+=1,u+=1}return{styled:c,links:f,cleanLength:d,ansi:l}}function $C(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",italicReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",italicReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",italicReset:"^:^Y",codeReset:"^:^Y"}}}function Wy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",italicReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",italicReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",italicReset:"^:^+",codeReset:"^:^+"}}}function zy(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
125
- `),l=!1,f="",u=[],p=i!==" ",h=(w,b,S=" ",k,A,E)=>{let P={prefix:S,body:w,bodyStyle:b};r!==void 0&&(P.prefixStyle=r),k&&k.length>0&&(P.links=k),A&&(P.ansi=!0),E!==void 0&&E>0&&(P.hangingIndent=E),c.push(P)},m=()=>p?(p=!1,i):" ",y=()=>{if(u.length!==0){if(s){let w=Jy(f,u);for(let b of w){let S={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),b.ansi&&(S.ansi=!0),c.push(S)}}else for(let w of u)h(w.replace(/\^/g,"^^"),n);u=[],f=""}};for(let w=0;w<d.length;w++){let b=d[w],S=b.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,f=S[1]??"");continue}if(l){u.push(b);continue}let k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let D=k[1].length,N=k[2]??"",L=s?D===1?"heading-1":D===2?"heading-2":"heading-3":n,K=s?Wy(L):o;h(vf(N,K),L,m());continue}let A=d[w+1];if(b.includes("|")&&A!==void 0&&FC(A)&&Ea(b).length===Ea(A).length){let D=Ea(b),N=[],L=w+2;for(;L<d.length&&d[L].includes("|");)N.push(Ea(d[L])),L++;let K=UC(D,N,a);for(let X of K)r!==void 0&&(X.prefixStyle=r),c.push(X);w=L-1;continue}let E=b.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let D=E[1]??"",N=E[2]??"",L=fr(N,o),K=D.length+2,X=L.links.map(Z=>({start:Z.start+K,end:Z.end+K,url:Z.url}));h(`${D}\u2022 ${L.styled}`,n,m(),X,L.ansi,D.length+2);continue}let P=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(P){let D=P[1]??"",N=P[2]??"",L=P[3]??"",K=fr(L,o),X=D.length+N.length+2,Z=K.links.map(Q=>({start:Q.start+X,end:Q.end+X,url:Q.url}));h(`${D}${N}. ${K.styled}`,n,m(),Z,K.ansi,D.length+N.length+2);continue}let B=b.trim()==="",_=fr(b,o);h(_.styled,n,B?" ":m(),_.links,_.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function hr(t,e){return zy(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function xo(t){return zy(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Ea(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function FC(t){if(!t.includes("|"))return!1;let e=Ea(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Oc(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return Lc(e)}function BC(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:Lc(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==="*"&&t[i+1]!=="*"){let a=r.length>0?r[r.length-1]:i>0?t[i-1]:"",c=t[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let f=i+1;f<t.length;f++){if(t[f]!=="*"||t[f+1]==="*")continue;let p=t[f-1],h=t[f+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(h)){l=f;break}}if(l!==-1&&l>i+1){r+=t.slice(i,l+1),i=l+1;continue}}}if(o==="_"){let a=r.length>0?r[r.length-1]:i>0?t[i-1]:"",c=t[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let f=i+1;f<t.length;f++){if(t[f]!=="_")continue;let p=t[f-1],h=t[f+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(h)){l=f;break}}if(l!==-1&&l>i+1){r+=t.slice(i,l+1),i=l+1;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:Oc(r)}),n=i}return e}function NC(t,e){let n=[],s="",r=0;for(let i of t){let o=Lc(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 DC(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("`")||o.text.includes("*")||o.text.includes("_"))n.push(o.text);else{let c=NC(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=Lc(d)}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 HC(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,Ky)),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),c=a.reduce((l,f)=>l+f.slack,0);if(c===0)return r;for(let l of a){let f=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let d=e-i;for(;d>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,d--}return r}function UC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Oc(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let f=d[l]??"",u=Oc(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let d=Math.max(s*Ky,n-OC-(s-1)*LC);i=HC(r,d)}let o=(d,l,f)=>{let u=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",w=i[m],b=DC(BC(y),w);u.push(b),b.length>p&&(p=b.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let w=0;w<s;w++){let b=u[w][m]??"",S=i[w],k=Oc(b),A=vf(b,f);y.push(A+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(t,"heading-3",Wy("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function Jy(t,e){if(t.length===0||!Fc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=MC(e.join(`
126
- `),{language:t,theme:jC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
127
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function WC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Fc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Fc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=qC[s];return r&&Fc(r)?r:""}function bf(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
128
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function zC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function as(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 Yy(t){if(t.length<=4096&&t.split(`
124
+ `)break;if(S!=="_")continue;let k=t[b-1],A=t[b+1]??"";if(!(k===" "||k===" "||k==="_")&&!/[A-Za-z0-9_]/.test(A)){w=b;break}}if(w!==-1&&w>u+1){let b=t.slice(u+1,w),S=pr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)f.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),u=w+1;continue}}}if(p==="`"){let h=t.indexOf("`",u+1);if(h!==-1&&h>u+1){let m=t.slice(u+1,h),y=m.replace(/\^/g,"^^");c+=`${n}${y}${s}`,d+=m.length,u=h+1;continue}}if(p==="["){let h=t.indexOf("]",u+1);if(h!==-1&&t[h+1]==="("&&h>u+1){let m=-1;{let y=1,w=h+2;for(;w<t.length;){let b=t[w];if(b==="\\"&&w+1<t.length){w+=2;continue}if(b==="(")y+=1;else if(b===")"&&(y-=1,y===0)){m=w;break}w+=1}}if(m!==-1&&m>h+2){let y=t.slice(u+1,h),w=t.slice(h+2,m),b=pr(y,e),S=d,k=w.startsWith("file://"),A=BC.test(w),E=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(w),P=!k&&!A&&!E;k||P?c+=`${o}${b.styled}${a}`:(c+=`\x1B]8;;${w}\x1B\\${o}${b.styled}${a}\x1B]8;;\x1B\\`,l=!0);for(let B of b.links)f.push({start:S+B.start,end:S+B.end,url:B.url});d+=b.cleanLength,(k||A||P)&&f.push({start:S,end:d,url:w}),u=m+1;continue}}}c+=p,d+=1,u+=1}return{styled:c,links:f,cleanLength:d,ansi:l}}function NC(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",italicReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",italicReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",italicReset:"^:^Y",codeReset:"^:^Y"}}}function zy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",italicReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",italicReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",italicReset:"^:^+",codeReset:"^:^+"}}}function Ky(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
125
+ `),l=!1,f="",u=[],p=i!==" ",h=(w,b,S=" ",k,A,E)=>{let P={prefix:S,body:w,bodyStyle:b};r!==void 0&&(P.prefixStyle=r),k&&k.length>0&&(P.links=k),A&&(P.ansi=!0),E!==void 0&&E>0&&(P.hangingIndent=E),c.push(P)},m=()=>p?(p=!1,i):" ",y=()=>{if(u.length!==0){if(s){let w=Yy(f,u);for(let b of w){let S={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),b.ansi&&(S.ansi=!0),c.push(S)}}else for(let w of u)h(w.replace(/\^/g,"^^"),n);u=[],f=""}};for(let w=0;w<d.length;w++){let b=d[w],S=b.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,f=S[1]??"");continue}if(l){u.push(b);continue}let k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let D=k[1].length,N=k[2]??"",L=s?D===1?"heading-1":D===2?"heading-2":"heading-3":n,K=s?zy(L):o;h(Sf(N,K),L,m());continue}let A=d[w+1];if(b.includes("|")&&A!==void 0&&DC(A)&&Ea(b).length===Ea(A).length){let D=Ea(b),N=[],L=w+2;for(;L<d.length&&d[L].includes("|");)N.push(Ea(d[L])),L++;let K=KC(D,N,a);for(let X of K)r!==void 0&&(X.prefixStyle=r),c.push(X);w=L-1;continue}let E=b.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let D=E[1]??"",N=E[2]??"",L=pr(N,o),K=D.length+2,X=L.links.map(Z=>({start:Z.start+K,end:Z.end+K,url:Z.url}));h(`${D}\u2022 ${L.styled}`,n,m(),X,L.ansi,D.length+2);continue}let P=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(P){let D=P[1]??"",N=P[2]??"",L=P[3]??"",K=pr(L,o),X=D.length+N.length+2,Z=K.links.map(Q=>({start:Q.start+X,end:Q.end+X,url:Q.url}));h(`${D}${N}. ${K.styled}`,n,m(),Z,K.ansi,D.length+N.length+2);continue}let B=b.trim()==="",_=pr(b,o);h(_.styled,n,B?" ":m(),_.links,_.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function mr(t,e){return Ky(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function xo(t){return Ky(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Ea(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function DC(t){if(!t.includes("|"))return!1;let e=Ea(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Oc(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return Lc(e)}function jC(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:Lc(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==="*"&&t[i+1]!=="*"){let a=r.length>0?r[r.length-1]:i>0?t[i-1]:"",c=t[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let f=i+1;f<t.length;f++){if(t[f]!=="*"||t[f+1]==="*")continue;let p=t[f-1],h=t[f+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(h)){l=f;break}}if(l!==-1&&l>i+1){r+=t.slice(i,l+1),i=l+1;continue}}}if(o==="_"){let a=r.length>0?r[r.length-1]:i>0?t[i-1]:"",c=t[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let f=i+1;f<t.length;f++){if(t[f]!=="_")continue;let p=t[f-1],h=t[f+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(h)){l=f;break}}if(l!==-1&&l>i+1){r+=t.slice(i,l+1),i=l+1;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:Oc(r)}),n=i}return e}function qC(t,e){let n=[],s="",r=0;for(let i of t){let o=Lc(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 WC(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("`")||o.text.includes("*")||o.text.includes("_"))n.push(o.text);else{let c=qC(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=Lc(d)}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 zC(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,Jy)),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),c=a.reduce((l,f)=>l+f.slack,0);if(c===0)return r;for(let l of a){let f=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let d=e-i;for(;d>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,d--}return r}function KC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Oc(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let f=d[l]??"",u=Oc(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let d=Math.max(s*Jy,n-HC-(s-1)*UC);i=zC(r,d)}let o=(d,l,f)=>{let u=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",w=i[m],b=WC(jC(y),w);u.push(b),b.length>p&&(p=b.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let w=0;w<s;w++){let b=u[w][m]??"",S=i[w],k=Oc(b),A=Sf(b,f);y.push(A+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(t,"heading-3",zy("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function Yy(t,e){if(t.length===0||!Fc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=LC(e.join(`
126
+ `),{language:t,theme:JC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
127
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function VC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Fc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Fc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=YC[s];return r&&Fc(r)?r:""}function vf(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
128
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function QC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function as(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 Vy(t){if(t.length<=4096&&t.split(`
129
129
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
130
130
  `);return i.length>40&&(s=i.slice(0,40).join(`
131
- `),r=!0),{text:s,truncated:r}}function Pa(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,f=o.toLowerCase(),u=l.toLowerCase();(u.startsWith(`${f} `)||u.startsWith(`${f} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=t.locations?.[0]?.path??t.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${as(l-t.startedAt)}`}let c={prefix:` ${VC(t.status)} `,prefixStyle:QC(t.status),body:o,bodyStyle:tR(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Pe(t.errorText),bodyStyle:"tool-status-fail"}),d}function Vy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
131
+ `),r=!0),{text:s,truncated:r}}function Pa(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,f=o.toLowerCase(),u=l.toLowerCase();(u.startsWith(`${f} `)||u.startsWith(`${f} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=t.locations?.[0]?.path??t.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${as(l-t.startedAt)}`}let c={prefix:` ${eR(t.status)} `,prefixStyle:tR(t.status),body:o,bodyStyle:oR(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Pe(t.errorText),bodyStyle:"tool-status-fail"}),d}function Qy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
132
132
  `))e.push({prefix:" ",body:Pe(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Pe(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
133
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=WC(r);if(i.length>0){let o=Jy(i,s.map(a=>Pe(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Pe(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Gy(t){Qy=t>=0?t:0}function Sf(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${zC(d)})`}else{let d=JC(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Pe(dt(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=kf(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...hr(c)),s.length>0&&s.unshift({body:""}),s}function Xy(t){let e=wt(t.oldText).split(`
133
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=VC(r);if(i.length>0){let o=Yy(i,s.map(a=>Pe(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Pe(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Xy(t){Gy=t>=0?t:0}function kf(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${QC(d)})`}else{let d=XC(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Pe(dt(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=If(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...mr(c)),s.length>0&&s.unshift({body:""}),s}function Zy(t){let e=wt(t.oldText).split(`
134
134
  `),n=wt(t.newText).split(`
135
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function JC(t){let{oldLines:e,newLines:n}=Xy(t),s=0,r=0;for(let i of Zy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function qy(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function kf(t,e={}){let n=e.maxLines??KC,s=e.contextLines??Qy,{oldLines:r,newLines:i}=Xy(t),o=Zy(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),h=Math.min(o.length-1,u+s);for(let m=p;m<=h;m++)l[m]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push(qy(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 d of o)a.push(qy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let f=a.length-d;c.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}c.push(a[d])}return c.join(`
136
- `)}function Zy(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(...YC(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 YC(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+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 If(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function VC(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 QC(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 ew(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...hr(t.plan));let n=t.status;if(n!==void 0){let s=GC(n);s!==null&&e.push(s)}return e}function GC(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 ZC(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function eR(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:c,end:d}=ZC(t.entries,e),l=d-c<a,f="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;f=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",w=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=vf(b,$C(w));u.push({prefix:" ",body:`${y} ${S}`,bodyStyle:w})}return u}function tR(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 _C,Ky,OC,LC,lt,jC,qC,KC,Qy,XC,Ao=V(()=>{"use strict";we();or();_C=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;Ky=6,OC=2,LC=3;lt=new PC.Instance({level:3}),jC={keyword:lt.blueBright,built_in:lt.cyan,type:lt.cyanBright,literal:lt.blue,number:lt.greenBright,string:lt.yellow,regexp:lt.red,comment:lt.gray,function:lt.yellow,title:lt.yellow,class:lt.yellowBright,attr:lt.cyan,attribute:lt.cyan,variable:lt.white,params:lt.white,meta:lt.magenta,symbol:lt.magenta,addition:lt.greenBright,deletion:lt.redBright,section:lt.cyan,tag:lt.cyan,name:lt.cyanBright};qC={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};KC=40,Qy=Number.POSITIVE_INFINITY;XC=5});import{highlight as nR,supportsLanguage as sR}from"cli-highlight";async function nw(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
137
- `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Fe(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=On(d)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
135
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function XC(t){let{oldLines:e,newLines:n}=Zy(t),s=0,r=0;for(let i of ew(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Wy(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function If(t,e={}){let n=e.maxLines??GC,s=e.contextLines??Gy,{oldLines:r,newLines:i}=Zy(t),o=ew(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),h=Math.min(o.length-1,u+s);for(let m=p;m<=h;m++)l[m]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push(Wy(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 d of o)a.push(Wy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let f=a.length-d;c.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}c.push(a[d])}return c.join(`
136
+ `)}function ew(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(...ZC(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 ZC(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+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 xf(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function eR(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 tR(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 tw(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...mr(t.plan));let n=t.status;if(n!==void 0){let s=nR(n);s!==null&&e.push(s)}return e}function nR(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 rR(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function iR(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:c,end:d}=rR(t.entries,e),l=d-c<a,f="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;f=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",w=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Sf(b,NC(w));u.push({prefix:" ",body:`${y} ${S}`,bodyStyle:w})}return u}function oR(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 BC,Jy,HC,UC,lt,JC,YC,GC,Gy,sR,Ao=V(()=>{"use strict";we();ar();BC=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;Jy=6,HC=2,UC=3;lt=new OC.Instance({level:3}),JC={keyword:lt.blueBright,built_in:lt.cyan,type:lt.cyanBright,literal:lt.blue,number:lt.greenBright,string:lt.yellow,regexp:lt.red,comment:lt.gray,function:lt.yellow,title:lt.yellow,class:lt.yellowBright,attr:lt.cyan,attribute:lt.cyan,variable:lt.white,params:lt.white,meta:lt.magenta,symbol:lt.magenta,addition:lt.greenBright,deletion:lt.redBright,section:lt.cyan,tag:lt.cyan,name:lt.cyanBright};YC={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};GC=40,Gy=Number.POSITIVE_INFINITY;sR=5});import{highlight as aR,supportsLanguage as dR}from"cli-highlight";async function sw(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
137
+ `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Oe(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Oe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=On(d)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
138
138
  `),process.exit(1)}let f=io(l.history);r=e.fold===!0?f.map(u=>({...u,hunks:oo(u.hunks)})):f}else process.stderr.write(`Daemon returned HTTP ${s.status}
139
139
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
140
- `);return}let i=$c({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(xf(r,a)),await i.flush()}function xf(t,e){if(t.length===0)return`No file edits found in this session.
141
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=oR(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
142
- `:n.join("")}function rR(t){let e=[];for(let n of t.hunks){let s=kf(n,{maxLines:1/0});iR(s)&&e.push({body:s,oldCount:tw(n.oldText),newCount:tw(n.newText)})}return e}function iR(t){if(t.length===0)return!1;for(let e of t.split(`
143
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function oR(t,e){let n=rR(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 c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
140
+ `);return}let i=$c({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Af(r,a)),await i.flush()}function Af(t,e){if(t.length===0)return`No file edits found in this session.
141
+ `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=uR(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
142
+ `:n.join("")}function cR(t){let e=[];for(let n of t.hunks){let s=If(n,{maxLines:1/0});lR(s)&&e.push({body:s,oldCount:nw(n.oldText),newCount:nw(n.newText)})}return e}function lR(t){if(t.length===0)return!1;for(let e of t.split(`
143
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function uR(t,e){let n=cR(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 c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
144
144
  `)+`
145
145
 
146
- `;return!e||!sR("diff")?i:nR(i,{language:"diff"})}function tw(t){if(t.length===0)return 0;let e=t.split(`
147
- `);return e[e.length-1]===""&&e.pop(),e.length}var Af=V(()=>{"use strict";lr();Kr();dc();Ao();wf()});async function sw(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
148
- `),process.exit(2));let n=await Fe(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=On(i)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
149
- `),process.exit(1)}let a=Tf(o,s??"cold"),c=e.diff===!0,d=null;if(c){let u=io(o.history);d=e.fold===!0?u.map(p=>({...p,hunks:oo(p.hunks)})):u}if(e.json){let u={...a};d!==null&&(u.diff=d),process.stdout.write(JSON.stringify(u,null,2)+`
146
+ `;return!e||!dR("diff")?i:aR(i,{language:"diff"})}function nw(t){if(t.length===0)return 0;let e=t.split(`
147
+ `);return e[e.length-1]===""&&e.pop(),e.length}var Cf=V(()=>{"use strict";ur();Kr();dc();Ao();bf()});async function rw(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
148
+ `),process.exit(2));let n=await Oe(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Oe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=On(i)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
149
+ `),process.exit(1)}let a=Ef(o,s??"cold"),c=e.diff===!0,d=null;if(c){let u=io(o.history);d=e.fold===!0?u.map(p=>({...p,hunks:oo(p.hunks)})):u}if(e.json){let u={...a};d!==null&&(u.diff=d),process.stdout.write(JSON.stringify(u,null,2)+`
150
150
  `);return}let l=process.stdout.isTTY===!0,f=!e.noColor&&l;if(c){let u=$c({disabled:e.noPager===!0});u.stream.write(Bc(a,e.verbose===!0)),u.stream.write(`
151
- `),u.stream.write(xf(d??[],f)),await u.flush();return}process.stdout.write(Bc(a,e.verbose===!0))}function Tf(t,e){let n=t.session,s=t.history,r=Hm(s),i=$u(s),o=Fu(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c: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 Bc(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:")}${dR(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=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}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 c=e?t.tools:t.tools.slice(0,Cf),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>Cf&&n.push(` ... ${t.tools.length-Cf} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>aR.has(l.name)),d=c.reduce((l,f)=>l+f.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Rf),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Rf&&n.push(` ... ${o.length-Rf} more (use --verbose to see all)`)}return n.join(`
151
+ `),u.stream.write(Af(d??[],f)),await u.flush();return}process.stdout.write(Bc(a,e.verbose===!0))}function Ef(t,e){let n=t.session,s=t.history,r=Hm(s),i=Fu(s),o=Ou(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c: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 Bc(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:")}${pR(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=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}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 c=e?t.tools:t.tools.slice(0,Rf),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>Rf&&n.push(` ... ${t.tools.length-Rf} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>fR.has(l.name)),d=c.reduce((l,f)=>l+f.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Tf),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Tf&&n.push(` ... ${o.length-Tf} more (use --verbose to see all)`)}return n.join(`
152
152
  `)+`
153
- `}function dR(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 Cf,Rf,aR,Ef=V(()=>{"use strict";lr();Kr();Ou();dc();wf();Af();Cf=10,Rf=15,aR=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Iw={};_l(Iw,{assertKnownAgent:()=>Uc,canonicalAgentId:()=>Ma,resolveAgentIdOrExit:()=>jc,runAgentsAdd:()=>Bf,runAgentsInstall:()=>_f,runAgentsList:()=>Mf,runAgentsLogs:()=>Ff,runAgentsPin:()=>Lf,runAgentsRefresh:()=>qc,runAgentsRemove:()=>Nf,runAgentsSet:()=>Of,runAgentsSync:()=>$f,runAgentsUninstall:()=>Df,runRegistryPin:()=>Wc});import*as Hc from"fs/promises";import*as Sw from"path";async function Mf(){let e=(await Fe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
153
+ `}function pR(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 Rf,Tf,fR,Pf=V(()=>{"use strict";ur();Kr();Lu();dc();bf();Cf();Rf=10,Tf=15,fR=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var xw={};$l(xw,{assertKnownAgent:()=>Uc,canonicalAgentId:()=>Ma,resolveAgentIdOrExit:()=>jc,runAgentsAdd:()=>Nf,runAgentsInstall:()=>$f,runAgentsList:()=>_f,runAgentsLogs:()=>Of,runAgentsPin:()=>Bf,runAgentsRefresh:()=>qc,runAgentsRemove:()=>Df,runAgentsSet:()=>Lf,runAgentsSync:()=>Ff,runAgentsUninstall:()=>Hf,runRegistryPin:()=>Wc});import*as Hc from"fs/promises";import*as kw from"path";async function _f(){let e=(await Oe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
154
154
  `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:Es(s.id,n.map(a=>a.id)),name:Es(s.name,n.map(a=>a.name)),version:Es(s.version,n.map(a=>a.version)),source:Es(s.source,n.map(a=>a.source)),distributions:Es(s.distributions,n.map(a=>a.distributions)),installed:Es(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
155
155
  `);for(let a of n)process.stdout.write(i(a)+`
156
156
  `);let o=e.fetchedAt!==void 0?` (synced ${wo(e.fetchedAt)})`:"";process.stdout.write(`
157
157
  Registry version: ${e.version}${o}
158
- `)}function Ma(t,e){if(e.includes(t))return t;let n=t.toLowerCase();if(n.length===0)return;let s=e.filter(r=>r.toLowerCase().startsWith(n));if(s.length===1)return s[0]}async function Uc(t){if((await Ae()).agents[t]!==void 0)return;let n;try{let s=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;n=s.body.agents.map(i=>i.id)}catch{return}Ma(t,n)===void 0&&(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
159
- `),process.exit(2))}async function jc(t,e){let n;try{let i=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!i.ok)return t;n=i.body.agents.map(a=>a.id)}catch{return t}let s=Ma(t,n);if(s!==void 0)return s;let r=t.toLowerCase();if(r.length>0){let i=n.filter(o=>o.toLowerCase().startsWith(r));i.length>1&&(process.stderr.write(`${e}: '${t}' is ambiguous (matches ${i.join(", ")}).
158
+ `)}function Ma(t,e){if(e.includes(t))return t;let n=t.toLowerCase();if(n.length===0)return;let s=e.filter(r=>r.toLowerCase().startsWith(n));if(s.length===1)return s[0]}async function Uc(t){if((await Ae()).agents[t]!==void 0)return;let n;try{let s=await Oe("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;n=s.body.agents.map(i=>i.id)}catch{return}Ma(t,n)===void 0&&(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
159
+ `),process.exit(2))}async function jc(t,e){let n;try{let i=await Oe("/v1/agents",{rethrowNetworkError:!0});if(!i.ok)return t;n=i.body.agents.map(a=>a.id)}catch{return t}let s=Ma(t,n);if(s!==void 0)return s;let r=t.toLowerCase();if(r.length>0){let i=n.filter(o=>o.toLowerCase().startsWith(r));i.length>1&&(process.stderr.write(`${e}: '${t}' is ambiguous (matches ${i.join(", ")}).
160
160
  `),process.exit(2))}process.stderr.write(`${e}: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
161
- `),process.exit(2)}async function _f(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
161
+ `),process.exit(2)}async function $f(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
162
162
  `),process.exit(2);return}let e=await jc(t,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
163
- `);let s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!s.installed){process.stdout.write(`${s.agentId} (${s.version}, ${s.distribution}): ${s.message??"nothing to install"}
163
+ `);let s=(await Oe(`/v1/agents/${encodeURIComponent(e)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!s.installed){process.stdout.write(`${s.agentId} (${s.version}, ${s.distribution}): ${s.message??"nothing to install"}
164
164
  `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
165
165
  `),s.command&&process.stdout.write(` \u2192 ${s.command}
166
- `)}async function $f(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
167
- `),process.exit(2);return}let e=await jc(t,"hydra agent sync"),s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
166
+ `)}async function Ff(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
167
+ `),process.exit(2);return}let e=await jc(t,"hydra agent sync"),s=(await Oe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
168
168
  `);return}let r=s.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:Es(i.id,r.map(c=>c.id)),upstream:Es(i.upstream,r.map(c=>c.upstream)),cwd:Es(i.cwd,r.map(c=>c.cwd))},a=c=>[c.id.padEnd(o.id),c.upstream.padEnd(o.upstream),c.cwd.padEnd(o.cwd),c.title].join(" ");process.stdout.write(a(i)+`
169
169
  `);for(let c of r)process.stdout.write(a(c)+`
170
170
  `);process.stdout.write(`
171
171
  Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
172
- `)}async function Ff(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
173
- `),process.exit(2);return}let n=O.agentLogFile(t);await mo(n,e,"No log file (agent never ran?)")}async function Of(t,e){let n=await Ae();if(!t){let c=await vw()??Pf(await bo());process.stdout.write(`${bw(c)}
174
- `);return}let s;try{let a=await Fe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){let a=t.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)t=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${t}' is ambiguous (matches ${c.join(", ")}).
172
+ `)}async function Of(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
173
+ `),process.exit(2);return}let n=O.agentLogFile(t);await mo(n,e,"No log file (agent never ran?)")}async function Lf(t,e){let n=await Ae();if(!t){let c=await Sw()??Mf(await bo());process.stdout.write(`${vw(c)}
174
+ `);return}let s;try{let a=await Oe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){let a=t.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)t=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${t}' is ambiguous (matches ${c.join(", ")}).
175
175
  `),process.exit(1);return}else{process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
176
- `),process.exit(1);return}}e!==void 0?await Gp(t,e):await Li(t);let i=Pf(await bo());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
177
- `),process.stdout.write(`${bw(i)}
178
- `);let o=await vw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${kw(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
179
- `))}function bw(t){return`Default agent is ${kw(t)}`}function kw(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function Pf(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 vw(){try{let t=await Fe("/v1/config",{rethrowNetworkError:!0});return t.ok?Pf(t.body):void 0}catch{return}}async function qc(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
180
- `)}async function Lf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
176
+ `),process.exit(1);return}}e!==void 0?await Gp(t,e):await Li(t);let i=Mf(await bo());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
177
+ `),process.stdout.write(`${vw(i)}
178
+ `);let o=await Sw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Iw(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
179
+ `))}function vw(t){return`Default agent is ${Iw(t)}`}function Iw(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function Mf(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 Sw(){try{let t=await Oe("/v1/config",{rethrowNetworkError:!0});return t.ok?Mf(t.body):void 0}catch{return}}async function qc(){let e=(await Oe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
180
+ `)}async function Bf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
181
181
  `),process.exit(2);return}await Xp(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
182
182
  `):process.stdout.write(`Pinned ${t} to ${e}.
183
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Bf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
183
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Nf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
184
184
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
185
- `),process.exit(2);return}let n=Rc(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await Bl(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
186
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Nf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
187
- `),process.exit(2);return}await Bl(t,void 0),process.stdout.write(`Removed local agent ${t}.
188
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Df(t){if(!t){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
185
+ `),process.exit(2);return}let n=Rc(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await Nl(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
186
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Df(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
187
+ `),process.exit(2);return}await Nl(t,void 0),process.stdout.write(`Removed local agent ${t}.
188
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Hf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
189
189
  `),process.exit(2);return}let e=await jc(t,"hydra agent uninstall"),n=wn();if(n===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
190
- `),process.exit(1);return}let s=Sw.join(O.agentsDir(),n,e),r=!1;try{await Hc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${n}.
190
+ `),process.exit(1);return}let s=kw.join(O.agentsDir(),n,e),r=!1;try{await Hc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${n}.
191
191
  `);return}await Hc.rm(s,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${n}). Next session using it will re-install.
192
192
  `)}async function Wc(t){await Zp(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.
193
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Es(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var zc=V(()=>{"use strict";Qe();we();Ui();Aa();lr()});var Kc,Ps,Ro,_a,xw,$a,Hf,Jc,ei,Aw,ti,Cw,ni,Rw,si,To,Eo,Tw,Po,Ew,Pw,Mw,Uf,_w,Yc,Vc,Fa,$w,Fw,Oa=V(()=>{"use strict";Kc="\x1B[?2004h",Ps="\x1B[?2004l",Ro="\x1B[200~",_a="\x1B[201~",xw="\x1B[?1049l",$a="\x1B[?7h",Hf="\x1B[?7l",Jc="\x1B[?25h",ei="\x1B[?1l",Aw="\x1B[>1u",ti="\x1B[<u",Cw="\x1B[>4;2m",ni="\x1B[>4;0m",Rw="\x1B[>5;1m",si="\x1B[>5;0m",To="\x1B[?1000l",Eo="\x1B[?1002l",Tw="\x1B[?1003l",Po="\x1B[?1006l",Ew="\x1B[?1015l",Pw="\x1B[?w",Mw="\x1B[=24;1w",Uf="\x1B[=0;0w",_w="\x1B]22;pointer\x07",Yc="\x1B]22;default\x07",Vc="\x1B[?1004h",Fa="\x1B[?1004l",$w="\x1B[?2026h",Fw="\x1B[?2026l"});function Bn(){process.stdout.write(ti),process.stdout.write(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(To),process.stdout.write(Eo),process.stdout.write(Po),process.stdout.write(ei),process.stdout.write("\x1B>")}function Jt(t){return t.width??80}function Ms(t){return t.height??24}function Nn(t,e){let n=Jt(t),s=Ms(t),r=e.contentWidth??lR,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||t.moveTo(1,1).eraseDisplayBelow();let u=Ow.repeat(a-2),p=mR(u,e.title);t.moveTo(l,f),t.dim.noFormat(uR),gR(t,p),t.dim.noFormat(fR);for(let h=1;h<=c;h++)t.moveTo(l,f+h),t.dim.noFormat(Lw),e.overlay&&t.noFormat(" ".repeat(o)),t.moveTo(l+a-1,f+h),t.dim.noFormat(Lw);return t.moveTo(l,f+d-1),t.dim.noFormat(pR+Ow.repeat(a-2)+hR),{x:l,y:f,w:a,h:d,contentX:l+1,contentY:f+1,contentW:o,contentH:c}}function mR(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 gR(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))}function Xe(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function La(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function ds(t){let{term:e,render:n,onKey:s,onResize:r,onMouse:i}=t,o=t.hideCursor!==!1;return n(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??n)()},l=(h,m,y)=>{c||s(h,m,y,p)},f=(h,m)=>{c||!i||i(h,m,p)},u=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",f),e.grabInput(!1),oe({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),t.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{u(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",f)):e.grabInput({}),oe({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var lR,Ow,Lw,uR,fR,pR,hR,ri=V(()=>{"use strict";Hr();Oa();lR=64,Ow="\u2500",Lw="\u2502",uR="\u250C",fR="\u2510",pR="\u2514",hR="\u2518"});function Bw(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function bR(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??yR,footer:wR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${Bw(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function vR(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function SR(t){return typeof t!="object"||t===null?!1:t.code===j.AuthRequired}function Nw(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[Ft];if(!(typeof s!="object"||s===null))return s}function kR(t){let e=Nw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function IR(t){let e=Nw(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function Dw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!SR(e))throw e;let n=kR(e)??t.fallbackAgentId??"",s=IR(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function xR(t,e,n){t.grabInput(!1),oe({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Bn(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
193
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Es(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var zc=V(()=>{"use strict";Ge();we();Ui();Aa();ur()});var Kc,Ps,Ro,_a,Aw,$a,Uf,Jc,ei,Cw,ti,Rw,ni,Tw,si,To,Eo,Ew,Po,Pw,Mw,_w,jf,$w,Yc,Vc,Fa,Fw,Ow,Oa=V(()=>{"use strict";Kc="\x1B[?2004h",Ps="\x1B[?2004l",Ro="\x1B[200~",_a="\x1B[201~",Aw="\x1B[?1049l",$a="\x1B[?7h",Uf="\x1B[?7l",Jc="\x1B[?25h",ei="\x1B[?1l",Cw="\x1B[>1u",ti="\x1B[<u",Rw="\x1B[>4;2m",ni="\x1B[>4;0m",Tw="\x1B[>5;1m",si="\x1B[>5;0m",To="\x1B[?1000l",Eo="\x1B[?1002l",Ew="\x1B[?1003l",Po="\x1B[?1006l",Pw="\x1B[?1015l",Mw="\x1B[?w",_w="\x1B[=24;1w",jf="\x1B[=0;0w",$w="\x1B]22;pointer\x07",Yc="\x1B]22;default\x07",Vc="\x1B[?1004h",Fa="\x1B[?1004l",Fw="\x1B[?2026h",Ow="\x1B[?2026l"});function Bn(){process.stdout.write(ti),process.stdout.write(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(To),process.stdout.write(Eo),process.stdout.write(Po),process.stdout.write(ei),process.stdout.write("\x1B>")}function Jt(t){return t.width??80}function Ms(t){return t.height??24}function Nn(t,e){let n=Jt(t),s=Ms(t),r=e.contentWidth??mR,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||t.moveTo(1,1).eraseDisplayBelow();let u=Lw.repeat(a-2),p=vR(u,e.title);t.moveTo(l,f),t.dim.noFormat(gR),SR(t,p),t.dim.noFormat(yR);for(let h=1;h<=c;h++)t.moveTo(l,f+h),t.dim.noFormat(Bw),e.overlay&&t.noFormat(" ".repeat(o)),t.moveTo(l+a-1,f+h),t.dim.noFormat(Bw);return t.moveTo(l,f+d-1),t.dim.noFormat(wR+Lw.repeat(a-2)+bR),{x:l,y:f,w:a,h:d,contentX:l+1,contentY:f+1,contentW:o,contentH:c}}function vR(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 SR(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))}function Xe(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function La(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function ds(t){let{term:e,render:n,onKey:s,onResize:r,onMouse:i}=t,o=t.hideCursor!==!1;return n(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??n)()},l=(h,m,y)=>{c||s(h,m,y,p)},f=(h,m)=>{c||!i||i(h,m,p)},u=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",f),e.grabInput(!1),oe({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),t.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{u(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",f)):e.grabInput({}),oe({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var mR,Lw,Bw,gR,yR,wR,bR,ri=V(()=>{"use strict";Hr();Oa();mR=64,Lw="\u2500",Bw="\u2502",gR="\u250C",yR="\u2510",wR="\u2514",bR="\u2518"});function Nw(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function xR(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??kR,footer:IR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${Nw(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function AR(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function CR(t){return typeof t!="object"||t===null?!1:t.code===j.AuthRequired}function Dw(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[Ft];if(!(typeof s!="object"||s===null))return s}function RR(t){let e=Dw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function TR(t){let e=Dw(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function Hw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!CR(e))throw e;let n=RR(e)??t.fallbackAgentId??"",s=TR(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function ER(t,e,n){t.grabInput(!1),oe({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Bn(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
194
194
  `);let r=n?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{t.grabInput({}),oe({src:"grab",site:"runTerminalAuthSpawn.reGrab",on:!0})}catch{}};try{let a=r(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",c=>{o(),i({exitCode:c})}),a.on("error",c=>{o(),process.stdout.write(`
195
195
  failed to spawn ${e.command}: ${c.message}
196
196
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
197
197
  failed to spawn ${e.command}: ${a.message}
198
- `),i({exitCode:-1})}})}function AR(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function jf(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(AR(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Hw(t,e,n,s,r){Bn();let i=bR(e,n,s),o=!1,a,c,d=()=>{let f=4;i.command&&f++,i.url&&f++,i.methodLines&&(f+=1+i.methodLines.length),a&&f++,c&&f++;let u=Nn(t,{contentHeight:f,contentWidth:80,title:"Authentication required"}),p=u.contentW,h=0;if(a&&(t.moveTo(u.contentX,u.contentY+h),t.brightYellow.noFormat(Xe(` ${a}`,p)),h++),c&&(t.moveTo(u.contentX,u.contentY+h),t.brightRed.noFormat(Xe(` ${c}`,p)),h++),t.moveTo(u.contentX,u.contentY+h),t.brightWhite.bold.noFormat(Xe(` ${i.title}`,p)),h+=2,t.moveTo(u.contentX,u.contentY+h),t.noFormat(Xe(` ${i.description}`,p)),h++,i.command&&(t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(Xe(i.command,p-7)),h++),i.url&&(t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(Xe(i.url,p-7)),h++),i.methodLines){t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" "),t.noFormat(Xe(m.label,p-3)),h++}return h++,t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(` ${i.footer}`),u},l=i.methodLines?.length??0;return ds({term:t,render:()=>{d()},onKey:(f,u,p,h)=>{if(o)return;let m=vR(f,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${Bw(y)}\u2026`,d();let w=r.runTerminalAuth??(b=>xR(t,b));(async()=>{let b=await jf(y,{authenticate:r.authenticate,runTerminalAuth:w});if(b.kind==="terminal-completed"){h("terminal-completed");return}if(b.kind==="retry"){h("retry");return}if(b.kind==="error"){c=b.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var yR,wR,qf=V(()=>{"use strict";Hr();Id();Ad();ri();yR="This agent requires authentication before use.",wR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as zw}from"timers/promises";function FR(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var PR,MR,_R,$R,_o,Wf=V(()=>{"use strict";Ca();uo();PR=200,MR=5e3,_R=2,$R=60,_o=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;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.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}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(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),zw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=PR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Qr(s,this.opts.subprotocols);this.bindStream(rs(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.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>=$R)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await zw(n),this.destroyed)return;n=Math.min(n*_R,MR)}}bindStream(e){this.current=e,e.onMessage(n=>{if(FR(n)&&n.id!==null){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.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(n){this.scheduleReconnect(n);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}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}
199
- `)}}});function Kw(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function ii(t){return{outcome:{outcome:"selected",optionId:Kw(t,["allow_once","allow_always"])}}}function Jw(t){return{outcome:{outcome:"selected",optionId:Kw(t,["reject_once","reject_always"])}}}function Xc(t){return t&&typeof t=="object"?t:void 0}function Ba(t){return typeof t=="string"&&t.length>0?t:void 0}function Yw(t){let e=Xc(t),n=Xc(e?.toolCall),s={paths:[]};if(!n)return s;let r=Ba(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Ba(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(Xc(d)?.path);let c=Xc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Ba(c.command);d&&(s.command=d);let l=Ba(c.url);l&&(s.url=l);let f=Ba(c.description);f&&(s.description=f)}return s}function Vw(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 Zc=V(()=>{"use strict"});function $0(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function hb(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 F0(t,e){let n=hb(t),s=hb(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 Na(){if(gr!==void 0)return gr;if($0())return gr=null,gr;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:mb,version:be}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&F0(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}gr={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{}gr=null}}catch{gr=null}return gr}function Da(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${mb}`}var mb,gr,Jf=V(()=>{"use strict";an();mb="@hydra-acp/cli"});import*as Ha from"fs/promises";import*as Yf from"path";async function Ua(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Yf.resolve(tt(e)),s;try{s=await Ha.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 gb(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 Ha.stat(r)).isDirectory())return r}catch{}return null}async function yb(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=Yf.resolve(tt(r)),o;try{o=(await Ha.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var Vf=V(()=>{"use strict";Qe()});var wb,bb,vb,Sb=V(()=>{"use strict";wb="hydra-acp/question/list",bb="hydra-acp/question/answer",vb="hydra-acp/question/dismiss"});import{EventEmitter as O0}from"events";import{WebSocket as L0}from"ws";function B0(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=ea(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new L0(t,e,n),o=()=>{i.off("error",a),s(rs(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function kb(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??B0,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Kt(d),f;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)f=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);f=(await Tc(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let u=new Qf(l,d,f,t,o),p=!1,h=m=>{p||(p=!0,u.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&u.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),os(t,f,o).catch(()=>{}),m}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[Ft]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var Qf,Ib=V(()=>{"use strict";ta();Ra();jr();uo();Ot();Qf=class extends O0{_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(()=>{}),os(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 Gf,rl,xb=V(()=>{"use strict";Ao();or();Gf=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())}},rl=class extends Gf{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=ss(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=xo(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=xo(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={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=Pa(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=Pa(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=pr(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return hr(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_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._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(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._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.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._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.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._pendingThoughtText=null,this._pendingThoughtRange=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 U0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function ja(t,e,n,s){Bn();let r=U0(e,n??N0),i=0,o=null,a=null,c=()=>{let E=Ms(t)-8;return Math.max(1,Math.min(D0,e.length,E))},d=()=>{let E=c(),P=Math.max(0,e.length-E);i>P&&(i=P),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},f=null,u=0,p=(E,P)=>{if(E<i||E>=i+u)return;let B=e[E];if(!B)return;let _=P.contentW,D=P.contentY+2+(E-i);t.moveTo(P.contentX,D);let N=E===r?"\u276F":" ",L=B.description??B.name,K=` ${N} ${B.id}`;if(E===r){let X=`${K} ${L}`;t.brightWhite.bgBlue.noFormat(La(Xe(X,_),_))}else{let X=_-K.length-2,Z=X>1?` ${Xe(L,X)}`:"";t.noFormat(K),Z.length>0&&t.dim.noFormat(Z);let Q=K.length+Z.length;Q<_&&t.noFormat(" ".repeat(_-Q))}},h=(E,P)=>{let B=E.contentY+2+u+1;t.moveTo(E.contentX,B);let D=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>P?` (${r+1}/${e.length})`:""}`,N=La(Xe(D,E.contentW),E.contentW);t.dim.noFormat(N)},m=()=>{d();let E=c(),P=E+4,B=Math.min(H0,Math.max(40,Jt(t)-8)),_=Nn(t,{contentHeight:P,contentWidth:B,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=_,f=_,u=Math.min(E,e.length-i),o=_.contentY+2,t.moveTo(_.contentX,_.contentY),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let D=Math.min(e.length,i+E);for(let N=i;N<D;N++)p(N,_);return h(_,E),_},y=()=>m(),w=E=>{let P=f;if(P===null){m();return}let B=c(),_=i;if(l(),i!==_){m();return}u=Math.min(B,e.length-i),E!==r&&(p(E,P),p(r,P)),h(P,B)},b=()=>{if(r<e.length-1){let E=r;r++,w(E)}},S=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=f;if(E===null){m();return}let P=c();d(),u=Math.min(P,e.length-i);let B=Math.min(e.length,i+P);for(let _=i;_<B;_++)p(_,E);for(let _=u;_<P;_++){let D=E.contentY+2+_;t.moveTo(E.contentX,D),t.noFormat(" ".repeat(E.contentW))}h(E,P)},A=E=>{let P=c(),B=Math.max(0,e.length-P);if(B===0)return;let _=Math.max(0,Math.min(B,i+E));_!==i&&(i=_,k())};return ds({term:t,render:y,overlay:s?.overlay===!0,onKey:(E,P,B,_)=>{if(E==="CTRL_C"||E==="CTRL_D"){_({kind:"cancel"});return}if(E==="ESCAPE"){_({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let D=e[r];D&&_({kind:"select",agentId:D.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){b();return}if(B?.isCharacter){let D=E.toLowerCase();if(D==="s"){let N=e[r];N&&_({kind:"select",agentId:N.id,persist:!0});return}if(D==="j"){b();return}if(D==="k"){S();return}}},onMouse:(E,P,B)=>{if(E==="MOUSE_WHEEL_UP"){A(-1);return}if(E==="MOUSE_WHEEL_DOWN"){A(1);return}if(E==="MOUSE_MOTION"){let X=P?.y;if(typeof X!="number"||o===null)return;let Z=X-o;if(Z<0||Z>=u)return;let Q=i+Z;if(Q<0||Q>=e.length)return;if(Q!==r){let fe=r;r=Q,w(fe)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let _=P?.x,D=P?.y;if(a!==null&&typeof _=="number"&&typeof D=="number"&&(_<a.x||_>=a.x+a.w||D<a.y||D>=a.y+a.h)){B({kind:"back"});return}if(typeof D!="number"||o===null)return;let N=D-o;if(N<0||N>=u)return;let L=i+N;if(L<0||L>=e.length)return;let K=e[L];K&&B({kind:"select",agentId:K.id,persist:!1})}})}var N0,D0,H0,Xf=V(()=>{"use strict";ri();N0="opencode",D0=20,H0=88});import j0 from"path";function qa(t){return Ab[j0.extname(t).toLowerCase()]??null}function q0(t){return qa(t)!==null}function Zf(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(!W0.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 z0(t){return Zf(t)!==null}function kn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Cb(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(!z0(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!q0(o))return null;n.push(o)}return n.length>0?n:null}var cs,Ab,W0,il=V(()=>{"use strict";cs=10*1024*1024,Ab={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};W0=new Set(Object.values(Ab))});import{spawn as K0}from"child_process";import ep from"fs/promises";import J0 from"os";import Y0 from"path";async function al(t={}){let e={...tp,...t};return e.platform==="darwin"?X0(e):e.platform==="linux"?Z0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Eb(t={}){let e={...tp,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Oo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Oo(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 Wa(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Pb(t,e={}){let{target:n="both",...s}=e,r={...tp,...s},i=await V0(r,t,n);if(i.ok)return i;let o=Q0(r,t,n);return o.ok||o.reason!==Mb?o:i}async function V0(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await ol(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 Oo(t,"wl-copy")?Tb(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Oo(t,"xclip")?Tb(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 Tb(t,e,n,s,r,i,o){let a=n;if(i){try{await ol(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await ol(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await ol(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function Q0(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Rb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Rb} 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??G0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Mb}}function G0(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 X0(t){let e=Y0.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 _b(t.spawn,"osascript",s);let r=await rT(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await ep.unlink(e).catch(()=>{})}try{let r=await Wa(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function Z0(t){let e=await eT(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await sT(t,e),s=nT(n);if(s)try{let r=await Wa(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>cs?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Wa(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function eT(t){return t.env.WAYLAND_DISPLAY&&await Oo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Oo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function nT(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of tT)if(e.has(n))return n;return null}async function sT(t,e){try{return(await Wa(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
200
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function np(t){return t.replace(/\r\n?/g,`
201
- `)}async function Oo(t,e){try{return await _b(t.spawn,"which",[e]),!0}catch{return!1}}async function rT(t,e){try{let n=await ep.readFile(t);return e&&await ep.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>cs?{ok:!1,reason:`clipboard image is ${kn(n.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:qa(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function _b(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 ol(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",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function Wa(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};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=>{d||(d=!0,r(f))}),i.on("close",f=>{c=f??0,l()})})}var tp,Rb,Mb,tT,dl=V(()=>{"use strict";il();tp={platform:process.platform,env:process.env,spawn:K0,tmpdir:J0.tmpdir};Rb=74994;Mb="no TTY available for OSC 52 clipboard write";tT=["image/png","image/jpeg","image/gif","image/webp"]});function oT(t,e){return`[pasted #${t} +${e} lines]`}var iT,za,sp,aT,_s,rp=V(()=>{"use strict";iT=/\[pasted #(\d+) \+\d+ lines\]/g,za=/\[pasted #(\d+) \+\d+ lines\]$/,sp=/^\[pasted #(\d+) \+\d+ lines\]/;aT=500,_s=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;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({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.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>aT&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();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],this.clearUndoHistory()}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.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){if(this.clearDoubleTap(),e.text.length===0)return[{type:"attachment-request",source:"clipboard"}];this.recordEdit();let n=e.text.split(`
202
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(oT(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(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.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),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.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
203
- `)}expandPastes(e){return e.replace(iT,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}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=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
198
+ `),i({exitCode:-1})}})}function PR(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function qf(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(PR(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Uw(t,e,n,s,r){Bn();let i=xR(e,n,s),o=!1,a,c,d=()=>{let f=4;i.command&&f++,i.url&&f++,i.methodLines&&(f+=1+i.methodLines.length),a&&f++,c&&f++;let u=Nn(t,{contentHeight:f,contentWidth:80,title:"Authentication required"}),p=u.contentW,h=0;if(a&&(t.moveTo(u.contentX,u.contentY+h),t.brightYellow.noFormat(Xe(` ${a}`,p)),h++),c&&(t.moveTo(u.contentX,u.contentY+h),t.brightRed.noFormat(Xe(` ${c}`,p)),h++),t.moveTo(u.contentX,u.contentY+h),t.brightWhite.bold.noFormat(Xe(` ${i.title}`,p)),h+=2,t.moveTo(u.contentX,u.contentY+h),t.noFormat(Xe(` ${i.description}`,p)),h++,i.command&&(t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(Xe(i.command,p-7)),h++),i.url&&(t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(Xe(i.url,p-7)),h++),i.methodLines){t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(" "),t.noFormat(Xe(m.label,p-3)),h++}return h++,t.moveTo(u.contentX,u.contentY+h),t.dim.noFormat(` ${i.footer}`),u},l=i.methodLines?.length??0;return ds({term:t,render:()=>{d()},onKey:(f,u,p,h)=>{if(o)return;let m=AR(f,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${Nw(y)}\u2026`,d();let w=r.runTerminalAuth??(b=>ER(t,b));(async()=>{let b=await qf(y,{authenticate:r.authenticate,runTerminalAuth:w});if(b.kind==="terminal-completed"){h("terminal-completed");return}if(b.kind==="retry"){h("retry");return}if(b.kind==="error"){c=b.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var kR,IR,Wf=V(()=>{"use strict";Hr();Id();Ad();ri();kR="This agent requires authentication before use.",IR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Kw}from"timers/promises";function DR(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var OR,LR,BR,NR,_o,zf=V(()=>{"use strict";Ca();uo();OR=200,LR=5e3,BR=2,NR=60,_o=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;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.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}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(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),Kw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=OR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Qr(s,this.opts.subprotocols);this.bindStream(rs(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.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>=NR)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await Kw(n),this.destroyed)return;n=Math.min(n*BR,LR)}}bindStream(e){this.current=e,e.onMessage(n=>{if(DR(n)&&n.id!==null){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.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(n){this.scheduleReconnect(n);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}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}
199
+ `)}}});function Jw(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function ii(t){return{outcome:{outcome:"selected",optionId:Jw(t,["allow_once","allow_always"])}}}function Yw(t){return{outcome:{outcome:"selected",optionId:Jw(t,["reject_once","reject_always"])}}}function Xc(t){return t&&typeof t=="object"?t:void 0}function Ba(t){return typeof t=="string"&&t.length>0?t:void 0}function Vw(t){let e=Xc(t),n=Xc(e?.toolCall),s={paths:[]};if(!n)return s;let r=Ba(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Ba(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(Xc(d)?.path);let c=Xc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Ba(c.command);d&&(s.command=d);let l=Ba(c.url);l&&(s.url=l);let f=Ba(c.description);f&&(s.description=f)}return s}function Qw(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 Zc=V(()=>{"use strict"});function N0(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function mb(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 D0(t,e){let n=mb(t),s=mb(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 Na(){if(yr!==void 0)return yr;if(N0())return yr=null,yr;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:gb,version:be}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&D0(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}yr={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{}yr=null}}catch{yr=null}return yr}function Da(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${gb}`}var gb,yr,Yf=V(()=>{"use strict";an();gb="@hydra-acp/cli"});import*as Ha from"fs/promises";import*as Vf from"path";async function Ua(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Vf.resolve(tt(e)),s;try{s=await Ha.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 yb(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 Ha.stat(r)).isDirectory())return r}catch{}return null}async function wb(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=Vf.resolve(tt(r)),o;try{o=(await Ha.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var Qf=V(()=>{"use strict";Ge()});var bb,vb,Sb,kb=V(()=>{"use strict";bb="hydra-acp/question/list",vb="hydra-acp/question/answer",Sb="hydra-acp/question/dismiss"});import{EventEmitter as H0}from"events";import{WebSocket as U0}from"ws";function j0(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=ea(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new U0(t,e,n),o=()=>{i.off("error",a),s(rs(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Ib(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??j0,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Kt(d),f;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)f=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);f=(await Tc(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let u=new Gf(l,d,f,t,o),p=!1,h=m=>{p||(p=!0,u.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&u.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),os(t,f,o).catch(()=>{}),m}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[Ft]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var Gf,xb=V(()=>{"use strict";ta();Ra();jr();uo();Ot();Gf=class extends H0{_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(()=>{}),os(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 Xf,rl,Ab=V(()=>{"use strict";Ao();ar();Xf=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())}},rl=class extends Xf{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=ss(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=xo(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=xo(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={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=Pa(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=Pa(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=hr(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return mr(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_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._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(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._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.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._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.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._pendingThoughtText=null,this._pendingThoughtRange=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 K0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function ja(t,e,n,s){Bn();let r=K0(e,n??q0),i=0,o=null,a=null,c=()=>{let E=Ms(t)-8;return Math.max(1,Math.min(W0,e.length,E))},d=()=>{let E=c(),P=Math.max(0,e.length-E);i>P&&(i=P),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},f=null,u=0,p=(E,P)=>{if(E<i||E>=i+u)return;let B=e[E];if(!B)return;let _=P.contentW,D=P.contentY+2+(E-i);t.moveTo(P.contentX,D);let N=E===r?"\u276F":" ",L=B.description??B.name,K=` ${N} ${B.id}`;if(E===r){let X=`${K} ${L}`;t.brightWhite.bgBlue.noFormat(La(Xe(X,_),_))}else{let X=_-K.length-2,Z=X>1?` ${Xe(L,X)}`:"";t.noFormat(K),Z.length>0&&t.dim.noFormat(Z);let Q=K.length+Z.length;Q<_&&t.noFormat(" ".repeat(_-Q))}},h=(E,P)=>{let B=E.contentY+2+u+1;t.moveTo(E.contentX,B);let D=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>P?` (${r+1}/${e.length})`:""}`,N=La(Xe(D,E.contentW),E.contentW);t.dim.noFormat(N)},m=()=>{d();let E=c(),P=E+4,B=Math.min(z0,Math.max(40,Jt(t)-8)),_=Nn(t,{contentHeight:P,contentWidth:B,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=_,f=_,u=Math.min(E,e.length-i),o=_.contentY+2,t.moveTo(_.contentX,_.contentY),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let D=Math.min(e.length,i+E);for(let N=i;N<D;N++)p(N,_);return h(_,E),_},y=()=>m(),w=E=>{let P=f;if(P===null){m();return}let B=c(),_=i;if(l(),i!==_){m();return}u=Math.min(B,e.length-i),E!==r&&(p(E,P),p(r,P)),h(P,B)},b=()=>{if(r<e.length-1){let E=r;r++,w(E)}},S=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=f;if(E===null){m();return}let P=c();d(),u=Math.min(P,e.length-i);let B=Math.min(e.length,i+P);for(let _=i;_<B;_++)p(_,E);for(let _=u;_<P;_++){let D=E.contentY+2+_;t.moveTo(E.contentX,D),t.noFormat(" ".repeat(E.contentW))}h(E,P)},A=E=>{let P=c(),B=Math.max(0,e.length-P);if(B===0)return;let _=Math.max(0,Math.min(B,i+E));_!==i&&(i=_,k())};return ds({term:t,render:y,overlay:s?.overlay===!0,onKey:(E,P,B,_)=>{if(E==="CTRL_C"||E==="CTRL_D"){_({kind:"cancel"});return}if(E==="ESCAPE"){_({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let D=e[r];D&&_({kind:"select",agentId:D.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){b();return}if(B?.isCharacter){let D=E.toLowerCase();if(D==="s"){let N=e[r];N&&_({kind:"select",agentId:N.id,persist:!0});return}if(D==="j"){b();return}if(D==="k"){S();return}}},onMouse:(E,P,B)=>{if(E==="MOUSE_WHEEL_UP"){A(-1);return}if(E==="MOUSE_WHEEL_DOWN"){A(1);return}if(E==="MOUSE_MOTION"){let X=P?.y;if(typeof X!="number"||o===null)return;let Z=X-o;if(Z<0||Z>=u)return;let Q=i+Z;if(Q<0||Q>=e.length)return;if(Q!==r){let fe=r;r=Q,w(fe)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let _=P?.x,D=P?.y;if(a!==null&&typeof _=="number"&&typeof D=="number"&&(_<a.x||_>=a.x+a.w||D<a.y||D>=a.y+a.h)){B({kind:"back"});return}if(typeof D!="number"||o===null)return;let N=D-o;if(N<0||N>=u)return;let L=i+N;if(L<0||L>=e.length)return;let K=e[L];K&&B({kind:"select",agentId:K.id,persist:!1})}})}var q0,W0,z0,Zf=V(()=>{"use strict";ri();q0="opencode",W0=20,z0=88});import J0 from"path";function qa(t){return Cb[J0.extname(t).toLowerCase()]??null}function Y0(t){return qa(t)!==null}function ep(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(!V0.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 Q0(t){return ep(t)!==null}function kn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Rb(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(!Q0(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!Y0(o))return null;n.push(o)}return n.length>0?n:null}var cs,Cb,V0,il=V(()=>{"use strict";cs=10*1024*1024,Cb={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};V0=new Set(Object.values(Cb))});import{spawn as G0}from"child_process";import tp from"fs/promises";import X0 from"os";import Z0 from"path";async function al(t={}){let e={...np,...t};return e.platform==="darwin"?sT(e):e.platform==="linux"?rT(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Pb(t={}){let e={...np,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Oo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Oo(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 Wa(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:sp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Mb(t,e={}){let{target:n="both",...s}=e,r={...np,...s},i=await eT(r,t,n);if(i.ok)return i;let o=tT(r,t,n);return o.ok||o.reason!==_b?o:i}async function eT(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await ol(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 Oo(t,"wl-copy")?Eb(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Oo(t,"xclip")?Eb(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 Eb(t,e,n,s,r,i,o){let a=n;if(i){try{await ol(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await ol(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await ol(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function tT(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Tb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Tb} 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??nT)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:_b}}function nT(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 sT(t){let e=Z0.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 $b(t.spawn,"osascript",s);let r=await cT(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await tp.unlink(e).catch(()=>{})}try{let r=await Wa(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:sp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function rT(t){let e=await iT(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await dT(t,e),s=aT(n);if(s)try{let r=await Wa(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>cs?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Wa(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:sp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function iT(t){return t.env.WAYLAND_DISPLAY&&await Oo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Oo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function aT(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of oT)if(e.has(n))return n;return null}async function dT(t,e){try{return(await Wa(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
200
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function sp(t){return t.replace(/\r\n?/g,`
201
+ `)}async function Oo(t,e){try{return await $b(t.spawn,"which",[e]),!0}catch{return!1}}async function cT(t,e){try{let n=await tp.readFile(t);return e&&await tp.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>cs?{ok:!1,reason:`clipboard image is ${kn(n.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:qa(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function $b(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 ol(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",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function Wa(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};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=>{d||(d=!0,r(f))}),i.on("close",f=>{c=f??0,l()})})}var np,Tb,_b,oT,dl=V(()=>{"use strict";il();np={platform:process.platform,env:process.env,spawn:G0,tmpdir:X0.tmpdir};Tb=74994;_b="no TTY available for OSC 52 clipboard write";oT=["image/png","image/jpeg","image/gif","image/webp"]});function uT(t,e){return`[pasted #${t} +${e} lines]`}var lT,za,rp,fT,_s,ip=V(()=>{"use strict";lT=/\[pasted #(\d+) \+\d+ lines\]/g,za=/\[pasted #(\d+) \+\d+ lines\]$/,rp=/^\[pasted #(\d+) \+\d+ lines\]/;fT=500,_s=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;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({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.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>fT&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();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],this.clearUndoHistory()}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.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){if(this.clearDoubleTap(),e.text.length===0)return[{type:"attachment-request",source:"clipboard"}];this.recordEdit();let n=e.text.split(`
202
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(uT(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(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.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),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.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
203
+ `)}expandPastes(e){return e.replace(lT,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}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=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
204
204
  `)){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(`
205
- `);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]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),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(za);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(sp);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=`
205
+ `);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]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),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(za);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(rp);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=`
206
206
  `,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+`
207
207
  `,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=`
208
208
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
209
- `+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(za);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}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(za);if(s!==null){this.killBuffer=s[0];let a=this.col-s[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let r=/[A-Za-z0-9_]/,i=this.col;for(;i>0&&!r.test(e[i-1]??"");)i-=1;for(;i>0&&r.test(e[i-1]??"");)i-=1;let o=e.slice(i,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(za);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(sp);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(za);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(sp);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(`
210
- `),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],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{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.recordEdit(),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"}]}}});var Lo,cl,ip=V(()=>{"use strict";Lo=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){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())}},cl=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import dT from"string-width";function $b(t,e){if(!t||e<=0)return 0;let n=0;for(let s of cT.segment(t)){let r=dT(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Fb(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 cT,Ob=V(()=>{"use strict";cT=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function lT(){Ka===0&&process.stdout.write($w),Ka++}function uT(){Ka!==0&&(Ka--,Ka===0&&process.stdout.write(Fw))}function Oe(t){lT();try{t()}finally{uT()}}var Ka,op=V(()=>{"use strict";Oa();Ka=0});import{spawn as fT}from"child_process";import{statSync as Lb}from"fs";import{homedir as Bb}from"os";import{isAbsolute as Nb,resolve as pT}from"path";import Ye from"string-width";import hT from"wrap-ansi";function xT(t){let e=t.replace(/\r\n?$|\n$/,"");return IT.test(e)?e:null}function AT(t,e){return!t||typeof t!="object"?!1:t[e]===!0}function CT(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function RT(t,e){if(t.body!==e.body||(t.prefix??"")!==(e.prefix??"")||(t.bodyStyle??"")!==(e.bodyStyle??"")||(t.prefixStyle??"")!==(e.prefixStyle??"")||!!t.ansi!=!!e.ansi||!!t.fillRow!=!!e.fillRow||!!t.collapsed!=!!e.collapsed||(t.blockKey??"")!==(e.blockKey??"")||(t.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let n=t.iterm2Image,s=e.iterm2Image;if(n===void 0!=(s===void 0)||n&&s&&(n.data!==s.data||n.heightCells!==s.heightCells))return!1;let r=t.links,i=e.links;if(r===void 0!=(i===void 0))return!1;if(r&&i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++){let a=r[o],c=i[o];if(a.start!==c.start||a.end!==c.end||a.url!==c.url)return!1}}return!0}function Hb(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 c=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}|${c}`}function ls(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 c=r[a];if(c===" "||c===" "){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 Fs(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.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 Ub(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){$s(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){$s(t,e.slice(c),n,o);return}d>c&&$s(t,e.slice(c,d),n,o);let l=r!==null&&d===r;$s(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Ja(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function $s(t,e,n,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{t.noFormat(a)};switch(n){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),t.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),t.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),t.brightYellow.noFormat(e),o(i);return;case"tool":o(r),t.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),t.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);t.bgColorGrayscale(25)(a);return}case"code":{t.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}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.dim.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(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(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 TT(t,e){return e<=0?[t]:t.length===0?[""]:hT(t,e,{hard:!0,trim:!1}).split(`
211
- `)}function Qb(t){Vb=t}function Gb(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function yr(t){return Ye(t,{ambiguousIsNarrow:!Vb})}function PT(t,e){if(!t.startsWith("\x1B]8;",e))return null;for(let n=e+4;n<t.length;n++){if(t[n]==="\x07")return t.slice(e,n+1);if(t[n]==="\x1B"&&t[n+1]==="\\")return t.slice(e,n+2)}return null}function MT(t,e){if(!t.startsWith("\x1B[",e))return null;let n=e+2;for(;n<t.length;){let r=t.charCodeAt(n);if(r<48||r>63)break;n+=1}for(;n<t.length;){let r=t.charCodeAt(n);if(r<32||r>47)break;n+=1}if(n>=t.length)return null;let s=t.charCodeAt(n);return s<64||s>126?null:t.slice(e,n+1)}function Dn(t,e){if(t.charCodeAt(e)===27){let s=PT(t,e);if(s!==null)return{text:s,width:0};let r=MT(t,e);return r!==null?{text:r,width:0}:null}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 ET.test(n)?{text:t.slice(e,e+2),width:0}:null}function mp(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Dn(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function gp(t,e,n){let s=0,r=e;for(;r<n;){let i=Dn(t,r);if(i){r+=i.text.length,i.width>0&&(s+=1);continue}s+=1,r+=1}return s}function yp(t,e,n){let s=e;for(;n>0&&s<t.length;){let r=Dn(t,s);if(r){s+=r.text.length,r.width>0&&(n-=1);continue}s+=1,n-=1}return s}function jb(t){if(!t.includes("^")&&!t.includes("\x1B"))return t;let e="",n=0;for(;n<t.length;){let s=Dn(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function _T(t){if(!t.includes("^")&&!t.includes("\x1B"))return"";let e="",n=0;for(;n<t.length;){let s=Dn(t,n);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}n+=s.text.length;continue}n+=1}return e}function Xb(t){if(!t.includes("^")&&!t.includes("\x1B"))return!1;for(let e=0;e<t.length;e++)if(Dn(t,e))return!0;return!1}function qb(t,e){let n=t.indexOf("^",e),s=t.indexOf("\x1B",e);return n===-1?s:s===-1?n:Math.min(n,s)}function*bp(t){let e=0;for(;e<t.length;){let n=Dn(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=qb(t,e);for(;r!==-1&&r<t.length;){if(Dn(t,r)){s=r;break}r=qb(t,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of wp.segment(t.slice(e,s)))yield{text:i,width:yr(i)};e=s}}function $T(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 FT(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Xb(t);return!s&&!Yb.test(t)?OT(t,e):LT(t,e,s)}function OT(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 LT(t,e,n){let s=[],r=n?[...bp(t)]:BT(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function BT(t){let e=[];for(let{segment:n}of wp.segment(t))e.push({text:n,width:yr(n)});return e}function Ct(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Xb(t);if(!s&&t.length<=e&&!Yb.test(t))return t;if(!s)return yr(t)<=e?t:e<=1?Wb(t,e):Wb(t,e-1)+"\u2026";let r=[...bp(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?zb(r,e):zb(r,e-1)+"\u2026"}function Wb(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of wp.segment(t)){let i=yr(r);if(s+i>e)break;n+=r,s+=i}return n}function zb(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 NT(t){let e=t.indexOf(`
212
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Kb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${pl(t.used)}/${pl(t.size)}`):e.push(pl(t.used)):typeof t.size=="number"&&e.push(`/${pl(t.size)}`),typeof t.costAmount=="number"&&e.push(mf(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function pl(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function ml(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"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-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_Q":return"ctrl-q";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 wr(){let t=[To,Eo,Tw,Po,Ew,Uf,Ps,ni,si,ti,ei,"\x1B>",$a,Jc,Yc,"\x1B]9;4;0\x07",xw].join("");try{process.stdout.write(t)}catch{}}function Zb(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 Jb(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",113:"ctrl-q",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":t===127&&e===3||t===8&&e===3?"alt-backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var ap,ll,ul,dp,cp,mT,Db,gT,Je,nt,yT,st,lp,up,wT,bT,vT,fp,pp,hp,ST,kT,IT,hl,Yb,wp,Vb,ET,fl,vp=V(()=>{"use strict";ip();gf();we();es();il();Ao();Ob();dl();op();Hr();Oa();ap=500,ll=1,ul=/[A-Za-z0-9_]/,dp=/[A-Za-z0-9_./\-~+@]/,cp=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,mT=/[.,;:!?)\]}'"]/,Db=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,gT=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Je=1,nt=0,yT=1,st=1,lp=8,up=5,wT=12,bT=12,vT=30,fp=6,pp=4,hp=2,ST=1e3,kT=1e4,IT=/^(https?|ftp):\/\/\S+$/;hl=class t{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;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;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;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=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??ST,this.painter=new Lo(this.term),this.scheduler=new cl({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??kT,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(Hf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),oe({src:"grab",site:"screen.start",on:!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.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),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),oe({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Yc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write($a),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(wr(),this.term.fullscreen(!1),this.term(`
213
- `)))}installBracketedPaste(){process.stdout.write(Kc),process.stdout.write(Cw),process.stdout.write(Rw),process.stdout.write(Aw),process.stdout.write(Vc);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(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(ti),process.stdout.write(Fa),process.stdout.write(ei),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(Pw),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(Uf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>wr(),this.onProcessSignal=e=>{wr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{wr(),process.stderr.write(`
209
+ `+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(za);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}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(za);if(s!==null){this.killBuffer=s[0];let a=this.col-s[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let r=/[A-Za-z0-9_]/,i=this.col;for(;i>0&&!r.test(e[i-1]??"");)i-=1;for(;i>0&&r.test(e[i-1]??"");)i-=1;let o=e.slice(i,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(za);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(rp);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(za);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(rp);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(`
210
+ `),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],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{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.recordEdit(),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"}]}}});var Lo,cl,op=V(()=>{"use strict";Lo=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){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())}},cl=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import pT from"string-width";function Fb(t,e){if(!t||e<=0)return 0;let n=0;for(let s of hT.segment(t)){let r=pT(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Ob(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 hT,Lb=V(()=>{"use strict";hT=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function mT(){Ka===0&&process.stdout.write(Fw),Ka++}function gT(){Ka!==0&&(Ka--,Ka===0&&process.stdout.write(Ow))}function Le(t){mT();try{t()}finally{gT()}}var Ka,ap=V(()=>{"use strict";Oa();Ka=0});import{spawn as yT}from"child_process";import{statSync as Bb}from"fs";import{homedir as Nb}from"os";import{isAbsolute as Db,resolve as wT}from"path";import Ve from"string-width";import bT from"wrap-ansi";function ET(t){let e=t.replace(/\r\n?$|\n$/,"");return TT.test(e)?e:null}function PT(t,e){return!t||typeof t!="object"?!1:t[e]===!0}function MT(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function _T(t,e){if(t.body!==e.body||(t.prefix??"")!==(e.prefix??"")||(t.bodyStyle??"")!==(e.bodyStyle??"")||(t.prefixStyle??"")!==(e.prefixStyle??"")||!!t.ansi!=!!e.ansi||!!t.fillRow!=!!e.fillRow||!!t.collapsed!=!!e.collapsed||(t.blockKey??"")!==(e.blockKey??"")||(t.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let n=t.iterm2Image,s=e.iterm2Image;if(n===void 0!=(s===void 0)||n&&s&&(n.data!==s.data||n.heightCells!==s.heightCells))return!1;let r=t.links,i=e.links;if(r===void 0!=(i===void 0))return!1;if(r&&i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++){let a=r[o],c=i[o];if(a.start!==c.start||a.end!==c.end||a.url!==c.url)return!1}}return!0}function Ub(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 c=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}|${c}`}function ls(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 c=r[a];if(c===" "||c===" "){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 Fs(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.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 jb(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){$s(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){$s(t,e.slice(c),n,o);return}d>c&&$s(t,e.slice(c,d),n,o);let l=r!==null&&d===r;$s(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Ja(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function $s(t,e,n,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{t.noFormat(a)};switch(n){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),t.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),t.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),t.brightYellow.noFormat(e),o(i);return;case"tool":o(r),t.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),t.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);t.bgColorGrayscale(25)(a);return}case"code":{t.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}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.dim.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(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(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 $T(t,e){return e<=0?[t]:t.length===0?[""]:bT(t,e,{hard:!0,trim:!1}).split(`
211
+ `)}function Gb(t){Qb=t}function Xb(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function wr(t){return Ve(t,{ambiguousIsNarrow:!Qb})}function OT(t,e){if(!t.startsWith("\x1B]8;",e))return null;for(let n=e+4;n<t.length;n++){if(t[n]==="\x07")return t.slice(e,n+1);if(t[n]==="\x1B"&&t[n+1]==="\\")return t.slice(e,n+2)}return null}function LT(t,e){if(!t.startsWith("\x1B[",e))return null;let n=e+2;for(;n<t.length;){let r=t.charCodeAt(n);if(r<48||r>63)break;n+=1}for(;n<t.length;){let r=t.charCodeAt(n);if(r<32||r>47)break;n+=1}if(n>=t.length)return null;let s=t.charCodeAt(n);return s<64||s>126?null:t.slice(e,n+1)}function Dn(t,e){if(t.charCodeAt(e)===27){let s=OT(t,e);if(s!==null)return{text:s,width:0};let r=LT(t,e);return r!==null?{text:r,width:0}:null}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 FT.test(n)?{text:t.slice(e,e+2),width:0}:null}function gp(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Dn(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function yp(t,e,n){let s=0,r=e;for(;r<n;){let i=Dn(t,r);if(i){r+=i.text.length,i.width>0&&(s+=1);continue}s+=1,r+=1}return s}function wp(t,e,n){let s=e;for(;n>0&&s<t.length;){let r=Dn(t,s);if(r){s+=r.text.length,r.width>0&&(n-=1);continue}s+=1,n-=1}return s}function qb(t){if(!t.includes("^")&&!t.includes("\x1B"))return t;let e="",n=0;for(;n<t.length;){let s=Dn(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function BT(t){if(!t.includes("^")&&!t.includes("\x1B"))return"";let e="",n=0;for(;n<t.length;){let s=Dn(t,n);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}n+=s.text.length;continue}n+=1}return e}function Zb(t){if(!t.includes("^")&&!t.includes("\x1B"))return!1;for(let e=0;e<t.length;e++)if(Dn(t,e))return!0;return!1}function Wb(t,e){let n=t.indexOf("^",e),s=t.indexOf("\x1B",e);return n===-1?s:s===-1?n:Math.min(n,s)}function*vp(t){let e=0;for(;e<t.length;){let n=Dn(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=Wb(t,e);for(;r!==-1&&r<t.length;){if(Dn(t,r)){s=r;break}r=Wb(t,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of bp.segment(t.slice(e,s)))yield{text:i,width:wr(i)};e=s}}function NT(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 DT(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Zb(t);return!s&&!Vb.test(t)?HT(t,e):UT(t,e,s)}function HT(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 UT(t,e,n){let s=[],r=n?[...vp(t)]:jT(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function jT(t){let e=[];for(let{segment:n}of bp.segment(t))e.push({text:n,width:wr(n)});return e}function Ct(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Zb(t);if(!s&&t.length<=e&&!Vb.test(t))return t;if(!s)return wr(t)<=e?t:e<=1?zb(t,e):zb(t,e-1)+"\u2026";let r=[...vp(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?Kb(r,e):Kb(r,e-1)+"\u2026"}function zb(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of bp.segment(t)){let i=wr(r);if(s+i>e)break;n+=r,s+=i}return n}function Kb(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 qT(t){let e=t.indexOf(`
212
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Jb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${pl(t.used)}/${pl(t.size)}`):e.push(pl(t.used)):typeof t.size=="number"&&e.push(`/${pl(t.size)}`),typeof t.costAmount=="number"&&e.push(gf(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function pl(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function ml(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"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-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_Q":return"ctrl-q";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 br(){let t=[To,Eo,Ew,Po,Pw,jf,Ps,ni,si,ti,ei,"\x1B>",$a,Jc,Yc,"\x1B]9;4;0\x07",Aw].join("");try{process.stdout.write(t)}catch{}}function ev(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 Yb(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",113:"ctrl-q",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":t===127&&e===3||t===8&&e===3?"alt-backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var dp,ll,ul,cp,lp,vT,Hb,ST,Ye,nt,kT,st,up,fp,IT,xT,AT,pp,hp,mp,CT,RT,TT,hl,Vb,bp,Qb,FT,fl,Sp=V(()=>{"use strict";op();yf();we();es();il();Ao();Lb();dl();ap();Hr();Oa();dp=500,ll=1,ul=/[A-Za-z0-9_]/,cp=/[A-Za-z0-9_./\-~+@]/,lp=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,vT=/[.,;:!?)\]}'"]/,Hb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,ST=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Ye=1,nt=0,kT=1,st=1,up=8,fp=5,IT=12,xT=12,AT=30,pp=6,hp=4,mp=2,CT=1e3,RT=1e4,TT=/^(https?|ftp):\/\/\S+$/;hl=class t{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;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;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;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=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??CT,this.painter=new Lo(this.term),this.scheduler=new cl({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??RT,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(Uf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),oe({src:"grab",site:"screen.start",on:!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.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),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),oe({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Yc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write($a),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(br(),this.term.fullscreen(!1),this.term(`
213
+ `)))}installBracketedPaste(){process.stdout.write(Kc),process.stdout.write(Rw),process.stdout.write(Tw),process.stdout.write(Cw),process.stdout.write(Vc);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(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(ti),process.stdout.write(Fa),process.stdout.write(ei),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(Mw),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(jf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>br(),this.onProcessSignal=e=>{br(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{br(),process.stderr.write(`
214
214
  uncaught: ${e.stack??e.message}
215
- `),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(Mw),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){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");oe({tag:"raw",bytes:s,len:e.length})}let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.includes("\x1B[I")||n.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=n.indexOf("\x1B[I"),i=n.indexOf("\x1B[O"),o=r===-1?i:i===-1?r:Math.min(r,i);if(o===-1)break;let a=o===r;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),n=n.slice(0,o)+n.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(n==="\x1B\x7F"||n==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(n.startsWith("\x1B\x7F")||n.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(n.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(Ro)){this.handleRawStdinSegment(n);return}if(n.includes(`
215
+ `),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(_w),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){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");oe({tag:"raw",bytes:s,len:e.length})}let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.includes("\x1B[I")||n.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=n.indexOf("\x1B[I"),i=n.indexOf("\x1B[O"),o=r===-1?i:i===-1?r:Math.min(r,i);if(o===-1)break;let a=o===r;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),n=n.slice(0,o)+n.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(n==="\x1B\x7F"||n==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(n.startsWith("\x1B\x7F")||n.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(n.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(Ro)){this.handleRawStdinSegment(n);return}if(n.includes(`
216
216
  `)){let s=n.split(`
217
- `);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=Jb(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=Jb(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=Ro,s=_a;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,`
218
- `);this.pasteBuffer="";let a=Cb(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=xT(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)),c=n.length-s.count,d=this.lines.slice(s.start,o),l=new Array(n.length),f=[];for(let u=0;u<n.length;u++){let p=d[u],h=n[u];p!==void 0&&RT(p,h)?l[u]=p:(p!==void 0&&f.push(p),l[u]=h)}for(let u=n.length;u<d.length;u++)f.push(d[u]);this.lines.splice(s.start,s.count,...l);for(let u of f)this.forgetLine(u);for(let u of l)this.lineIds.has(u)||this.trackLine(u);if(this.invalidateSelectionIfTouches(f),s.count=n.length,c!==0)for(let[u,p]of this.keyedBlocks)u!==e&&p.start>s.start&&(p.start+=c);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(`
219
- `),[o,...a]=i,c=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??"",c+=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),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let f={prefix:d,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),c+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(c),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=fl(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&&Oe(()=>{this.term.hideCursor(),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())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,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)),oe({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),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 c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,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}}}farEndpointFrom(e){if(this.selection===null)return null;let n=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.startLineId),i=this.lineIndexById(n.endLineId);if(s<0||r<0||i<0)return null;let o=(f,u,p,h)=>f!==p?f-p:u-h,a=o(s,e.offset,r,n.startOffset),c=o(s,e.offset,i,n.endOffset);if(a<=0)return{sourceLineId:n.endLineId,offset:n.endOffset};if(c>=0)return{sourceLineId:n.startLineId,offset:n.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-n.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-n.endOffset)>=d?{sourceLineId:n.endLineId,offset:n.endOffset}:{sourceLineId:n.startLineId,offset:n.startOffset}}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 c=(r.body??"").slice(o.start,o.end);(Ja(r.bodyStyle)||r.ansi)&&(c=jb(c)),n.push(c)}return n.join(`
220
- `)}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 c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=d===r?Math.max(0,Math.min(u,o)):0,h=d===i?Math.max(0,Math.min(u,a)):u;c.set(f,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null)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=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,c=Math.max(r.start,i),d=Math.min(r.end,a);if(d<=c)return null;let l,f;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let p=gp(u,i,c),h=gp(u,c,d);l=yp(e.body,o,p),f=yp(e.body,l,h)}else l=c-i+o,f=d-i+o;return{start:l,end:f,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let n=this.lineIndexById(e);return n===-1?null:this.lines[n]?.body??null}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"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}: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,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.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(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=c&&f.start<d)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(c=>c.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 c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(Hf),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()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=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.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&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.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}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(process.env.HYDRA_TUI_KEY_TRACE&&oe({tag:"key",name:e,isChar:!!n.isCharacter}),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=ml(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 r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=CT(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(l===null&&c==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let f=this.nearestKeyAboveRow(o.y),u=this.nearestKeyBelowRow(o.y);f!==null&&u!==null&&this.hoveredRunKeys.has(f)&&this.hoveredRunKeys.has(u)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let f=l?.key??null,u=l?.sub??null;(f!==this.hoveredBlockKey||u!==this.hoveredSubKey)&&(this.hoveredBlockKey=f,this.hoveredSubKey=u,this.hoveredRunKeys=f!==null&&this.onHoverRun?this.onHoverRun(f)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback()));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=ll&&Math.abs(o.y-d.y)<=ll&&Date.now()-d.t<=ap||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,AT(n,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let f=this.btwHeaderSidRegion();if(f!==null&&this.onHydraLinkClick&&o.y===f.row&&o.x>=f.colStart&&o.x<=f.colEnd)this.onHydraLinkClick(f.sessionId);else if(this.onBlockClick){let u=this.keyAtRow(o.y);if(u!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===u;)p-=1;this.schedulePendingBlockClick(u,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(n&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=ap&&Math.abs(e.x-i.x)<=ll&&Math.abs(e.y-i.y)<=ll&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let f=e.y;for(;f>1&&this.keyAtRow(f-1)===l;)f-=1;let u=e.y-f;if(this.onBlockDoubleClick(l,u)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&Db.test(l)){let u=l.match(Db)?.[1]??null;if(u&&this.onHydraLinkClick(u)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let n=this.lineById(e);if(n===null)return;let s=(n.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let n=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=n&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let n=this.scrollbackVisibleRows();if(n<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,n+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-n),a=r.slice(o,i),c=Math.max(0,n-a.length),d=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=d<c;if(d===0&&l||u){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(d>=n-1&&f){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,n){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=this.term.width,i=Math.max(1,Math.min(r,e));for(let o=1;o<s;o++){let a=n-o;if(a>=1){let d=this.resolveCellToSource(i,a);if(d!==null){let l=this.lineById(d.sourceLineId);return l?{sourceLineId:d.sourceLineId,offset:(l.body??"").length}:d}}let c=n+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let n=this.farEndpointFrom(e);return n===null?!1:(this.selectionAnchor=n,this.selectionDragStarted=!0,this.setSelection(n,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,n){if(this.autoscrollTimer!==null&&this.autoscrollDir===n){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=n,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},t.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=mp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!ul.test(r[a])&&!cp.test(r[a]))return null;let c=a;for(;c>0&&cp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&cp.test(r[d]);)d++;for(;d>c+1&&mT.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!ul.test(r[a]))return null;let f=a;for(;f>0&&ul.test(r[f-1]);)f--;let u=a+1;for(;u<r.length&&ul.test(r[u]);)u++;return this.projectCleanRangeToRaw(i,s.length,f,u)}projectCleanRangeToRaw(e,n,s,r){let i=n,o=n;for(let a=0;a<e.length;a++)if(e[a]===s&&i===n&&(i=a),e[a]===r&&o===n){o=a;break}return{start:i,end:o}}pathTokenAt(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{clean:r,rawToClean:i}=mp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!dp.test(r[a]))return null;let c=a;for(;c>0&&dp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&dp.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=r.slice(d).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi||!n.links)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=mp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of n.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Bb():`${Bb()}/${n.slice(2)}`);let s=Nb(n)||e.startsWith("~"),r=Nb(n)?n:pT(this.sessionbar.cwd,n);if(s)return r;try{if(Lb(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.raw;if(!gT.test(s))return!1;let r=s.startsWith(jt)?[s]:[jt+s,s],i=null;for(let o of r)try{if(Lb(O.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let f of c)f.includes("%f")&&(d=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let f=fT(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},ap);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset))}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&&Pb(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}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?_w:Yc))}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,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),f=i-l;return f<0||f>=d.length?null:d[f]?.blockKey??null}nearestKeyAboveRow(e){for(let n=e-1;n>=1;n--){let s=this.keyAtRow(n);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(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,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),f=i-l;if(f<0||f>=d.length)return null;let u=d[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}: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),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),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 h=this.wrapOrigin.get(p);if(!h)return null;let m=yr(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=Ja(p.bodyStyle)||p.ansi===!0?Fb(bp(p.body),b):$b(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=gp(p.body,y,k),P=yp(A,h.sourceColOffset,E);return{sourceLineId:h.sourceLineId,offset:P}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+k-y}}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=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}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=s.bodyDisplayShift??0,i=n.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}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 h=p.body.length;if(e.col<f+h){o=l.length-1-u;break}f+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Je-st-nt-yT-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(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),Oe(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-nt-st-Je;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-Je),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),n=this.term.height,s=this.sessionbar.title?.trim(),r=Ey(this.sessionbar.agent,this.sessionbar.model),i=dt(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=Ye(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",f=Ye(l),u,p;if(s){let b=Math.min(s.length,8);u=Math.min(i.length,Math.max(8,d-f-b)),p=Math.max(0,d-u-f)}else p=0,u=d;let h=Ct(i,u),m=s?Ct(s,p):"",y=Ye(h)+(s?f+Ye(m):0),w=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(w)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=fl(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?as(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;c.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;c.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let d=Kb(this.sessionbar.usage)??"",l="\u2500\u2500 ",f=a?` ${a}`:"",u=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Ye(o)+Ye(f)+u.length+Ye(s);for(let A of c)y+=Ye(" \xB7 ")+Ye(A.text);y+=Ye(p);let w=Ye(h)+Ye(d)+Ye(m),b=Math.max(0,n-y-w),S="\u2500".repeat(b),k=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),f&&(i?this.term.brightRed.noFormat(f):r==="busy"?this.term.brightYellow.noFormat(f):this.term.dim.noFormat(f)),s&&(this.term.dim(u),this.term.dim(s));for(let A of c)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let n=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=Ye(i)+Ye(a)+Ye(o),d=Math.max(0,n-c),l="\u2500".repeat(d),f=s?`${s.kind}|${s.text}`:"",u=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${f}|${u}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.terminalFocused?this.hoveredBannerHit:null;for(let w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let b=m[w];if(b===void 0)continue;let S=null;b.includes("mode")?S="mode":b.includes("pick")?S="pick":b.includes("guide")?S="guide":b.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(b):this.term.dim(b)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Ye(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Ye(w),S=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=S:w.includes("pick")&&h.pick===null?h.pick=S:w.includes("guide")&&h.guide===null?h.guide=S:w.includes("detach")&&h.detach===null&&(h.detach=S),m+=b+Ye(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?fl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Kb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Ye(n)+i.length+Ye(r)+o.length+Ye(c)+d.length,f="\u2500".repeat(Math.max(0,e-l)),u=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:f,usage:c,right:d,signature:u}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-nt-st-Je,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=fl(this.btwOverlaySessionId),f=1+c.length+Ye(a)+" \xB7 ".length,u=f+Ye(d)-1;return{row:o,colStart:f,colEnd:u,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(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 h=Math.max(0,r.length-s);this.scrollOffset>h&&(this.scrollOffset=h)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let u=-1,p=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let h=0;h<c.length;h++){let m=c[h]?.blockKey;m===void 0||!(m===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m))||(u===-1&&(u=h),p=h)}for(let h=0;h<s;h++){let m=n+h,y=h-d,w=y>=0?c[y]:void 0,b=this.activeMatchCol(w,l),S=w?this.selectionRangeForChunk(w):null,k=w!==void 0&&w.blockKey!==void 0&&(w.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w.blockKey)),A=w!==void 0&&w.blockKey===void 0&&u!==-1&&y>=u&&y<=p,E=k||A,P=this.terminalFocused&&E&&(this.hoveredSubKey===null||(w.hoverSubKey??null)===this.hoveredSubKey),B=Hb("sb",e,w,this.scrollbackHighlight,b,S)+(P?"|H":"");this.paintRow(m,B,()=>{w&&this.writeFormattedLine(w,e,b,f,S,P)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(up,this.queuedTexts.length)}chipRows(){return Math.min(pp,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(fp,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-Je-st-nt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let f=c+l,u=this.completions[l],p=l===e-1&&this.completions.length>fp,h=this.completions.length-fp+1,m=u?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,m,()=>{if(!u)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=u.name.padEnd(d),w=u.description??"",b=n-y.length-4,S=b>0?Ct(w,b):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Je-st-nt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>pp,f=this.attachments.length-pp,u=this.attachments[c],p=u?`${u.name??"image"} \xB7 ${kn(u.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{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($T(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-Je-st-nt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,f=this.queuedTexts[d],u=d===e-1&&this.queuedTexts.length>up,p=this.queuedTexts.length-up,h=f===void 0?"":u?`+ ${p+1} more queued`:Ct(NT(f),n-4),m=!u&&d===c,y=f===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":u?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${h}`,b=w+" ".repeat(Math.max(0,n-1-w.length));m?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.compactionPrompt){this.drawCompactionPrompt();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=ls(s.buffer,n),i=Fs(r,s,lp),o=this.term.height-i.rendered-nt-st-Je+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,f="wrap",u="";d&&(d.bufferIdx===0&&d.startCol===0?f="first":d.startCol===0&&(f="newline"),u=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(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-hp-nt-st-Je+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${Ct(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${Ct(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-nt-st-Je+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${Ct(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,f=` ${d?"\u276F":" "} ${a+1}. ${Ct(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(f):this.term.dim(f)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-nt-st-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${Ct(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,f=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${Ct(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${Ct(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(vT,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-nt-st-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${Ct(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(` ${Ct(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,u=` ${l?"\u276F":" "} ${c+1}. ${Ct(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.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")})}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}bannerHitAt(e,n){let s=this.bannerHits;if(!s||n!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-nt-st-Je;this.drawSeparator(s),this.drawBottomSeparator(e-Je)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-nt-st-Je+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-nt-st-Je;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-nt-st-Je+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-nt-st-Je;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-hp-nt-st-Je+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-nt-st-Je+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-nt-st-Je;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-nt-st-Je+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=ls(s.buffer,n),i=Fs(r,s,lp),a=this.term.height-i.rendered-nt-st-Je+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-nt-st-Je;this.term.moveTo(Math.min(c,this.term.width),Math.min(a,d))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return hp;if(this.compactionPrompt)return this.compactionRows();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=ls(s.buffer,n);return Math.min(lp,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(wT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(bT,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-nt-st-Je+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${Ct(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 l=e.options[d];if(!l)continue;let f=d===e.selectedIndex,p=` ${f?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${Ct(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${f?"1":"0"}|${l.value}|${l.label}`,()=>{f?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${n}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-nt-st-Je,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let f=this.wrapBtwTail(n,c);for(let u=0;u<c;u++){let p=d+1+u,h=f.length-c+u,m=h>=0?f[h]:void 0,y=Hb(`btw|c${u}`,n,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let f of this.lines)s(f)||d.push(f);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.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 d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),i+=f.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let h=this.wrapCache.get(s);if(h)return h}let r=e.prefix??"",i=yr(r),o=Math.max(1,n-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),c=Math.max(1,o-a),d=Ja(e.bodyStyle),l=e.ansi?TT(e.body,a>0?c:o):FT(e.body,a>0?c:o,{stripMarkup:d}),f=[],u=0,p=0;for(let h=0;h<l.length;h++){let m=l[h]??"",y=h===0||a===0?m:" ".repeat(a)+m,w={prefix:h===0?e.prefix:" ".repeat(i),body:y};if(e.prefixStyle!==void 0&&(w.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(w.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(w.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(w.hoverSubKey=e.hoverSubKey),e.fillRow&&(w.fillRow=!0),e.ansi&&(w.ansi=!0),h===0&&e.iterm2Image&&(w.iterm2Image=e.iterm2Image),s!==void 0&&m.length>0)if(e.ansi){let b=u,S=0;for(let P=0;P<m.length;){let B=Dn(m,P);if(B){P+=B.text.length,B.width>0&&(S+=1);continue}S+=1,P+=1}let k=S;for(;k>0&&u<e.body.length;){let P=Dn(e.body,u);if(P){u+=P.text.length,P.width>0&&(k-=1);continue}u+=1,k-=1}let A=u;if(h===l.length-1){for(;A<e.body.length;){let P=Dn(e.body,A);if(!P)break;A+=P.text.length}u=A}let E={sourceLineId:s,sourceColOffset:b,sourceColEnd:A};h>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(w,E)}else{let b=e.body.indexOf(m,p),S=b===-1?p:b,k={sourceLineId:s,sourceColOffset:S};h>0&&a>0&&(k.bodyDisplayShift=a),this.wrapOrigin.set(w,k),p=S+m.length}f.push(w)}return s!==void 0&&this.wrapCache.set(s,f),f}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&$s(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-yr(e.prefix??"")),c=Ja(e.bodyStyle),d=e.ansi?e.body:Ct(e.body,a,{stripMarkup:c}),l=(f,u)=>{if(f.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=u?s-u:null;Ub(this.term,f,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else $s(this.term,f,e.bodyStyle,o)};if(i!==null){let f=Math.max(0,Math.min(d.length,i.start)),u=Math.max(f,Math.min(d.length,i.end)),p=Ja(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,f),0),u>f){let m=d.slice(f,u);p&&(m=jb(m)),$s(this.term,m,"selection-highlight",o)}let h=d.slice(u);if(p&&u>f){let m=_T(d.slice(0,u));m.length>0&&(h=m+h)}l(h,u)}else this.scrollbackHighlight!==null&&!e.ansi?Ub(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):$s(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let f=e.ansi?Ye(d):yr(d),u=a-f;if(u>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;$s(this.term," ".repeat(u),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Yb=/[^\x20-\x7e]/,wp=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Vb=!1;ET=/[a-zA-Z+\-:_!#/]/;fl=pt});function DT(t,e,n=gl){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 ev(t,e){Bn();let n=pt(e.sessionId),s=e.importedFromMachine??"another machine",r=dt(e.cwd),i=gl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+gl.length*2+2,d=Nn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(d.contentX,d.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(Xe(p.value,l-p.label.length-2)),u++;return u++,tv(t,d,u,{intro:"What do you want to do?",choices:gl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return ds({term:t,render:o,onKey:(a,c,d,l)=>{let f=HT(a,d);if(!f)return;let u=DT(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function tv(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(La(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function HT(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 nv(t,e,n){let s=pt(e.sessionId),r=e.title??dt(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 c=Nn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Xe(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+Xe(r,d-2)),l++,l++,tv(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},f=p=>{l(),n.pop(),c(p)},u=(p,h,m)=>{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(m?.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,h,m)=>{d||u(p,h,m)},onResize:()=>{d||a()}})})}var gl,Sp=V(()=>{"use strict";we();es();ri();gl=[{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 Va(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 sv(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]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Va(e);return o.length<=r.length?null:o+i}var yl=V(()=>{"use strict"});var Bo,kp=V(()=>{"use strict";Bo=class{buffer;cur;killBuf="";undoStack=[];redoStack=[];constructor(e=""){this.buffer=e,this.cur=e.length}get text(){return this.buffer}get cursor(){return this.cur}setText(e,n={}){n.recordUndo&&this.recordEdit(),this.buffer=e,this.cur=e.length}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}snap(){return{text:this.buffer,cursor:this.cur}}restore(e){this.buffer=e.text,this.cur=e.cursor}recordEdit(){this.undoStack.push(this.snap()),this.undoStack.length>500&&this.undoStack.shift(),this.redoStack=[]}undo(){let e=this.undoStack.pop();return e===void 0?!1:(this.redoStack.push(this.snap()),this.restore(e),!0)}redo(){let e=this.redoStack.pop();return e===void 0?!1:(this.undoStack.push(this.snap()),this.restore(e),!0)}moveLeft(){this.cur>0&&(this.cur-=1)}moveRight(){this.cur<this.buffer.length&&(this.cur+=1)}moveHome(){this.cur=0}moveEnd(){this.cur=this.buffer.length}moveWordBackward(){let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;this.cur=e}moveWordForward(){let e=this.buffer.length,n=this.cur;for(;n<e&&/\s/.test(this.buffer[n]??"");)n+=1;for(;n<e&&!/\s/.test(this.buffer[n]??"");)n+=1;this.cur=n}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,n){if(n)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as rv from"os";async function di(t,e,n={}){let s=n.defaultCwd??(e?await gb(e.cwd):void 0)??rv.homedir();Bn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:pt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:dt(e.cwd)}]:[],a=new Bo(s),c=null,d=!1,l=null,f=null,u=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),b=h.indexOf(y),S=()=>{let _=o.length+6;l=Nn(t,{contentHeight:_,title:r,overlay:n.overlay===!0});let D=l.contentW,N=0;for(let K of o)t.moveTo(l.contentX,l.contentY+N),t.dim.noFormat(` ${K.label}`),t.noFormat(Xe(K.value,D-K.label.length-2)),N++;N++,t.moveTo(l.contentX,l.contentY+N),t.noFormat(` ${i}`),N+=2,E(N),N+=2;let L=l.contentY+N;c!==null?(t.moveTo(l.contentX,L),t.red.noFormat(` ${Xe(c,D-2)}`),f=null,u=null,p=null):(t.moveTo(l.contentX,L),t.dim.noFormat(h),f=L,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},k=()=>o.length+3,A=0,E=_=>{if(!l)return;let D=_??k();t.moveTo(l.contentX,l.contentY+D).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+D),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+D),t.noFormat(" ");let L=Math.max(1,l.contentW-1-2),K=a.text,X=a.cursor;X<A&&(A=X),X-A>=L&&(A=X-L+1),A<0&&(A=0);let Z=K.slice(A,A+L);A>0&&Z.length>0&&(Z="\u2026"+Z.slice(1));let Q=X-A;if(d){t.noFormat(Z);return}Q>=Z.length?(t.noFormat(Z),t.bgWhite(" ")):(t.noFormat(Z.slice(0,Q)),t.bgWhite.noFormat(Z[Q]??" "),t.noFormat(Z.slice(Q+1)))},P=()=>{if(E(),!l)return;let _=k()+2;t.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+_),t.dim.noFormat("\u2502");let D=l.contentY+_;t.moveTo(l.contentX,D),c!==null?(t.red.noFormat(` ${Xe(c,l.contentW-2)}`),f=null,u=null,p=null):(t.dim.noFormat(h),f=D,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},B=_=>{if(d)return;let D=a.text;d=!0,c=null,P(),Ua(D).then(N=>{if(d=!1,N.ok){_({kind:"ok",path:N.path});return}c=N.reason,P()})};return ds({term:t,render:S,overlay:n.overlay===!0,onKey:(_,D,N,L)=>{if(!d){if(_==="ENTER"||_==="KP_ENTER"){B(L);return}if(_==="ESCAPE"){L({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){L({kind:"cancel"});return}if(_==="TAB"){d=!0,yb(a.text).then(K=>{if(d=!1,K.matches.length===0)return;let X;if(K.matches.length===1)X=K.prefix+K.matches[0];else{let Z=Va(K.matches);if(Z.length<=K.basePrefix.length)return;X=K.prefix+Z}X!==a.text&&(a.setText(X,{recordUndo:!0}),c=null,P())});return}if(a.handleKey(_,N?.isCharacter===!0)){c=null,P();return}}},onMouse:(_,D,N)=>{if(d||_!=="MOUSE_LEFT_BUTTON_PRESSED")return;let L=D?.x,K=D?.y;if(!(typeof L!="number"||typeof K!="number")){if(l!==null&&(L<l.x||L>=l.x+l.w||K<l.y||K>=l.y+l.h)){N({kind:"back"});return}if(f!==null&&K===f){if(u!==null&&L>=u.start&&L<=u.end){B(N);return}if(p!==null&&L>=p.start&&L<=p.end){N({kind:"back"});return}}}}})}var Ip=V(()=>{"use strict";we();es();Vf();yl();ri();kp()});import*as ov from"fs";import*as av from"os";import*as wl from"path";function bl(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 UT(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function jT(t){return t.replace(/\\ /g," ")}function iv(t){return t.replace(/ /g,"\\ ")}function qT(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function WT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=av.homedir()+n.slice(1)),wl.isAbsolute(n)?n:wl.resolve(e,n)}function zT(t){let e;try{e=ov.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function vl(t,e,n=zT){let s=jT(t),{dirPrefix:r,base:i}=qT(s);if(r.length===0&&!UT(t)&&i.length===0)return null;let o=WT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(u=>u.name.startsWith(i)&&(c||!u.name.startsWith(".")));if(d.length===0)return null;let l=d.map(u=>u.isDir?u.name+"/":u.name);if(d.length===1){let u=d[0],p=u.isDir?u.name+"/":u.name;return{replacement:iv(r+p),candidates:l}}let f=Va(d.map(u=>u.name));return{replacement:iv(r+f),candidates:l}}var xp=V(()=>{"use strict";yl()});function KT(t){process.stdout.write(`\x1B]9;4;${t}\x1B\\`)}function JT(t,e,n){let s=`${n.agentId}@${n.version}`;if(n.source==="npm")return n.phase==="install_start"||n.phase==="download_start"?`${t} installing ${s} via npm\u2026`:n.phase==="installed"?`${t} ${s} installed`:`${t} installing ${s} via npm\u2026`;if(n.phase==="download_start"||n.phase==="download_progress"){let r=n.receivedBytes??0,i=n.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${t} downloading ${s} ${o}/${a} MB (${c}%)`}return`${t} downloading ${s} ${o} MB`}return n.phase==="download_done"?`${t} downloaded ${s}, verifying\u2026`:n.phase==="extract"?`${t} extracting ${s}\u2026`:n.phase==="installed"?`${t} ${s} installed`:e||t}function Sl(t,e){let n=!1,s="",r=!1,i=t,o=a=>{n||a===3&&r||a===0&&!r||(r=a===3,KT(a))};return{write(a){n||(i=a,s=a,e.write(a))},applyProgress(a){if(n)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=JT(i,s,a);s=d,e.write(d)},finalize(){n||(n=!0,o(0),e.finalize())}}}function dv(t){let e=!1;return{write(n){e||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(n))},finalize(){e||(e=!0,process.stdout.write(`
221
- `))}}}var Ap=V(()=>{"use strict"});function Rp(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Tp(t,e){let n=()=>{process.stdout.write(ti),process.stdout.write(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(To),process.stdout.write(Eo),process.stdout.write(Po),process.stdout.write(ei),process.stdout.write("\x1B>")};n();let s=e.prefs??Rp();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=kl(e.sessions,r),o=T=>{let M=T;return s.filters.cwdOnly&&(M=M.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=XT(M,s.filters.hostFilter),M},a=o(i),c={columns:e.config.tui.sessionColumns??vo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(T=>ko(T,Date.now())),l=Io(d,c),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let T=a.findIndex(M=>M.sessionId===e.currentSessionId);T>=0&&(u=T+1)}let h=!1,m="",y=120,w=!1,b=0,S="normal",k=null,A=!1,E="input",P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,L=null,K=!1,X=null,Z=null,Q=null,fe=null,Me=()=>{if(fe!==null){let T=fe;return{plain:T,render:()=>{t.brightYellow.noFormat(` ${T}`)}}}if(h){let T=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${T} \xB7 ^c clears`,render:()=>{t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" "),t.dim.noFormat(` ${T} \xB7 ^c clears`)}}}return Q!==null?{plain:Q,render:()=>{t.dim.noFormat(` ${Q}`)}}:null},In=!1,De=new _s({history:[]});if(e.initialPrompt&&De.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)De.addAttachment(T);let us=e.config.tui.promptHistoryMaxEntries;la(O.globalTuiHistoryFile()).then(T=>{let M=T.length>us?T.slice(T.length-us):T;De.setHistory(M)}).catch(()=>{});let ke=new Lo(t),G=Ms(t),xe=Jt(t),je=0,Yt="",Os=0,un=[],bt=1,Ls=0,Bs=0,fs=0,li="",No=[],xn=1,ed=0,Do=[],ge=1,Ns=0,td=0,ui=0,fi=()=>{G=Ms(t),xe=Jt(t);let T=Math.max(10,xe-Cp-1);Os=Math.max(10,xe-cv);let M=Math.max(10,xe-8),U=De.state().attachments.length,Y=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",re=Math.max(10,M-Y.length);Yt=GT(r,re)+Y;let ie=De.state();un=ls(ie.buffer,Os);let ve=Fs(un,ie,Qa);bt=ve.rendered,Ls=ve.windowStart,Bs=ve.cursorVisualRow,fs=ve.cursorVisualCol;let Ce=6+bt,et=Math.max(3,G-Ce);je=Math.min(a.length,et),li=ur(So,l,T,c).padEnd(T),No=d.map(mt=>ur(mt,l,T,c).padEnd(T))},pi=()=>{d=a.map(T=>ko(T,Date.now())),l=Io(d,c),f=1+a.length,fi()},Rt=()=>{let T=o(i);h&&m.length>0?a=T.filter(M=>ZT(M,m)):a=T,pi(),h?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An()},ps=T=>{if(T!==void 0){let M=a.findIndex(U=>U.sessionId===T);if(M>=0){u=M+1,An();return}}u=a.length>0?1:0,p=0,An()},An=()=>{if(u===0)return;let T=u-1;T<p?p=T:T>=p+je?p=T-je+1:p+je>a.length&&(p=Math.max(0,a.length-je))},he=()=>Math.max(2,xe-3),Ke=!1,qe=!0,yt=!1,Ds=[],hs=e.composerAgentId,ms=e.composerModel,hi=()=>{let T=hs;if(!T)return"";let M=ms;return M?`${T}\u2022${M}`:T},Hs=null,gs=null,Bt=null,mi=()=>{let T=he(),M=`\u2500 ${Yt} `,U=hi(),Y="";if(U.length>0){let Ve=`\u2500 ${U} `;Ve.length+M.length+1<=T&&(Y=Ve)}let re=Math.max(1,T-M.length-Y.length),ie="\u2500".repeat(re),ve=(u===0||Ke)&&qe;if(Hs=M.length>0?{start:2,end:1+M.length}:null,Y.length>0){let Ve=1+M.length+re+1;gs={start:Ve,end:Ve+Y.length-1}}else gs=null;let Ce=ve?t.brightBlue:t.dim,et=ve?t.brightBlue.bold:t.dim.bold,mt=(Ve,Ks)=>{(Ks?et:Ce).noFormat(Ve)};Ce.noFormat("\u256D"),mt(M,Bt==="cwd"),Ce.noFormat(ie),Y&&mt(Y,Bt==="agent"),Ce.noFormat("\u256E")},Un=()=>{let T=he(),M="\u2500".repeat(T);(u===0||Ke)&&qe?t.brightBlue.noFormat(`\u2570${M}\u256F`):t.dim.noFormat(`\u2570${M}\u256F`)},Ho=()=>{let T=Me();if(T===null)return;let M=Math.max(0,Jt(t)-2);if(T.plain.length>M){let U=T.plain.slice(0,Math.max(0,M-1))+"\u2026";t.dim.noFormat(` ${U}`);return}T.render()},Us=T=>{let M=un[T];return M?(De.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},gi=T=>{let M=he(),U=Us(T),Y=Math.max(0,M-1-U.length),re=" ".repeat(Y);(u===0||Ke)&&qe?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${U}${re}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${U}${re}`),t.dim.noFormat("\u2502"))},Tt=T=>{let M=No[T]??"",U=a[T],Y=U&&U.priority&&U.priority>0?"* ":" ";u===T+1&&!Ke&&qe?t.brightWhite.bgBlue.noFormat(`${Y}${M}`):t.noFormat(`${Y}${M}`)},Vt=()=>{let T=p,M=Math.max(0,a.length-p-je),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Y=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Y})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),T>0&&U.push({kind:"plain",text:`\u2191 ${T} above`}),M>0&&U.push({kind:"plain",text:`\u2193 ${M} below`}),U},jn=()=>{let T=Vt();return T.length===0?"":` ${T.map(M=>M.text).join(" \xB7 ")}`},Re=T=>pt(T),nd=()=>{let T=k?`${k.sessionId}|${k.status}`:"";return["ind",S,T,X?`${X.text}${X.cursor}`:"",Z??"",h?`1|${m}|${a.length}`:"0",jn(),Ai?"h1":"h0",zs?"ho1":"ho0"].join("")},$e=()=>{Oe(()=>{ke.paintRow(Wn(),nd(),()=>{let T=()=>{Jn=null,Zt=null};if(S==="confirm-kill"&&k)T(),t.brightYellow.noFormat(` kill ${Re(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)T(),k.status==="warm"?t.brightRed.noFormat(` kill + delete ${Re(k.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Re(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)T(),t.dim.noFormat(` working on ${Re(k.sessionId)}\u2026`);else if(S==="rename"&&k&&X){T();let M=X.text,U=X.cursor;t.brightYellow.noFormat(" title: "),t.brightYellow.noFormat(M.slice(0,U)),U<M.length?(t.bgBrightYellow.noFormat(M[U]??" "),t.brightYellow.noFormat(M.slice(U+1))):t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(Z!==null)T(),t.dim.noFormat(` ${Z}`);else{let M=Vt(),U=jn(),Y="Esc \xB7 Go Back",re=Y.length,ie=5,ve=U.length,Ce=Math.max(1,xe-ve-re-ie);if(Zt=null,M.length>0){t.dim.noFormat(" ");let et=3;for(let mt=0;mt<M.length;mt++){let Ve=M[mt];mt>0&&(t.dim.noFormat(" \xB7 "),et+=3),Ve.kind==="host"?(Zt={start:et,end:et+Ve.text.length-1},zs?t.noFormat(Ve.text):t.dim.noFormat(Ve.text)):t.dim.noFormat(Ve.text),et+=Ve.text.length}}t.dim(" ".repeat(Ce)),Ai?t.noFormat(Y):t.dim.noFormat(Y),Jn={start:xe-ie-re+1,end:xe-ie}}})})},Et=T=>xn+1+T,qn=()=>xn+bt+1,Qt=()=>xn+bt+3,x=T=>Qt()+1+(T-p),Wn=()=>Qt()+1+je,fn=()=>{let T=Bs-Ls;if(T<0||T>=bt)return;let M=3+fs;t.moveTo(M,Et(T))},js=()=>qe?u===0?"f":Ke?"h":"u":"x",yi=()=>`ct|${js()}|${he()}|${Yt}|${hi()}|${Bt??""}`,Uo=()=>`cb|${js()}|${he()}`,Sr=()=>fe!==null?`cs|i|${fe}`:h?`cs|s|${m}|${a.length}`:Q!==null?`cs|h|${Q}`:"blank",zn=T=>`cbb|${js()}|${he()}|${Us(T)}`,jo=()=>`h|${li}`,wi=T=>{let M=a[T],U=M&&M.priority&&M.priority>0?"* ":" ",Y=No[T]??"";return`sr|${u===T+1&&!Ke&&qe?"1":"0"}|${U}${Y}`},Ze=()=>{Oe(()=>{t.hideCursor(),fi(),An(),xn=1,ke.ensureSize(xe,G),ke.paintRow(xn,yi(),()=>{mi()});for(let T=0;T<bt;T++){let M=Ls+T;ke.paintRow(Et(T),zn(M),()=>{gi(M)})}ke.paintRow(qn(),Uo(),()=>{Un()}),ke.paintRow(qn()+1,Sr(),()=>Ho()),ke.paintRow(Qt(),jo(),()=>{t.dim.noFormat(` ${li}`)});for(let T=0;T<je;T++){let M=p+T,U=Qt()+1+T;M<a.length?ke.paintRow(U,wi(M),()=>{Tt(M)}):ke.paintRow(U,"blank",()=>{})}$e();for(let T=Wn()+1;T<=G;T++)ke.paintRow(T,"blank",()=>{});u===0&&(fn(),t.hideCursor(!1))})},qo=()=>{ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ze()},ys=()=>{Oe(()=>{t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
217
+ `);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=Yb(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=Yb(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=Ro,s=_a;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,`
218
+ `);this.pasteBuffer="";let a=Rb(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=ET(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)),c=n.length-s.count,d=this.lines.slice(s.start,o),l=new Array(n.length),f=[];for(let u=0;u<n.length;u++){let p=d[u],h=n[u];p!==void 0&&_T(p,h)?l[u]=p:(p!==void 0&&f.push(p),l[u]=h)}for(let u=n.length;u<d.length;u++)f.push(d[u]);this.lines.splice(s.start,s.count,...l);for(let u of f)this.forgetLine(u);for(let u of l)this.lineIds.has(u)||this.trackLine(u);if(this.invalidateSelectionIfTouches(f),s.count=n.length,c!==0)for(let[u,p]of this.keyedBlocks)u!==e&&p.start>s.start&&(p.start+=c);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(`
219
+ `),[o,...a]=i,c=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??"",c+=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),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let f={prefix:d,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),c+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(c),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=fl(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&&Le(()=>{this.term.hideCursor(),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())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,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)),oe({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),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 c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,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}}}farEndpointFrom(e){if(this.selection===null)return null;let n=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.startLineId),i=this.lineIndexById(n.endLineId);if(s<0||r<0||i<0)return null;let o=(f,u,p,h)=>f!==p?f-p:u-h,a=o(s,e.offset,r,n.startOffset),c=o(s,e.offset,i,n.endOffset);if(a<=0)return{sourceLineId:n.endLineId,offset:n.endOffset};if(c>=0)return{sourceLineId:n.startLineId,offset:n.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-n.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-n.endOffset)>=d?{sourceLineId:n.endLineId,offset:n.endOffset}:{sourceLineId:n.startLineId,offset:n.startOffset}}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 c=(r.body??"").slice(o.start,o.end);(Ja(r.bodyStyle)||r.ansi)&&(c=qb(c)),n.push(c)}return n.join(`
220
+ `)}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 c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=d===r?Math.max(0,Math.min(u,o)):0,h=d===i?Math.max(0,Math.min(u,a)):u;c.set(f,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null)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=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,c=Math.max(r.start,i),d=Math.min(r.end,a);if(d<=c)return null;let l,f;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let p=yp(u,i,c),h=yp(u,c,d);l=wp(e.body,o,p),f=wp(e.body,l,h)}else l=c-i+o,f=d-i+o;return{start:l,end:f,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let n=this.lineIndexById(e);return n===-1?null:this.lines[n]?.body??null}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"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}: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,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.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(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=c&&f.start<d)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(c=>c.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 c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(Uf),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()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=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.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&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.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}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(process.env.HYDRA_TUI_KEY_TRACE&&oe({tag:"key",name:e,isChar:!!n.isCharacter}),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=ml(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 r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=MT(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(l===null&&c==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let f=this.nearestKeyAboveRow(o.y),u=this.nearestKeyBelowRow(o.y);f!==null&&u!==null&&this.hoveredRunKeys.has(f)&&this.hoveredRunKeys.has(u)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let f=l?.key??null,u=l?.sub??null;(f!==this.hoveredBlockKey||u!==this.hoveredSubKey)&&(this.hoveredBlockKey=f,this.hoveredSubKey=u,this.hoveredRunKeys=f!==null&&this.onHoverRun?this.onHoverRun(f)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback()));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=ll&&Math.abs(o.y-d.y)<=ll&&Date.now()-d.t<=dp||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,PT(n,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let f=this.btwHeaderSidRegion();if(f!==null&&this.onHydraLinkClick&&o.y===f.row&&o.x>=f.colStart&&o.x<=f.colEnd)this.onHydraLinkClick(f.sessionId);else if(this.onBlockClick){let u=this.keyAtRow(o.y);if(u!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===u;)p-=1;this.schedulePendingBlockClick(u,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(n&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=dp&&Math.abs(e.x-i.x)<=ll&&Math.abs(e.y-i.y)<=ll&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let f=e.y;for(;f>1&&this.keyAtRow(f-1)===l;)f-=1;let u=e.y-f;if(this.onBlockDoubleClick(l,u)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&Hb.test(l)){let u=l.match(Hb)?.[1]??null;if(u&&this.onHydraLinkClick(u)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let n=this.lineById(e);if(n===null)return;let s=(n.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let n=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=n&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let n=this.scrollbackVisibleRows();if(n<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,n+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-n),a=r.slice(o,i),c=Math.max(0,n-a.length),d=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=d<c;if(d===0&&l||u){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(d>=n-1&&f){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,n){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=this.term.width,i=Math.max(1,Math.min(r,e));for(let o=1;o<s;o++){let a=n-o;if(a>=1){let d=this.resolveCellToSource(i,a);if(d!==null){let l=this.lineById(d.sourceLineId);return l?{sourceLineId:d.sourceLineId,offset:(l.body??"").length}:d}}let c=n+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let n=this.farEndpointFrom(e);return n===null?!1:(this.selectionAnchor=n,this.selectionDragStarted=!0,this.setSelection(n,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,n){if(this.autoscrollTimer!==null&&this.autoscrollDir===n){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=n,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},t.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=gp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!ul.test(r[a])&&!lp.test(r[a]))return null;let c=a;for(;c>0&&lp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&lp.test(r[d]);)d++;for(;d>c+1&&vT.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!ul.test(r[a]))return null;let f=a;for(;f>0&&ul.test(r[f-1]);)f--;let u=a+1;for(;u<r.length&&ul.test(r[u]);)u++;return this.projectCleanRangeToRaw(i,s.length,f,u)}projectCleanRangeToRaw(e,n,s,r){let i=n,o=n;for(let a=0;a<e.length;a++)if(e[a]===s&&i===n&&(i=a),e[a]===r&&o===n){o=a;break}return{start:i,end:o}}pathTokenAt(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{clean:r,rawToClean:i}=gp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!cp.test(r[a]))return null;let c=a;for(;c>0&&cp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&cp.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=r.slice(d).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi||!n.links)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=gp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of n.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Nb():`${Nb()}/${n.slice(2)}`);let s=Db(n)||e.startsWith("~"),r=Db(n)?n:wT(this.sessionbar.cwd,n);if(s)return r;try{if(Bb(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.raw;if(!ST.test(s))return!1;let r=s.startsWith(jt)?[s]:[jt+s,s],i=null;for(let o of r)try{if(Bb(O.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let f of c)f.includes("%f")&&(d=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let f=yT(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},dp);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset))}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&&Mb(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}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?$w:Yc))}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,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),f=i-l;return f<0||f>=d.length?null:d[f]?.blockKey??null}nearestKeyAboveRow(e){for(let n=e-1;n>=1;n--){let s=this.keyAtRow(n);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(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,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),f=i-l;if(f<0||f>=d.length)return null;let u=d[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}: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),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),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 h=this.wrapOrigin.get(p);if(!h)return null;let m=wr(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=Ja(p.bodyStyle)||p.ansi===!0?Ob(vp(p.body),b):Fb(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=yp(p.body,y,k),P=wp(A,h.sourceColOffset,E);return{sourceLineId:h.sourceLineId,offset:P}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+k-y}}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=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}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=s.bodyDisplayShift??0,i=n.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}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 h=p.body.length;if(e.col<f+h){o=l.length-1-u;break}f+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Ye-st-nt-kT-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(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),Le(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-nt-st-Ye;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-Ye),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),n=this.term.height,s=this.sessionbar.title?.trim(),r=Py(this.sessionbar.agent,this.sessionbar.model),i=dt(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=Ve(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",f=Ve(l),u,p;if(s){let b=Math.min(s.length,8);u=Math.min(i.length,Math.max(8,d-f-b)),p=Math.max(0,d-u-f)}else p=0,u=d;let h=Ct(i,u),m=s?Ct(s,p):"",y=Ve(h)+(s?f+Ve(m):0),w=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(w)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=fl(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?as(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;c.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;c.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let d=Jb(this.sessionbar.usage)??"",l="\u2500\u2500 ",f=a?` ${a}`:"",u=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Ve(o)+Ve(f)+u.length+Ve(s);for(let A of c)y+=Ve(" \xB7 ")+Ve(A.text);y+=Ve(p);let w=Ve(h)+Ve(d)+Ve(m),b=Math.max(0,n-y-w),S="\u2500".repeat(b),k=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),f&&(i?this.term.brightRed.noFormat(f):r==="busy"?this.term.brightYellow.noFormat(f):this.term.dim.noFormat(f)),s&&(this.term.dim(u),this.term.dim(s));for(let A of c)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let n=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=Ve(i)+Ve(a)+Ve(o),d=Math.max(0,n-c),l="\u2500".repeat(d),f=s?`${s.kind}|${s.text}`:"",u=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${f}|${u}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.terminalFocused?this.hoveredBannerHit:null;for(let w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let b=m[w];if(b===void 0)continue;let S=null;b.includes("mode")?S="mode":b.includes("pick")?S="pick":b.includes("guide")?S="guide":b.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(b):this.term.dim(b)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Ve(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Ve(w),S=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=S:w.includes("pick")&&h.pick===null?h.pick=S:w.includes("guide")&&h.guide===null?h.guide=S:w.includes("detach")&&h.detach===null&&(h.detach=S),m+=b+Ve(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?fl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Jb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Ve(n)+i.length+Ve(r)+o.length+Ve(c)+d.length,f="\u2500".repeat(Math.max(0,e-l)),u=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:f,usage:c,right:d,signature:u}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-nt-st-Ye,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=fl(this.btwOverlaySessionId),f=1+c.length+Ve(a)+" \xB7 ".length,u=f+Ve(d)-1;return{row:o,colStart:f,colEnd:u,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(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 h=Math.max(0,r.length-s);this.scrollOffset>h&&(this.scrollOffset=h)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let u=-1,p=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let h=0;h<c.length;h++){let m=c[h]?.blockKey;m===void 0||!(m===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m))||(u===-1&&(u=h),p=h)}for(let h=0;h<s;h++){let m=n+h,y=h-d,w=y>=0?c[y]:void 0,b=this.activeMatchCol(w,l),S=w?this.selectionRangeForChunk(w):null,k=w!==void 0&&w.blockKey!==void 0&&(w.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w.blockKey)),A=w!==void 0&&w.blockKey===void 0&&u!==-1&&y>=u&&y<=p,E=k||A,P=this.terminalFocused&&E&&(this.hoveredSubKey===null||(w.hoverSubKey??null)===this.hoveredSubKey),B=Ub("sb",e,w,this.scrollbackHighlight,b,S)+(P?"|H":"");this.paintRow(m,B,()=>{w&&this.writeFormattedLine(w,e,b,f,S,P)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(fp,this.queuedTexts.length)}chipRows(){return Math.min(hp,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(pp,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-Ye-st-nt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let f=c+l,u=this.completions[l],p=l===e-1&&this.completions.length>pp,h=this.completions.length-pp+1,m=u?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,m,()=>{if(!u)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=u.name.padEnd(d),w=u.description??"",b=n-y.length-4,S=b>0?Ct(w,b):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Ye-st-nt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>hp,f=this.attachments.length-hp,u=this.attachments[c],p=u?`${u.name??"image"} \xB7 ${kn(u.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{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(NT(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-Ye-st-nt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,f=this.queuedTexts[d],u=d===e-1&&this.queuedTexts.length>fp,p=this.queuedTexts.length-fp,h=f===void 0?"":u?`+ ${p+1} more queued`:Ct(qT(f),n-4),m=!u&&d===c,y=f===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":u?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${h}`,b=w+" ".repeat(Math.max(0,n-1-w.length));m?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.compactionPrompt){this.drawCompactionPrompt();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=ls(s.buffer,n),i=Fs(r,s,up),o=this.term.height-i.rendered-nt-st-Ye+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,f="wrap",u="";d&&(d.bufferIdx===0&&d.startCol===0?f="first":d.startCol===0&&(f="newline"),u=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(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-mp-nt-st-Ye+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${Ct(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${Ct(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-nt-st-Ye+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${Ct(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,f=` ${d?"\u276F":" "} ${a+1}. ${Ct(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(f):this.term.dim(f)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-nt-st-Ye+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${Ct(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,f=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${Ct(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${Ct(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(AT,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-nt-st-Ye+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${Ct(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(` ${Ct(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,u=` ${l?"\u276F":" "} ${c+1}. ${Ct(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.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")})}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}bannerHitAt(e,n){let s=this.bannerHits;if(!s||n!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-nt-st-Ye;this.drawSeparator(s),this.drawBottomSeparator(e-Ye)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-nt-st-Ye+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-nt-st-Ye;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-nt-st-Ye+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-nt-st-Ye;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-mp-nt-st-Ye+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-nt-st-Ye+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-nt-st-Ye;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-nt-st-Ye+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=ls(s.buffer,n),i=Fs(r,s,up),a=this.term.height-i.rendered-nt-st-Ye+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-nt-st-Ye;this.term.moveTo(Math.min(c,this.term.width),Math.min(a,d))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return mp;if(this.compactionPrompt)return this.compactionRows();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=ls(s.buffer,n);return Math.min(up,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(IT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(xT,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-nt-st-Ye+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${Ct(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 l=e.options[d];if(!l)continue;let f=d===e.selectedIndex,p=` ${f?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${Ct(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${f?"1":"0"}|${l.value}|${l.label}`,()=>{f?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${n}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-nt-st-Ye,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let f=this.wrapBtwTail(n,c);for(let u=0;u<c;u++){let p=d+1+u,h=f.length-c+u,m=h>=0?f[h]:void 0,y=Ub(`btw|c${u}`,n,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let f of this.lines)s(f)||d.push(f);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.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 d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),i+=f.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let h=this.wrapCache.get(s);if(h)return h}let r=e.prefix??"",i=wr(r),o=Math.max(1,n-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),c=Math.max(1,o-a),d=Ja(e.bodyStyle),l=e.ansi?$T(e.body,a>0?c:o):DT(e.body,a>0?c:o,{stripMarkup:d}),f=[],u=0,p=0;for(let h=0;h<l.length;h++){let m=l[h]??"",y=h===0||a===0?m:" ".repeat(a)+m,w={prefix:h===0?e.prefix:" ".repeat(i),body:y};if(e.prefixStyle!==void 0&&(w.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(w.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(w.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(w.hoverSubKey=e.hoverSubKey),e.fillRow&&(w.fillRow=!0),e.ansi&&(w.ansi=!0),h===0&&e.iterm2Image&&(w.iterm2Image=e.iterm2Image),s!==void 0&&m.length>0)if(e.ansi){let b=u,S=0;for(let P=0;P<m.length;){let B=Dn(m,P);if(B){P+=B.text.length,B.width>0&&(S+=1);continue}S+=1,P+=1}let k=S;for(;k>0&&u<e.body.length;){let P=Dn(e.body,u);if(P){u+=P.text.length,P.width>0&&(k-=1);continue}u+=1,k-=1}let A=u;if(h===l.length-1){for(;A<e.body.length;){let P=Dn(e.body,A);if(!P)break;A+=P.text.length}u=A}let E={sourceLineId:s,sourceColOffset:b,sourceColEnd:A};h>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(w,E)}else{let b=e.body.indexOf(m,p),S=b===-1?p:b,k={sourceLineId:s,sourceColOffset:S};h>0&&a>0&&(k.bodyDisplayShift=a),this.wrapOrigin.set(w,k),p=S+m.length}f.push(w)}return s!==void 0&&this.wrapCache.set(s,f),f}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&$s(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-wr(e.prefix??"")),c=Ja(e.bodyStyle),d=e.ansi?e.body:Ct(e.body,a,{stripMarkup:c}),l=(f,u)=>{if(f.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=u?s-u:null;jb(this.term,f,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else $s(this.term,f,e.bodyStyle,o)};if(i!==null){let f=Math.max(0,Math.min(d.length,i.start)),u=Math.max(f,Math.min(d.length,i.end)),p=Ja(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,f),0),u>f){let m=d.slice(f,u);p&&(m=qb(m)),$s(this.term,m,"selection-highlight",o)}let h=d.slice(u);if(p&&u>f){let m=BT(d.slice(0,u));m.length>0&&(h=m+h)}l(h,u)}else this.scrollbackHighlight!==null&&!e.ansi?jb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):$s(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let f=e.ansi?Ve(d):wr(d),u=a-f;if(u>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;$s(this.term," ".repeat(u),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Vb=/[^\x20-\x7e]/,bp=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Qb=!1;FT=/[a-zA-Z+\-:_!#/]/;fl=pt});function WT(t,e,n=gl){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 tv(t,e){Bn();let n=pt(e.sessionId),s=e.importedFromMachine??"another machine",r=dt(e.cwd),i=gl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+gl.length*2+2,d=Nn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(d.contentX,d.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(Xe(p.value,l-p.label.length-2)),u++;return u++,nv(t,d,u,{intro:"What do you want to do?",choices:gl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return ds({term:t,render:o,onKey:(a,c,d,l)=>{let f=zT(a,d);if(!f)return;let u=WT(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function nv(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(La(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function zT(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 sv(t,e,n){let s=pt(e.sessionId),r=e.title??dt(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 c=Nn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Xe(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+Xe(r,d-2)),l++,l++,nv(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},f=p=>{l(),n.pop(),c(p)},u=(p,h,m)=>{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(m?.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,h,m)=>{d||u(p,h,m)},onResize:()=>{d||a()}})})}var gl,kp=V(()=>{"use strict";we();es();ri();gl=[{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 Va(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 rv(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]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Va(e);return o.length<=r.length?null:o+i}var yl=V(()=>{"use strict"});var Bo,Ip=V(()=>{"use strict";Bo=class{buffer;cur;killBuf="";undoStack=[];redoStack=[];constructor(e=""){this.buffer=e,this.cur=e.length}get text(){return this.buffer}get cursor(){return this.cur}setText(e,n={}){n.recordUndo&&this.recordEdit(),this.buffer=e,this.cur=e.length}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}snap(){return{text:this.buffer,cursor:this.cur}}restore(e){this.buffer=e.text,this.cur=e.cursor}recordEdit(){this.undoStack.push(this.snap()),this.undoStack.length>500&&this.undoStack.shift(),this.redoStack=[]}undo(){let e=this.undoStack.pop();return e===void 0?!1:(this.redoStack.push(this.snap()),this.restore(e),!0)}redo(){let e=this.redoStack.pop();return e===void 0?!1:(this.undoStack.push(this.snap()),this.restore(e),!0)}moveLeft(){this.cur>0&&(this.cur-=1)}moveRight(){this.cur<this.buffer.length&&(this.cur+=1)}moveHome(){this.cur=0}moveEnd(){this.cur=this.buffer.length}moveWordBackward(){let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;this.cur=e}moveWordForward(){let e=this.buffer.length,n=this.cur;for(;n<e&&/\s/.test(this.buffer[n]??"");)n+=1;for(;n<e&&!/\s/.test(this.buffer[n]??"");)n+=1;this.cur=n}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,n){if(n)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as iv from"os";async function di(t,e,n={}){let s=n.defaultCwd??(e?await yb(e.cwd):void 0)??iv.homedir();Bn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:pt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:dt(e.cwd)}]:[],a=new Bo(s),c=null,d=!1,l=null,f=null,u=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),b=h.indexOf(y),S=()=>{let _=o.length+6;l=Nn(t,{contentHeight:_,title:r,overlay:n.overlay===!0});let D=l.contentW,N=0;for(let K of o)t.moveTo(l.contentX,l.contentY+N),t.dim.noFormat(` ${K.label}`),t.noFormat(Xe(K.value,D-K.label.length-2)),N++;N++,t.moveTo(l.contentX,l.contentY+N),t.noFormat(` ${i}`),N+=2,E(N),N+=2;let L=l.contentY+N;c!==null?(t.moveTo(l.contentX,L),t.red.noFormat(` ${Xe(c,D-2)}`),f=null,u=null,p=null):(t.moveTo(l.contentX,L),t.dim.noFormat(h),f=L,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},k=()=>o.length+3,A=0,E=_=>{if(!l)return;let D=_??k();t.moveTo(l.contentX,l.contentY+D).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+D),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+D),t.noFormat(" ");let L=Math.max(1,l.contentW-1-2),K=a.text,X=a.cursor;X<A&&(A=X),X-A>=L&&(A=X-L+1),A<0&&(A=0);let Z=K.slice(A,A+L);A>0&&Z.length>0&&(Z="\u2026"+Z.slice(1));let Q=X-A;if(d){t.noFormat(Z);return}Q>=Z.length?(t.noFormat(Z),t.bgWhite(" ")):(t.noFormat(Z.slice(0,Q)),t.bgWhite.noFormat(Z[Q]??" "),t.noFormat(Z.slice(Q+1)))},P=()=>{if(E(),!l)return;let _=k()+2;t.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+_),t.dim.noFormat("\u2502");let D=l.contentY+_;t.moveTo(l.contentX,D),c!==null?(t.red.noFormat(` ${Xe(c,l.contentW-2)}`),f=null,u=null,p=null):(t.dim.noFormat(h),f=D,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},B=_=>{if(d)return;let D=a.text;d=!0,c=null,P(),Ua(D).then(N=>{if(d=!1,N.ok){_({kind:"ok",path:N.path});return}c=N.reason,P()})};return ds({term:t,render:S,overlay:n.overlay===!0,onKey:(_,D,N,L)=>{if(!d){if(_==="ENTER"||_==="KP_ENTER"){B(L);return}if(_==="ESCAPE"){L({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){L({kind:"cancel"});return}if(_==="TAB"){d=!0,wb(a.text).then(K=>{if(d=!1,K.matches.length===0)return;let X;if(K.matches.length===1)X=K.prefix+K.matches[0];else{let Z=Va(K.matches);if(Z.length<=K.basePrefix.length)return;X=K.prefix+Z}X!==a.text&&(a.setText(X,{recordUndo:!0}),c=null,P())});return}if(a.handleKey(_,N?.isCharacter===!0)){c=null,P();return}}},onMouse:(_,D,N)=>{if(d||_!=="MOUSE_LEFT_BUTTON_PRESSED")return;let L=D?.x,K=D?.y;if(!(typeof L!="number"||typeof K!="number")){if(l!==null&&(L<l.x||L>=l.x+l.w||K<l.y||K>=l.y+l.h)){N({kind:"back"});return}if(f!==null&&K===f){if(u!==null&&L>=u.start&&L<=u.end){B(N);return}if(p!==null&&L>=p.start&&L<=p.end){N({kind:"back"});return}}}}})}var xp=V(()=>{"use strict";we();es();Qf();yl();ri();Ip()});import*as av from"fs";import*as dv from"os";import*as wl from"path";function bl(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 KT(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function JT(t){return t.replace(/\\ /g," ")}function ov(t){return t.replace(/ /g,"\\ ")}function YT(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function VT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=dv.homedir()+n.slice(1)),wl.isAbsolute(n)?n:wl.resolve(e,n)}function QT(t){let e;try{e=av.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function vl(t,e,n=QT){let s=JT(t),{dirPrefix:r,base:i}=YT(s);if(r.length===0&&!KT(t)&&i.length===0)return null;let o=VT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(u=>u.name.startsWith(i)&&(c||!u.name.startsWith(".")));if(d.length===0)return null;let l=d.map(u=>u.isDir?u.name+"/":u.name);if(d.length===1){let u=d[0],p=u.isDir?u.name+"/":u.name;return{replacement:ov(r+p),candidates:l}}let f=Va(d.map(u=>u.name));return{replacement:ov(r+f),candidates:l}}var Ap=V(()=>{"use strict";yl()});function GT(t){process.stdout.write(`\x1B]9;4;${t}\x1B\\`)}function XT(t,e,n){let s=`${n.agentId}@${n.version}`;if(n.source==="npm")return n.phase==="install_start"||n.phase==="download_start"?`${t} installing ${s} via npm\u2026`:n.phase==="installed"?`${t} ${s} installed`:`${t} installing ${s} via npm\u2026`;if(n.phase==="download_start"||n.phase==="download_progress"){let r=n.receivedBytes??0,i=n.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${t} downloading ${s} ${o}/${a} MB (${c}%)`}return`${t} downloading ${s} ${o} MB`}return n.phase==="download_done"?`${t} downloaded ${s}, verifying\u2026`:n.phase==="extract"?`${t} extracting ${s}\u2026`:n.phase==="installed"?`${t} ${s} installed`:e||t}function Sl(t,e){let n=!1,s="",r=!1,i=t,o=a=>{n||a===3&&r||a===0&&!r||(r=a===3,GT(a))};return{write(a){n||(i=a,s=a,e.write(a))},applyProgress(a){if(n)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=XT(i,s,a);s=d,e.write(d)},finalize(){n||(n=!0,o(0),e.finalize())}}}function cv(t){let e=!1;return{write(n){e||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(n))},finalize(){e||(e=!0,process.stdout.write(`
221
+ `))}}}var Cp=V(()=>{"use strict"});function Tp(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Ep(t,e){let n=()=>{process.stdout.write(ti),process.stdout.write(Ps),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(To),process.stdout.write(Eo),process.stdout.write(Po),process.stdout.write(ei),process.stdout.write("\x1B>")};n();let s=e.prefs??Tp();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=kl(e.sessions,r),o=T=>{let M=T;return s.filters.cwdOnly&&(M=M.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=sE(M,s.filters.hostFilter),M},a=o(i),c={columns:e.config.tui.sessionColumns??vo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(T=>ko(T,Date.now())),l=Io(d,c),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let T=a.findIndex(M=>M.sessionId===e.currentSessionId);T>=0&&(u=T+1)}let h=!1,m="",y=120,w=!1,b=0,S="normal",k=null,A=!1,E="input",P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,L=null,K=!1,X=null,Z=null,Q=null,fe=null,Me=()=>{if(fe!==null){let T=fe;return{plain:T,render:()=>{t.brightYellow.noFormat(` ${T}`)}}}if(h){let T=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${T} \xB7 ^c clears`,render:()=>{t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" "),t.dim.noFormat(` ${T} \xB7 ^c clears`)}}}return Q!==null?{plain:Q,render:()=>{t.dim.noFormat(` ${Q}`)}}:null},In=!1,He=new _s({history:[]});if(e.initialPrompt&&He.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)He.addAttachment(T);let us=e.config.tui.promptHistoryMaxEntries;la(O.globalTuiHistoryFile()).then(T=>{let M=T.length>us?T.slice(T.length-us):T;He.setHistory(M)}).catch(()=>{});let ke=new Lo(t),G=Ms(t),xe=Jt(t),qe=0,Yt="",Ls=0,un=[],bt=1,Bs=0,Ns=0,fs=0,li="",No=[],xn=1,ed=0,Do=[],ge=1,Ds=0,td=0,ui=0,fi=()=>{G=Ms(t),xe=Jt(t);let T=Math.max(10,xe-Rp-1);Ls=Math.max(10,xe-lv);let M=Math.max(10,xe-8),U=He.state().attachments.length,Y=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",re=Math.max(10,M-Y.length);Yt=nE(r,re)+Y;let ie=He.state();un=ls(ie.buffer,Ls);let ve=Fs(un,ie,Qa);bt=ve.rendered,Bs=ve.windowStart,Ns=ve.cursorVisualRow,fs=ve.cursorVisualCol;let Ce=6+bt,et=Math.max(3,G-Ce);qe=Math.min(a.length,et),li=fr(So,l,T,c).padEnd(T),No=d.map(mt=>fr(mt,l,T,c).padEnd(T))},pi=()=>{d=a.map(T=>ko(T,Date.now())),l=Io(d,c),f=1+a.length,fi()},Rt=()=>{let T=o(i);h&&m.length>0?a=T.filter(M=>rE(M,m)):a=T,pi(),h?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+qe>a.length&&(p=Math.max(0,a.length-qe)),An()},ps=T=>{if(T!==void 0){let M=a.findIndex(U=>U.sessionId===T);if(M>=0){u=M+1,An();return}}u=a.length>0?1:0,p=0,An()},An=()=>{if(u===0)return;let T=u-1;T<p?p=T:T>=p+qe?p=T-qe+1:p+qe>a.length&&(p=Math.max(0,a.length-qe))},he=()=>Math.max(2,xe-3),Je=!1,We=!0,yt=!1,Hs=[],hs=e.composerAgentId,ms=e.composerModel,hi=()=>{let T=hs;if(!T)return"";let M=ms;return M?`${T}\u2022${M}`:T},Us=null,gs=null,Bt=null,mi=()=>{let T=he(),M=`\u2500 ${Yt} `,U=hi(),Y="";if(U.length>0){let Qe=`\u2500 ${U} `;Qe.length+M.length+1<=T&&(Y=Qe)}let re=Math.max(1,T-M.length-Y.length),ie="\u2500".repeat(re),ve=(u===0||Je)&&We;if(Us=M.length>0?{start:2,end:1+M.length}:null,Y.length>0){let Qe=1+M.length+re+1;gs={start:Qe,end:Qe+Y.length-1}}else gs=null;let Ce=ve?t.brightBlue:t.dim,et=ve?t.brightBlue.bold:t.dim.bold,mt=(Qe,Js)=>{(Js?et:Ce).noFormat(Qe)};Ce.noFormat("\u256D"),mt(M,Bt==="cwd"),Ce.noFormat(ie),Y&&mt(Y,Bt==="agent"),Ce.noFormat("\u256E")},Un=()=>{let T=he(),M="\u2500".repeat(T);(u===0||Je)&&We?t.brightBlue.noFormat(`\u2570${M}\u256F`):t.dim.noFormat(`\u2570${M}\u256F`)},Ho=()=>{let T=Me();if(T===null)return;let M=Math.max(0,Jt(t)-2);if(T.plain.length>M){let U=T.plain.slice(0,Math.max(0,M-1))+"\u2026";t.dim.noFormat(` ${U}`);return}T.render()},js=T=>{let M=un[T];return M?(He.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},gi=T=>{let M=he(),U=js(T),Y=Math.max(0,M-1-U.length),re=" ".repeat(Y);(u===0||Je)&&We?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${U}${re}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${U}${re}`),t.dim.noFormat("\u2502"))},Tt=T=>{let M=No[T]??"",U=a[T],Y=U&&U.priority&&U.priority>0?"* ":" ";u===T+1&&!Je&&We?t.brightWhite.bgBlue.noFormat(`${Y}${M}`):t.noFormat(`${Y}${M}`)},Vt=()=>{let T=p,M=Math.max(0,a.length-p-qe),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Y=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Y})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),T>0&&U.push({kind:"plain",text:`\u2191 ${T} above`}),M>0&&U.push({kind:"plain",text:`\u2193 ${M} below`}),U},jn=()=>{let T=Vt();return T.length===0?"":` ${T.map(M=>M.text).join(" \xB7 ")}`},Re=T=>pt(T),nd=()=>{let T=k?`${k.sessionId}|${k.status}`:"";return["ind",S,T,X?`${X.text}${X.cursor}`:"",Z??"",h?`1|${m}|${a.length}`:"0",jn(),Ai?"h1":"h0",Ks?"ho1":"ho0"].join("")},$e=()=>{Le(()=>{ke.paintRow(Wn(),nd(),()=>{let T=()=>{Jn=null,Zt=null};if(S==="confirm-kill"&&k)T(),t.brightYellow.noFormat(` kill ${Re(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)T(),k.status==="warm"?t.brightRed.noFormat(` kill + delete ${Re(k.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Re(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)T(),t.dim.noFormat(` working on ${Re(k.sessionId)}\u2026`);else if(S==="rename"&&k&&X){T();let M=X.text,U=X.cursor;t.brightYellow.noFormat(" title: "),t.brightYellow.noFormat(M.slice(0,U)),U<M.length?(t.bgBrightYellow.noFormat(M[U]??" "),t.brightYellow.noFormat(M.slice(U+1))):t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(Z!==null)T(),t.dim.noFormat(` ${Z}`);else{let M=Vt(),U=jn(),Y="Esc \xB7 Go Back",re=Y.length,ie=5,ve=U.length,Ce=Math.max(1,xe-ve-re-ie);if(Zt=null,M.length>0){t.dim.noFormat(" ");let et=3;for(let mt=0;mt<M.length;mt++){let Qe=M[mt];mt>0&&(t.dim.noFormat(" \xB7 "),et+=3),Qe.kind==="host"?(Zt={start:et,end:et+Qe.text.length-1},Ks?t.noFormat(Qe.text):t.dim.noFormat(Qe.text)):t.dim.noFormat(Qe.text),et+=Qe.text.length}}t.dim(" ".repeat(Ce)),Ai?t.noFormat(Y):t.dim.noFormat(Y),Jn={start:xe-ie-re+1,end:xe-ie}}})})},Et=T=>xn+1+T,qn=()=>xn+bt+1,Qt=()=>xn+bt+3,x=T=>Qt()+1+(T-p),Wn=()=>Qt()+1+qe,fn=()=>{let T=Ns-Bs;if(T<0||T>=bt)return;let M=3+fs;t.moveTo(M,Et(T))},qs=()=>We?u===0?"f":Je?"h":"u":"x",yi=()=>`ct|${qs()}|${he()}|${Yt}|${hi()}|${Bt??""}`,Uo=()=>`cb|${qs()}|${he()}`,Sr=()=>fe!==null?`cs|i|${fe}`:h?`cs|s|${m}|${a.length}`:Q!==null?`cs|h|${Q}`:"blank",zn=T=>`cbb|${qs()}|${he()}|${js(T)}`,jo=()=>`h|${li}`,wi=T=>{let M=a[T],U=M&&M.priority&&M.priority>0?"* ":" ",Y=No[T]??"";return`sr|${u===T+1&&!Je&&We?"1":"0"}|${U}${Y}`},Ze=()=>{Le(()=>{t.hideCursor(),fi(),An(),xn=1,ke.ensureSize(xe,G),ke.paintRow(xn,yi(),()=>{mi()});for(let T=0;T<bt;T++){let M=Bs+T;ke.paintRow(Et(T),zn(M),()=>{gi(M)})}ke.paintRow(qn(),Uo(),()=>{Un()}),ke.paintRow(qn()+1,Sr(),()=>Ho()),ke.paintRow(Qt(),jo(),()=>{t.dim.noFormat(` ${li}`)});for(let T=0;T<qe;T++){let M=p+T,U=Qt()+1+T;M<a.length?ke.paintRow(U,wi(M),()=>{Tt(M)}):ke.paintRow(U,"blank",()=>{})}$e();for(let T=Wn()+1;T<=G;T++)ke.paintRow(T,"blank",()=>{});u===0&&(fn(),t.hideCursor(!1))})},qo=()=>{ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ze()},ys=()=>{Le(()=>{t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
222
222
 
223
- `);for(let T of QT){if(T===null){t(`
224
- `);continue}let[M,U]=T;t.brightCyan.noFormat(` ${M.padEnd(VT)}`),t.noFormat(U)(`
223
+ `);for(let T of tE){if(T===null){t(`
224
+ `);continue}let[M,U]=T;t.brightCyan.noFormat(` ${M.padEnd(eE)}`),t.noFormat(U)(`
225
225
  `)}t(`
226
226
  `),t.dim.noFormat(" press any key to dismiss")(`
227
- `)})},qt=()=>ge+4,Cl=2,vt=0,ws=()=>{G=Ms(t);let T=Math.max(2,G-(ge+3)-Cl);return Math.max(1,Math.floor(T/2))},sd=()=>{let T=ws();D<vt?vt=D:D>=vt+T&&(vt=D-T+1),vt+T>B.length&&(vt=Math.max(0,B.length-T)),vt<0&&(vt=0)},rd=T=>{xe=Jt(t);let M=Math.max(2,xe-3),U="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,M-U.length));T?t.brightBlue.noFormat(`\u256D${U}${Y}\u256E`):t.dim.noFormat(`\u256D${U}${Y}\u256E`),t.styleReset()},kr=()=>{xe=Jt(t),ed=Math.max(10,xe-cv);let T=P.state();Do=ls(T.buffer,ed);let M=Fs(Do,T,YT);ge=M.rendered,Ns=M.windowStart,td=M.cursorVisualRow,ui=M.cursorVisualCol},Wo=(T,M)=>{xe=Jt(t);let U=Math.max(2,xe-3),Y=Do[T],re="";Y&&(re=(P.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let ie=Math.max(0,U-1-re.length),ve=" ".repeat(ie);M?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${re}${ve}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${re}${ve}`),t.dim.noFormat("\u2502")),t.styleReset()},Gt=T=>{xe=Jt(t);let M=Math.max(2,xe-3),U="\u2500".repeat(M);T?t.brightBlue.noFormat(`\u2570${U}\u256F`):t.dim.noFormat(`\u2570${U}\u256F`),t.styleReset()},ut=()=>3+ui,Ir=()=>2+(td-Ns),bi=()=>{let T=E==="input";Oe(()=>{T&&t.hideCursor(),t.moveTo(1,1),rd(T);for(let M=0;M<ge;M++)t.moveTo(1,2+M),Wo(Ns+M,T);t.moveTo(1,2+ge),Gt(T),T&&(t.moveTo(ut(),Ir()),t.hideCursor(!1))})},vi=()=>{Oe(()=>{t.hideCursor();for(let T=0;T<ge;T++)t.moveTo(1,2+T),Wo(Ns+T,!0);t.moveTo(ut(),Ir()),t.hideCursor(!1)})},xr={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Si=(T,M)=>{let U=B[T];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Jt(t),re=Math.max(20,Y-Cp),ie=pt(U.sessionId),ve=U.title??dt(U.cwd),Ce=M&&U.snippets.length>1?` [${N+1}/${U.snippets.length}]`:M&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",et=`${ie} ${U.status==="warm"?"warm":"cold"}`,mt=Math.max(5,re-et.length-Ce.length-2),Ve=Ta(ve,mt),Ks=`${et} ${Ve}${Ce}`.padEnd(re),Nt=U.snippets[M?N:0],Ss=Nt?xr[Nt.kind]??Nt.kind:"",ks=Nt?.toolName?`${Ss} \xB7 ${Nt.toolName}`:Ss,ft=Math.max(10,re-ks.length-6),St=Nt?Ta(Nt.text,ft):"",mn=Nt?` ${ks} ${St}`:" (no snippet)";return{rowBudget:re,line1:Ks,line2:mn.padEnd(re+Cp),focusedRow:M}},zo=(T,M)=>{let{line1:U,focusedRow:Y}=Si(T,M);Y?t.brightWhite.bgBlue.noFormat(`\u276F ${U}`):t.noFormat(` ${U}`),t.styleReset()},Ko=(T,M)=>{let{line2:U}=Si(T,M);t.dim.noFormat(U),t.styleReset()},Ar=()=>{if(K)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(L!==null)t.brightRed.noFormat(` ${L}`),t.styleReset(),t.eraseLineAfter();else if(E==="input")B.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 T=B.length,M=_?" \xB7 truncated":"",U=T>0?` ${T} ${T===1?"session":"sessions"} match${M} \xB7 `:" ";t.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},Cn=()=>{kr();let T=E==="input",M=P.state().buffer.join(`
228
- `);Oe(()=>{t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),rd(T);for(let Y=0;Y<ge;Y++)t.moveTo(1,2+Y),Wo(Ns+Y,T);t.moveTo(1,2+ge),Gt(T);let U=B.length;if(U===0)t.moveTo(1,qt()),K||(L===null&&M.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):L===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,qt()+1),Ar();else{sd();let Y=ws(),re=E!=="input";for(let ie=0;ie<Y;ie++){let ve=vt+ie;t.moveTo(1,qt()+ie*2),ve<U?zo(ve,re&&ve===D):t.eraseLineAfter(),t.moveTo(1,qt()+ie*2+1),ve<U?Ko(ve,re&&ve===D):t.eraseLineAfter()}t.moveTo(1,qt()+Y*2),Ar()}T&&(t.moveTo(ut(),Ir()),t.hideCursor(!1))})},bs=(T,M)=>{let U=T-vt;U<0||U>=ws()||Oe(()=>{t.moveTo(1,qt()+U*2),zo(T,M),t.moveTo(1,qt()+U*2+1),Ko(T,M)})},ki=()=>{Oe(()=>{t.moveTo(1,qt()+ws()*2),Ar()})},id=()=>{Oe(()=>{let T=ws(),M=B.length,U=E!=="input";for(let Y=0;Y<T;Y++){let re=vt+Y;t.moveTo(1,qt()+Y*2),re<M?zo(re,U&&re===D):t.eraseLineAfter(),t.moveTo(1,qt()+Y*2+1),re<M?Ko(re,U&&re===D):t.eraseLineAfter()}t.moveTo(1,qt()+T*2),Ar()})},qs=()=>P.state().buffer.join(`
229
- `),Rn=T=>{let M=ge;P.feed({type:"paste",text:T}),kr(),ge!==M?Cn():vi()},Tn=async()=>{let T=qs().trim();if(T.length!==0){if(a.length===0){L="no sessions in view to search",Cn();return}K=!0,L=null,Cn();try{let M=await Ry(e.target,T,{sessionIds:a.map(U=>U.sessionId)});B=M.results,_=M.truncated,D=0,N=0,vt=0,E=M.results.length>0?"results":"input",kr()}catch(M){L=`search failed: ${M.message}`}finally{K=!1,Cn()}}},vs=()=>{},Wt=()=>{Oe(()=>{let T=u===0;T&&t.hideCursor(),ke.paintRow(xn,yi(),()=>{mi()}),ke.paintRow(qn(),Uo(),()=>{Un()});for(let M=0;M<bt;M++){let U=Ls+M;ke.paintRow(Et(M),zn(U),()=>{gi(U)})}T&&(fn(),t.hideCursor(!1))})},pn=()=>{Oe(()=>{ke.paintRow(qn()+1,Sr(),()=>Ho())})},Ws=()=>{Q!==null&&(Q=null,pn())},Cr=()=>{Oe(()=>{let T=De.state();un=ls(T.buffer,Os);let M=Fs(un,T,Qa);Ls=M.windowStart,Bs=M.cursorVisualRow,fs=M.cursorVisualCol;let U=u===0;U&&t.hideCursor();for(let Y=0;Y<bt;Y++){let re=Ls+Y;ke.paintRow(Et(Y),zn(re),()=>{gi(re)})}U&&(fn(),t.hideCursor(!1))})},Ii=async()=>{let T=await al();if(!T.ok){Z=T.reason,$e();return}if(T.kind!=="image"){let M=De.state(),U=[...M.buffer],Y=M.row,re=M.col;De.feed({type:"paste",text:T.text});let ie=De.state();if(U.length!==ie.buffer.length||Y!==ie.row||re!==ie.col||!U.every((Ce,et)=>Ce===ie.buffer[et])){let Ce=ls(ie.buffer,Os);Fs(Ce,ie,Qa).rendered!==bt?Ze():Cr()}return}De.addAttachment(T.attachment),Z=`attached ${T.attachment.name??"image"}`,Ze()},Rl=T=>{T<p||T>=p+je||Oe(()=>{ke.paintRow(x(T),wi(T),()=>{Tt(T)})})},Xt=()=>{Oe(()=>{for(let T=0;T<je;T++){let M=Qt()+1+T,U=p+T;U<a.length?ke.paintRow(M,wi(U),()=>{Tt(U)}):ke.paintRow(M,"blank",()=>{})}$e()})},Tl=()=>{Oe(()=>{ke.paintRow(Qt(),jo(),()=>{t.dim.noFormat(` ${li}`)});for(let T=0;T<je;T++){let M=Qt()+1+T,U=p+T;U<a.length?ke.paintRow(M,wi(U),()=>{Tt(U)}):ke.paintRow(M,"blank",()=>{})}$e(),u===0&&(fn(),t.hideCursor(!1))})},hn=!1,Kn="",od=0,ad=200,Rr=null,xi=!1,Jn=null,Ai=!1,Zt=null,zs=!1,zt=null,Ci=null,Tr=null,Ri=T=>{let M=T.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let Y=M.indexOf("\x1B[I"),re=M.indexOf("\x1B[O"),ie=Y===-1?re:re===-1?Y:Math.min(Y,re);if(ie===-1)break;let ve=qe;qe=ie===Y,qe&&(od=Date.now()),ve!==qe&&!yt&&Ds.length<=1&&Oe(()=>{Wt(),Xt()}),M=M.slice(0,ie)+M.slice(ie+"\x1B[I".length)}if(M.length===0)return}if(!hn&&M===""&&Ci){Ci();return}if(!hn&&(M===""||M==="\x1B_"||M==="\x1B")){Tr?.(M);return}if(hn){let Y=M.indexOf(_a);if(Y===-1){Kn+=M;return}Kn+=M.slice(0,Y),hn=!1;let re=Buffer.from(Kn,"binary").toString("utf-8").replace(/\r\n?/g,`
230
- `);Kn="";let ie=M.slice(Y+_a.length);if(A)E==="input"&&!K&&Rn(re);else if(u===0&&!h){let ve=De.feed({type:"paste",text:re});for(let Ve of ve)Ve.type==="attachment-request"&&Ii();let Ce=De.state(),et=ls(Ce.buffer,Os);Fs(et,Ce,Qa).rendered!==bt?Ze():Cr()}ie.length>0&&zt&&zt(Buffer.from(ie,"binary"));return}let U=M.indexOf(Ro);if(U===-1){zt?.(T);return}U>0&&zt?.(Buffer.from(M.slice(0,U),"binary")),M=M.slice(U+Ro.length),hn=!0,M.length>0&&Ri(Buffer.from(M,"binary"))};return Ze(),await new Promise(T=>{let M=null,U=!1,Y=null,re=!1,ie=Ds,ve=F=>{ie.push(F)},Ce=()=>{ie.pop(),yt||ie[ie.length-1]?.onResize()},et={push:ve,pop:Ce},mt=()=>{let F={kind:"new",cwd:r},z=De.state().attachments;return z.length>0&&(F.attachments=[...z]),hs&&(F.agentId=hs),ms&&(F.model=ms),F},Ve=async()=>{Qs(),ke.clearCache(),ve({onKey:()=>{},onResize:()=>{}});let z;try{z=await di(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{Ce(),$r()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=kl(i,r),Rt()),yt||Ze()},Ks=async()=>{let F=e.availableAgents;if(!F||F.length===0)return;Qs(),ke.clearCache(),ve({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await ja(t,F,hs,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{Ce(),$r()}if(ue.kind==="select"){hs=ue.agentId;let J=e.config.defaultModels;if(ms=J?J[ue.agentId]:void 0,ue.persist)try{await Li(ue.agentId)}catch{}}yt||Ze()};vs=()=>{P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,vt=0,L=null,K=!1,E="input",A=!1,Ce()};let Nt=(F,z,ue)=>{Js(),ie[ie.length-1]?.onKey(F,z,ue)},Ss=()=>{yt||ie[ie.length-1]?.onResize()};Tr=F=>{yt||ie[ie.length-1]?.onKey(F,null,{})};let ks=!1,ft=()=>{if(ks)return;ks=!0,ie.length=0,M&&(clearInterval(M),M=null),Y&&(Y.abort(),Y=null,U=!1),t.off("key",Nt),t.off("mouse",_r),t.off("resize",Ss),process.stdout.write(Ps),process.stdout.write(Fa);let F=t;F.stdin&&zt&&(F.stdin.removeListener("data",Ri),F.stdin.on("data",zt),zt=null),hn=!1,Kn="",t.grabInput(!1),oe({src:"grab",site:"picker.detachInput",on:!1})},St=()=>{yt||(yt=!0,ft(),t.hideCursor(!1),t.moveTo(1,Wn()+1),t(`
231
- `))},mn=()=>{if(yt||ie.length>1||S!=="normal"||h||re)return;U&&Y&&(Y.abort(),Y=null,U=!1);let F=u>0?a[u-1]?.sessionId:void 0;U=!0;let z=new AbortController;Y=z,en(F,{silent:!0,signal:z.signal}).finally(()=>{Y===z&&(Y=null),U=!1})},Js=()=>{yt||(M&&clearInterval(M),M=setInterval(mn,3e3))},Dt=()=>(ft(),Sl("",{write(z){fe=z,pn()},finalize(){fe=null,St()}})),En=()=>(St(),T({kind:In?"exit":"abort"}),!0),gn=()=>{let F=d.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
227
+ `)})},qt=()=>ge+4,Rl=2,vt=0,ws=()=>{G=Ms(t);let T=Math.max(2,G-(ge+3)-Rl);return Math.max(1,Math.floor(T/2))},sd=()=>{let T=ws();D<vt?vt=D:D>=vt+T&&(vt=D-T+1),vt+T>B.length&&(vt=Math.max(0,B.length-T)),vt<0&&(vt=0)},rd=T=>{xe=Jt(t);let M=Math.max(2,xe-3),U="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,M-U.length));T?t.brightBlue.noFormat(`\u256D${U}${Y}\u256E`):t.dim.noFormat(`\u256D${U}${Y}\u256E`),t.styleReset()},kr=()=>{xe=Jt(t),ed=Math.max(10,xe-lv);let T=P.state();Do=ls(T.buffer,ed);let M=Fs(Do,T,ZT);ge=M.rendered,Ds=M.windowStart,td=M.cursorVisualRow,ui=M.cursorVisualCol},Wo=(T,M)=>{xe=Jt(t);let U=Math.max(2,xe-3),Y=Do[T],re="";Y&&(re=(P.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let ie=Math.max(0,U-1-re.length),ve=" ".repeat(ie);M?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${re}${ve}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${re}${ve}`),t.dim.noFormat("\u2502")),t.styleReset()},Gt=T=>{xe=Jt(t);let M=Math.max(2,xe-3),U="\u2500".repeat(M);T?t.brightBlue.noFormat(`\u2570${U}\u256F`):t.dim.noFormat(`\u2570${U}\u256F`),t.styleReset()},ut=()=>3+ui,Ir=()=>2+(td-Ds),bi=()=>{let T=E==="input";Le(()=>{T&&t.hideCursor(),t.moveTo(1,1),rd(T);for(let M=0;M<ge;M++)t.moveTo(1,2+M),Wo(Ds+M,T);t.moveTo(1,2+ge),Gt(T),T&&(t.moveTo(ut(),Ir()),t.hideCursor(!1))})},vi=()=>{Le(()=>{t.hideCursor();for(let T=0;T<ge;T++)t.moveTo(1,2+T),Wo(Ds+T,!0);t.moveTo(ut(),Ir()),t.hideCursor(!1)})},xr={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Si=(T,M)=>{let U=B[T];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Jt(t),re=Math.max(20,Y-Rp),ie=pt(U.sessionId),ve=U.title??dt(U.cwd),Ce=M&&U.snippets.length>1?` [${N+1}/${U.snippets.length}]`:M&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",et=`${ie} ${U.status==="warm"?"warm":"cold"}`,mt=Math.max(5,re-et.length-Ce.length-2),Qe=Ta(ve,mt),Js=`${et} ${Qe}${Ce}`.padEnd(re),Nt=U.snippets[M?N:0],Ss=Nt?xr[Nt.kind]??Nt.kind:"",ks=Nt?.toolName?`${Ss} \xB7 ${Nt.toolName}`:Ss,ft=Math.max(10,re-ks.length-6),St=Nt?Ta(Nt.text,ft):"",mn=Nt?` ${ks} ${St}`:" (no snippet)";return{rowBudget:re,line1:Js,line2:mn.padEnd(re+Rp),focusedRow:M}},zo=(T,M)=>{let{line1:U,focusedRow:Y}=Si(T,M);Y?t.brightWhite.bgBlue.noFormat(`\u276F ${U}`):t.noFormat(` ${U}`),t.styleReset()},Ko=(T,M)=>{let{line2:U}=Si(T,M);t.dim.noFormat(U),t.styleReset()},Ar=()=>{if(K)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(L!==null)t.brightRed.noFormat(` ${L}`),t.styleReset(),t.eraseLineAfter();else if(E==="input")B.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 T=B.length,M=_?" \xB7 truncated":"",U=T>0?` ${T} ${T===1?"session":"sessions"} match${M} \xB7 `:" ";t.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},Cn=()=>{kr();let T=E==="input",M=P.state().buffer.join(`
228
+ `);Le(()=>{t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),rd(T);for(let Y=0;Y<ge;Y++)t.moveTo(1,2+Y),Wo(Ds+Y,T);t.moveTo(1,2+ge),Gt(T);let U=B.length;if(U===0)t.moveTo(1,qt()),K||(L===null&&M.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):L===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,qt()+1),Ar();else{sd();let Y=ws(),re=E!=="input";for(let ie=0;ie<Y;ie++){let ve=vt+ie;t.moveTo(1,qt()+ie*2),ve<U?zo(ve,re&&ve===D):t.eraseLineAfter(),t.moveTo(1,qt()+ie*2+1),ve<U?Ko(ve,re&&ve===D):t.eraseLineAfter()}t.moveTo(1,qt()+Y*2),Ar()}T&&(t.moveTo(ut(),Ir()),t.hideCursor(!1))})},bs=(T,M)=>{let U=T-vt;U<0||U>=ws()||Le(()=>{t.moveTo(1,qt()+U*2),zo(T,M),t.moveTo(1,qt()+U*2+1),Ko(T,M)})},ki=()=>{Le(()=>{t.moveTo(1,qt()+ws()*2),Ar()})},id=()=>{Le(()=>{let T=ws(),M=B.length,U=E!=="input";for(let Y=0;Y<T;Y++){let re=vt+Y;t.moveTo(1,qt()+Y*2),re<M?zo(re,U&&re===D):t.eraseLineAfter(),t.moveTo(1,qt()+Y*2+1),re<M?Ko(re,U&&re===D):t.eraseLineAfter()}t.moveTo(1,qt()+T*2),Ar()})},Ws=()=>P.state().buffer.join(`
229
+ `),Rn=T=>{let M=ge;P.feed({type:"paste",text:T}),kr(),ge!==M?Cn():vi()},Tn=async()=>{let T=Ws().trim();if(T.length!==0){if(a.length===0){L="no sessions in view to search",Cn();return}K=!0,L=null,Cn();try{let M=await Ty(e.target,T,{sessionIds:a.map(U=>U.sessionId)});B=M.results,_=M.truncated,D=0,N=0,vt=0,E=M.results.length>0?"results":"input",kr()}catch(M){L=`search failed: ${M.message}`}finally{K=!1,Cn()}}},vs=()=>{},Wt=()=>{Le(()=>{let T=u===0;T&&t.hideCursor(),ke.paintRow(xn,yi(),()=>{mi()}),ke.paintRow(qn(),Uo(),()=>{Un()});for(let M=0;M<bt;M++){let U=Bs+M;ke.paintRow(Et(M),zn(U),()=>{gi(U)})}T&&(fn(),t.hideCursor(!1))})},pn=()=>{Le(()=>{ke.paintRow(qn()+1,Sr(),()=>Ho())})},zs=()=>{Q!==null&&(Q=null,pn())},Cr=()=>{Le(()=>{let T=He.state();un=ls(T.buffer,Ls);let M=Fs(un,T,Qa);Bs=M.windowStart,Ns=M.cursorVisualRow,fs=M.cursorVisualCol;let U=u===0;U&&t.hideCursor();for(let Y=0;Y<bt;Y++){let re=Bs+Y;ke.paintRow(Et(Y),zn(re),()=>{gi(re)})}U&&(fn(),t.hideCursor(!1))})},Ii=async()=>{let T=await al();if(!T.ok){Z=T.reason,$e();return}if(T.kind!=="image"){let M=He.state(),U=[...M.buffer],Y=M.row,re=M.col;He.feed({type:"paste",text:T.text});let ie=He.state();if(U.length!==ie.buffer.length||Y!==ie.row||re!==ie.col||!U.every((Ce,et)=>Ce===ie.buffer[et])){let Ce=ls(ie.buffer,Ls);Fs(Ce,ie,Qa).rendered!==bt?Ze():Cr()}return}He.addAttachment(T.attachment),Z=`attached ${T.attachment.name??"image"}`,Ze()},Tl=T=>{T<p||T>=p+qe||Le(()=>{ke.paintRow(x(T),wi(T),()=>{Tt(T)})})},Xt=()=>{Le(()=>{for(let T=0;T<qe;T++){let M=Qt()+1+T,U=p+T;U<a.length?ke.paintRow(M,wi(U),()=>{Tt(U)}):ke.paintRow(M,"blank",()=>{})}$e()})},El=()=>{Le(()=>{ke.paintRow(Qt(),jo(),()=>{t.dim.noFormat(` ${li}`)});for(let T=0;T<qe;T++){let M=Qt()+1+T,U=p+T;U<a.length?ke.paintRow(M,wi(U),()=>{Tt(U)}):ke.paintRow(M,"blank",()=>{})}$e(),u===0&&(fn(),t.hideCursor(!1))})},hn=!1,Kn="",od=0,ad=200,Rr=null,xi=!1,Jn=null,Ai=!1,Zt=null,Ks=!1,zt=null,Ci=null,Tr=null,Ri=T=>{let M=T.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let Y=M.indexOf("\x1B[I"),re=M.indexOf("\x1B[O"),ie=Y===-1?re:re===-1?Y:Math.min(Y,re);if(ie===-1)break;let ve=We;We=ie===Y,We&&(od=Date.now()),ve!==We&&!yt&&Hs.length<=1&&Le(()=>{Wt(),Xt()}),M=M.slice(0,ie)+M.slice(ie+"\x1B[I".length)}if(M.length===0)return}if(!hn&&M===""&&Ci){Ci();return}if(!hn&&(M===""||M==="\x1B_"||M==="\x1B")){Tr?.(M);return}if(hn){let Y=M.indexOf(_a);if(Y===-1){Kn+=M;return}Kn+=M.slice(0,Y),hn=!1;let re=Buffer.from(Kn,"binary").toString("utf-8").replace(/\r\n?/g,`
230
+ `);Kn="";let ie=M.slice(Y+_a.length);if(A)E==="input"&&!K&&Rn(re);else if(u===0&&!h){let ve=He.feed({type:"paste",text:re});for(let Qe of ve)Qe.type==="attachment-request"&&Ii();let Ce=He.state(),et=ls(Ce.buffer,Ls);Fs(et,Ce,Qa).rendered!==bt?Ze():Cr()}ie.length>0&&zt&&zt(Buffer.from(ie,"binary"));return}let U=M.indexOf(Ro);if(U===-1){zt?.(T);return}U>0&&zt?.(Buffer.from(M.slice(0,U),"binary")),M=M.slice(U+Ro.length),hn=!0,M.length>0&&Ri(Buffer.from(M,"binary"))};return Ze(),await new Promise(T=>{let M=null,U=!1,Y=null,re=!1,ie=Hs,ve=F=>{ie.push(F)},Ce=()=>{ie.pop(),yt||ie[ie.length-1]?.onResize()},et={push:ve,pop:Ce},mt=()=>{let F={kind:"new",cwd:r},z=He.state().attachments;return z.length>0&&(F.attachments=[...z]),hs&&(F.agentId=hs),ms&&(F.model=ms),F},Qe=async()=>{Gs(),ke.clearCache(),ve({onKey:()=>{},onResize:()=>{}});let z;try{z=await di(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{Ce(),$r()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=kl(i,r),Rt()),yt||Ze()},Js=async()=>{let F=e.availableAgents;if(!F||F.length===0)return;Gs(),ke.clearCache(),ve({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await ja(t,F,hs,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{Ce(),$r()}if(ue.kind==="select"){hs=ue.agentId;let J=e.config.defaultModels;if(ms=J?J[ue.agentId]:void 0,ue.persist)try{await Li(ue.agentId)}catch{}}yt||Ze()};vs=()=>{P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,vt=0,L=null,K=!1,E="input",A=!1,Ce()};let Nt=(F,z,ue)=>{Ys(),ie[ie.length-1]?.onKey(F,z,ue)},Ss=()=>{yt||ie[ie.length-1]?.onResize()};Tr=F=>{yt||ie[ie.length-1]?.onKey(F,null,{})};let ks=!1,ft=()=>{if(ks)return;ks=!0,ie.length=0,M&&(clearInterval(M),M=null),Y&&(Y.abort(),Y=null,U=!1),t.off("key",Nt),t.off("mouse",_r),t.off("resize",Ss),process.stdout.write(Ps),process.stdout.write(Fa);let F=t;F.stdin&&zt&&(F.stdin.removeListener("data",Ri),F.stdin.on("data",zt),zt=null),hn=!1,Kn="",t.grabInput(!1),oe({src:"grab",site:"picker.detachInput",on:!1})},St=()=>{yt||(yt=!0,ft(),t.hideCursor(!1),t.moveTo(1,Wn()+1),t(`
231
+ `))},mn=()=>{if(yt||ie.length>1||S!=="normal"||h||re)return;U&&Y&&(Y.abort(),Y=null,U=!1);let F=u>0?a[u-1]?.sessionId:void 0;U=!0;let z=new AbortController;Y=z,en(F,{silent:!0,signal:z.signal}).finally(()=>{Y===z&&(Y=null),U=!1})},Ys=()=>{yt||(M&&clearInterval(M),M=setInterval(mn,3e3))},Dt=()=>(ft(),Sl("",{write(z){fe=z,pn()},finalize(){fe=null,St()}})),En=()=>(St(),T({kind:In?"exit":"abort"}),!0),gn=()=>{let F=d.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
232
232
  `);return`${u}:${p}:${Z??""}
233
- ${F}`},en=async(F,z={})=>{try{let ue=z.silent?gn():"",J=f,de=await Ln(e.target,{includeNonInteractive:!0,signal:z.signal}),ce=F??(u>0?a[u-1]?.sessionId:void 0);if(i=kl(de,r),Rt(),ce!==void 0){let Te=a.findIndex(He=>He.sessionId===ce);Te>=0?u=Te+1:u=0}if(u>f-1&&(u=Math.max(0,f-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An(),z.silent&&gn()===ue)return;f===J?Tl():Ze()}catch(ue){if(z.silent)return;Z=`refresh failed: ${ue.message}`,Ze()}},Er=async F=>{if(!k)return;let z=k;S="busy",$e();try{await xy(e.target,z.sessionId,F),S="normal",k=null,X=null,await en(z.sessionId)}catch(ue){S="normal",k=null,X=null,Z=`rename failed: ${ue.message}`,$e()}},Ti=async F=>{try{await Cy(e.target,F.sessionId),Z="title regen queued (press r to refresh)",$e()}catch(z){Z=`regen failed: ${z.message}`,$e()}},Pr=async F=>{let ue=(F.priority&&F.priority>0?F.priority:0)>0?null:1,J=ue??0;for(let ce of i)ce.sessionId===F.sessionId&&(ce.priority=J>0?J:void 0);let de=F.sessionId;i=kl(i,r),Rt(),ps(de),Ze(),Z=J>0?"priority: high":"priority: normal",$e();try{await Ay(e.target,F.sessionId,ue)}catch(ce){Z=`priority failed: ${ce.message}`,$e()}},Ys=async()=>{if(re)return;re=!0;let F=u>0?a[u-1]?.sessionId:void 0;Z="syncing agents\u2026",$e();try{let{synced:z,skipped:ue,agents:J}=await Iy(e.target);await en(F),Z=`synced ${z} new (${ue} known) from ${J} agent${J===1?"":"s"}`,$e()}catch(z){Z=`sync failed: ${z.message}`,$e()}finally{re=!1}},Mr=async F=>{if(!k)return;let z=k;S="busy",$e();try{F==="kill"?await os(e.target,z.sessionId):await Ty(e.target,z.sessionId),S="normal",k=null,z.sessionId===e.currentSessionId&&(In=!0);let ue;if(F==="kill")ue=z.sessionId;else{let J=a.findIndex(de=>de.sessionId===z.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await en(ue)}catch(ue){S="normal",k=null,Z=`${F} failed: ${ue.message}`,$e()}},ot=(F,z)=>{F===0!=(z===0)&&(Wt(),z===0?(t.hideCursor(!1),fn()):t.hideCursor())},rt=F=>{let z=Math.min(f-1,Math.max(0,u+F));if(z===u)return;let ue=u;u=z,An(),Oe(()=>{Xt(),ot(ue,u)})},Pn=()=>Z===null?!1:(Z=null,$e(),!0),Yn=()=>{ys(),ve({onKey:F=>{if(F==="CTRL_C"){St(),T({kind:"abort"});return}Ce()},onResize:()=>ys()})},Vs=F=>{let z=null,ue=null,J=!0,de=()=>{Oe(()=>{if(t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${pt(F.sessionId)}`)(`
233
+ ${F}`},en=async(F,z={})=>{try{let ue=z.silent?gn():"",J=f,de=await Ln(e.target,{includeNonInteractive:!0,signal:z.signal}),ce=F??(u>0?a[u-1]?.sessionId:void 0);if(i=kl(de,r),Rt(),ce!==void 0){let Te=a.findIndex(Ue=>Ue.sessionId===ce);Te>=0?u=Te+1:u=0}if(u>f-1&&(u=Math.max(0,f-1)),p+qe>a.length&&(p=Math.max(0,a.length-qe)),An(),z.silent&&gn()===ue)return;f===J?El():Ze()}catch(ue){if(z.silent)return;Z=`refresh failed: ${ue.message}`,Ze()}},Er=async F=>{if(!k)return;let z=k;S="busy",$e();try{await Ay(e.target,z.sessionId,F),S="normal",k=null,X=null,await en(z.sessionId)}catch(ue){S="normal",k=null,X=null,Z=`rename failed: ${ue.message}`,$e()}},Ti=async F=>{try{await Ry(e.target,F.sessionId),Z="title regen queued (press r to refresh)",$e()}catch(z){Z=`regen failed: ${z.message}`,$e()}},Pr=async F=>{let ue=(F.priority&&F.priority>0?F.priority:0)>0?null:1,J=ue??0;for(let ce of i)ce.sessionId===F.sessionId&&(ce.priority=J>0?J:void 0);let de=F.sessionId;i=kl(i,r),Rt(),ps(de),Ze(),Z=J>0?"priority: high":"priority: normal",$e();try{await Cy(e.target,F.sessionId,ue)}catch(ce){Z=`priority failed: ${ce.message}`,$e()}},Vs=async()=>{if(re)return;re=!0;let F=u>0?a[u-1]?.sessionId:void 0;Z="syncing agents\u2026",$e();try{let{synced:z,skipped:ue,agents:J}=await xy(e.target);await en(F),Z=`synced ${z} new (${ue} known) from ${J} agent${J===1?"":"s"}`,$e()}catch(z){Z=`sync failed: ${z.message}`,$e()}finally{re=!1}},Mr=async F=>{if(!k)return;let z=k;S="busy",$e();try{F==="kill"?await os(e.target,z.sessionId):await Ey(e.target,z.sessionId),S="normal",k=null,z.sessionId===e.currentSessionId&&(In=!0);let ue;if(F==="kill")ue=z.sessionId;else{let J=a.findIndex(de=>de.sessionId===z.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await en(ue)}catch(ue){S="normal",k=null,Z=`${F} failed: ${ue.message}`,$e()}},ot=(F,z)=>{F===0!=(z===0)&&(Wt(),z===0?(t.hideCursor(!1),fn()):t.hideCursor())},rt=F=>{let z=Math.min(f-1,Math.max(0,u+F));if(z===u)return;let ue=u;u=z,An(),Le(()=>{Xt(),ot(ue,u)})},Pn=()=>Z===null?!1:(Z=null,$e(),!0),Yn=()=>{ys(),ve({onKey:F=>{if(F==="CTRL_C"){St(),T({kind:"abort"});return}Ce()},onResize:()=>ys()})},Qs=F=>{let z=null,ue=null,J=!0,de=()=>{Le(()=>{if(t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${pt(F.sessionId)}`)(`
234
234
 
235
235
  `),J)t.dim.noFormat(" loading\u2026")(`
236
236
  `);else if(ue!==null)t.brightRed.noFormat(` ${ue}`)(`
237
- `);else if(z!==null)for(let He of z)t.noFormat(` ${He}`)(`
237
+ `);else if(z!==null)for(let Ue of z)t.noFormat(` ${Ue}`)(`
238
238
  `);t(`
239
239
  `),t.dim.noFormat(" Esc / ^C to return")(`
240
- `)})};de();let ce=new AbortController,Te={onKey:He=>{if(He==="ESCAPE"||He==="CTRL_C"){ce.abort(),Ce();return}},onResize:()=>de()};ve(Te),(async()=>{try{let He=await ln(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(F.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!He.ok)throw new Error(`daemon returned HTTP ${He.status}`);let We=await He.json(),at=On(We),tn=Tf(at,F.status);z=Bc(tn,!1).replace(/\n$/,"").split(`
241
- `)}catch(He){if(ce.signal.aborted)return;ue=`failed to load info: ${He.message}`}finally{J=!1,!yt&&ie[ie.length-1]===Te&&de()}})()},El=()=>{if(a.length===0){Z="no sessions to search",$e();return}P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,vt=0,L=null,K=!1,E="input",A=!0,kr(),Cn(),ve({onKey:(z,ue,J)=>{if(E==="input"){if(K)return;if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="ENTER"||z==="KP_ENTER"){if(qs().trim().length===0)return;Tn();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&B.length>0){E="results",D=0,N=0,Oe(()=>{bi(),bs(0,!0),ki(),t.hideCursor()});return}let de=P.state(),ce=[...de.buffer],Te=de.row,He=de.col,We=null;if(z==="")We={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")We={type:"key",name:"alt-underscore"};else if(J?.isCharacter)We={type:"char",ch:z};else{let ze=ml(z);ze!==null&&(We={type:"key",name:ze})}if(We===null){t.moveTo(ut(),Ir());return}P.feed(We);let at=P.state();if(ce.length===at.buffer.length&&ce.every((ze,Ue)=>ze===at.buffer[Ue])&&Te===at.row&&He===at.col){t.moveTo(ut(),Ir());return}let Vn=ge;kr(),ge!==Vn?Cn():vi();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="CTRL_F"){E="input",id(),ki(),bi();return}if(z==="ENTER"||z==="KP_ENTER"){let ce=B[D];if(!ce)return;let Te=a.find(We=>We.sessionId===ce.sessionId);if(!!Te?.importedFromMachine&&!Te.upstreamSessionId){St();let We={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(We.agentId=Te.agentId),T(We);return}(async()=>{let We=await nv(t,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},et);if(We==="cancel"){St(),T({kind:"abort"});return}if(We==="back")return;St();let at={kind:"attach",sessionId:ce.sessionId,readonly:We==="view"};Te?.agentId!==void 0&&(at.agentId=Te.agentId),T(at)})();return}if(J?.isCharacter&&(z==="n"||z==="N")){let ce=B[D];if(!ce||ce.snippets.length<=1)return;N=(N+1)%ce.snippets.length,bs(D,!0);return}if(J?.isCharacter&&(z==="p"||z==="P")){let ce=B[D];if(!ce||ce.snippets.length<=1)return;N=(N-1+ce.snippets.length)%ce.snippets.length,bs(D,!0);return}let de=ce=>{if(ce<0&&D===0){E="input",Oe(()=>{bs(0,!1),ki(),bi()});return}let Te=Math.min(B.length-1,Math.max(0,D+ce));if(Te===D)return;let He=D,We=vt;D=Te,N=0,sd(),vt!==We?id():(Oe(()=>{bs(He,!1),bs(D,!0)}),ki())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":de(-1);return;case"DOWN":case"TAB":case"CTRL_N":de(1);return;case"PAGE_UP":de(-ws());return;case"PAGE_DOWN":de(ws());return;case"HOME":de(-D);return;case"END":de(B.length);return}return}},onResize:()=>Cn()})},Pl=(F,z,ue)=>{if(S!=="busy"){if(F==="CTRL_O"){Ve();return}if(F==="CTRL_L"){qo();return}if(S==="rename"&&X){if(F==="ENTER"||F==="KP_ENTER"){let J=X.text.trim();if(J.length===0){S="normal",k=null,X=null,$e();return}Er(J);return}if(F==="ESCAPE"||F==="CTRL_C"){S="normal",k=null,X=null,$e();return}if(X.handleKey(F,ue?.isCharacter===!0)){$e();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(F==="y"||F==="Y")){Mr(S==="confirm-kill"?"kill":"delete");return}if(F==="ESCAPE"||F==="CTRL_C"||F==="ENTER"||F==="KP_ENTER"||ue?.isCharacter&&(F==="n"||F==="N")){S="normal",k=null,$e();return}return}if(Pn(),Ke&&(Ke=!1,u=0,Oe(()=>{Wt(),Xt()})),F==="CTRL_F"&&u!==0){El();return}if(u===0&&!h){if(F==="ESCAPE"){En();return}if(F==="ENTER"||F==="KP_ENTER"){let Ue=De.expandedText(),kt=mt();Ue.trim().length>0&&(kt.prompt=Ue),kt.installStatus=Dt(),T(kt);return}if(F==="UP"&&w){let Ue=Date.now(),kt=Ue-b;if(b=Ue,kt<y){fn();return}w=!1}if(F==="DOWN"){let Ue=De.state(),kt=Ue.historyIndex!==-1||Ue.queueIndex!==-1,gt=un.length===0||Bs===un.length-1;if(!kt&&gt&&a.length>0){rt(1);return}}if(F==="PAGE_DOWN"&&(un.length===0||Bs===un.length-1)&&a.length>0){rt(1);return}if(F==="CTRL_P"){a.length>0&&rt(1);return}if(w=!1,F==="TAB"){let Ue=De.state(),kt=Ue.buffer[Ue.row]??"",gt=bl(kt,Ue.col);if(gt!==null){let Pt=vl(gt.token,r);if(Pt!==null){if(Pt.replacement!==gt.token&&(De.replaceRangeOnCurrentLine(gt.start,Ue.col,Pt.replacement),Cr()),Pt.candidates.length>1){let Gs=Pt.candidates.join(" ");Q=`${Pt.candidates.length} matches: ${Gs}`,pn()}else Ws();fn();return}}}Ws();let J=De.state(),de=[...J.buffer],ce=J.row,Te=J.col,He=null;if(F==="")He={type:"key",name:"ctrl-underscore"};else if(F==="\x1B_"||F==="\x1B")He={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)He={type:"char",ch:F};else{let Ue=ml(F);Ue!==null&&(He={type:"key",name:Ue})}if(He===null){fn();return}let We=De.feed(He),at=De.state(),tn=de.length===at.buffer.length&&de.every((Ue,kt)=>Ue===at.buffer[kt])&&ce===at.row&&Te===at.col;if(We.some(Ue=>Ue.type==="exit")){En();return}for(let Ue of We)Ue.type==="attachment-request"&&Ii();if(tn){fn();return}let Vn=ls(at.buffer,Os);if(Fs(Vn,at,Qa).rendered!==bt){Ze();return}Cr();return}if(!h&&ue?.isCharacter&&F==="?"){Yn();return}if(h){if(ue?.isCharacter){m+=F,Rt(),Ze();return}if(F==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Rt(),Ze()):(h=!1,Rt(),Ze());return}if(F==="ESCAPE"||F==="CTRL_C"){h=!1,m="",Rt(),Ze();return}}if(ue?.isCharacter){if(F==="/"){h=!0,m="",Rt(),Ze();return}if(F==="n"||F==="N"){rt(1);return}if(F==="p"||F==="P"){rt(-1);return}if(F==="c"||F==="C"){let J=u>0?a[u-1]:void 0,de=mt();J?.cwd&&(de.cwd=J.cwd),de.installStatus=Dt(),T(de);return}if(F==="q"||F==="Q"){En();return}if(F==="o"||F==="O"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Rt(),ps(J),Ze();return}if(F==="h"||F==="H"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=lv(s.filters.hostFilter,i),Rt(),ps(J),Ze();return}if(F==="i"&&u>0){let J=a[u-1];if(!J)return;Vs(J);return}if(F==="I"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Rt(),ps(J),Ze();return}if(F==="r"||F==="R"){let J=u>0?a[u-1]?.sessionId:void 0;en(J);return}if(F==="s"||F==="S"){Ys();return}if((F==="v"||F==="V")&&u>0){let J=a[u-1];if(!J)return;let de={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Dt(),T(de);return}if((F==="f"||F==="F")&&u>0){let J=a[u-1];if(!J)return;St();let de={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(de.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(de.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(de.sourceUpstreamSessionId=J.upstreamSessionId),T(de);return}if((F==="k"||F==="K")&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",$e();return}if(F==="t"&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},X=new Bo(J.title??""),S="rename",$e();return}if(F==="T"&&u>0){let J=a[u-1];if(!J)return;Ti({sessionId:J.sessionId});return}if(F==="*"&&u>0){let J=a[u-1];if(!J)return;Pr(J);return}if((F==="d"||F==="D")&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",$e();return}Ke=!1,u=0,De.feed({type:"char",ch:F}),Ze();return}switch(F){case"UP":case"SHIFT_TAB":case"CTRL_P":F==="UP"&&(u===1&&(w=!0),b=Date.now()),rt(-1);return;case"DOWN":case"TAB":case"CTRL_N":rt(1);return;case"PAGE_UP":rt(-je);return;case"PAGE_DOWN":rt(je);return;case"HOME":rt(1-u);return;case"END":rt(f);return;case"RIGHT":if(Ke||u===0)break;case"ENTER":case"KP_ENTER":{if(Ke){let ce=De.expandedText(),Te=mt();ce.trim().length>0&&(Te.prompt=ce),Te.installStatus=Dt(),T(Te);return}if(u===0){let ce=mt();ce.installStatus=Dt(),T(ce);return}let J=a[u-1];if(!J){St(),T({kind:"abort"});return}let de={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Dt(),T(de);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":En();return}}};ve({onKey:(F,z,ue)=>Pl(F,z,ue),onResize:()=>{yt||Ze()}});let _r=(F,z)=>{if(yt||ie.length!==1||S!=="normal")return;let ue=F==="MOUSE_MOTION",J=F==="MOUSE_LEFT_BUTTON_PRESSED",de=F==="MOUSE_LEFT_BUTTON_RELEASED",ce=F==="MOUSE_WHEEL_UP",Te=F==="MOUSE_WHEEL_DOWN",He=qe&&Date.now()-od<ad,We=!qe||He;if(J){Rr={x:z?.x??-1,y:z?.y??-1},xi=We;return}if(ue&&We)return;let at=de&&Rr!==null&&z?.x===Rr.x&&z?.y===Rr.y,tn=at&&!xi,Vn=at&&xi;if(de&&(Rr=null,xi=!1,!at))return;if(ce||Te){if(a.length===0)return;let Le=ce?-3:3,Mt=Math.max(0,a.length-je),Xs=Math.min(Mt,Math.max(0,p+Le));if(Xs===p)return;if(p=Xs,u>0){let Pi=u-1;Pi<p?u=p+1:Pi>=p+je&&(u=p+je)}Xt();return}if(!ue&&!tn)return;let ze=z?.y;if(typeof ze!="number")return;{let Le=z?.x,Mt=Jn!==null&&ze===Wn()&&typeof Le=="number"&&Le>=Jn.start&&Le<=Jn.end,Xs=Zt!==null&&ze===Wn()&&typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end;(Mt!==Ai||Xs!==zs)&&(Ai=Mt,zs=Xs,$e(),u===0?(fn(),t.hideCursor(!1)):t.hideCursor(!0))}if(tn&&Jn!==null&&ze===Wn()){let Le=z?.x;if(typeof Le=="number"&&Le>=Jn.start&&Le<=Jn.end){En();return}}if(tn&&Zt!==null&&ze===Wn()){let Le=z?.x;if(typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end){let Mt=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=lv(s.filters.hostFilter,i),Rt(),ps(Mt),Ze();return}}if(ze>=xn&&ze<=qn()){let Le=null;if(ze===xn){let Mt=z?.x;typeof Mt=="number"&&(gs!==null&&Mt>=gs.start&&Mt<=gs.end?Le="agent":Hs!==null&&Mt>=Hs.start&&Mt<=Hs.end&&(Le="cwd"))}if(Le!==Bt&&(Bt=Le,Wt()),tn&&ze===xn){if(Bt==="agent"){Ks();return}if(Bt==="cwd"){Ve();return}}if((tn||Vn)&&u!==0){Ke=!1;let Mt=u;u=0,Oe(()=>{Xt(),ot(Mt,u)});return}ue&&!Ke&&u!==0&&(Ke=!0,Oe(()=>{Wt(),Xt()}));return}Bt!==null&&(Bt=null,Wt()),Ke&&(Ke=!1,Oe(()=>{Wt(),Xt()}));let kt=Qt()+1,gt=kt+je-1;if(ze<kt||ze>gt)return;let Pt=p+(ze-kt);if(Pt<0||Pt>=a.length)return;let Gs=a[Pt];if(!Gs)return;let Is=Pt+1;if(ue&&u===0)return;let dd=u===0,Ml=u===Is;if(Vn&&u!==Is){let Le=u;u=Is,An(),Oe(()=>{Xt(),ot(Le,u)});return}if(Vn)return;if(u!==Is){let Le=u;u=Is,An(),Oe(()=>{Xt(),ot(Le,u)})}if(!tn||dd||!Ml)return;let Ei={kind:"attach",sessionId:Gs.sessionId};Gs.agentId!==void 0&&(Ei.agentId=Gs.agentId),Ei.installStatus=Dt(),T(Ei)},$r=()=>{t.grabInput({mouse:"motion"}),oe({src:"grab",site:"picker.installGrab",on:!0});let F=t;F.stdin&&typeof F.onStdin=="function"&&(zt=F.onStdin,F.stdin.removeListener("data",F.onStdin),F.stdin.on("data",Ri),process.stdout.write(Kc),process.stdout.write(Vc)),t.on("key",Nt),t.on("mouse",_r),t.on("resize",Ss)},Qs=()=>{process.stdout.write(Ps),process.stdout.write(Fa);let F=t;F.stdin&&zt&&(F.stdin.removeListener("data",Ri),F.stdin.on("data",zt),zt=null),hn=!1,Kn="",t.off("key",Nt),t.off("mouse",_r),t.off("resize",Ss),t.grabInput(!1),oe({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if($r(),process.platform!=="win32"){let F=!1,z=()=>{F&&(F=!1,t.fullscreen(!0),n(),t.hideCursor(),$r(),yt||qo())};Ci=()=>{F||yt||(F=!0,Qs(),t.fullscreen(!1),process.stdout.write(`${$a}${Jc}
242
- `),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(mn,3e3)})}function GT(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+Ta(dt(t),s)}function kl(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",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 XT(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function lv(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 ZT(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[pt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,dt(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Cp,Qa,YT,cv,VT,QT,uv=V(()=>{"use strict";_c();we();es();Qe();Ra();Xf();jd();dl();rp();vp();Sp();Ip();kp();xp();ri();ip();op();Oa();Kr();Ef();Hr();Ap();Cp=2,Qa=4,YT=4,cv=4,VT=20,QT=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],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)"],["^o","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 warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import eE from"wrap-ansi";async function fv(t,e,n,s){Bn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
243
- `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(t),l=Ms(t),f=Math.min(tE,Math.max(20,d-4)),u=Math.max(1,f-1),p=o.flatMap(A=>eE(A,u,{hard:!0,trim:!1}).split(`
244
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,w=y.length+(m?1:0)+4,b=Nn(t,{contentHeight:w,contentWidth:f,title:"Agent failed to start"}),S=b.contentW,k=0;t.moveTo(b.contentX,b.contentY+k),t.brightWhite.bold.noFormat(Xe(` ${i}`,S)),k+=2;for(let A of y)t.moveTo(b.contentX,b.contentY+k),t.brightRed.noFormat(Xe(` ${A}`,S)),k++;return m&&(t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(Xe(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(Xe(` ${a}`,S)),b};return ds({term:t,render:()=>{c()},onKey:(d,l,f,u)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){u("retry");return}if(d==="ESCAPE"){u(r?"back":"cancel");return}d==="CTRL_C"&&u("cancel")}})}var tE,pv=V(()=>{"use strict";ri();tE=100});import{spawn as nE}from"child_process";function sE(t,e){let n="";for(let s=0;s<t.length;s++){let r=t[s];if(r!=="%"||s===t.length-1){n+=r;continue}switch(t[s+1]){case"%":n+="%",s++;break;case"s":n+=e.sessionId,s++;break;case"c":n+=e.cwd,s++;break;case"a":n+=e.agentId,s++;break;case"u":n+=e.baseUrl,s++;break;case"t":n+=e.tokenFile,s++;break;default:n+=r;break}}return n}function rE(t){if(Array.isArray(t))return[...t];let e=t;return e.trim().length===0?[]:e.trim().split(/\s+/)}function iE(t,e){let n=rE(t.command);if(n.length===0)return null;let s=n.map(a=>tt(sE(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function oE(t){let e={stdout:"",stderr:"",bytes:0,truncated:!1},n=(s,r)=>{if(e.truncated)return;let i=t-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>n(s,"stdout"),onStderr:s=>n(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${t} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function hv(t,e,n){let s=iE(t,e);if(s===null){n.notify("hotkey: empty command");return}let r=oE(n.maxOutputBytes??aE),i=n.spawnFn??nE,o;try{o=i(s.program,s.args,{cwd:n.cwd,env:{...n.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){n.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{n.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{n.emitLines(r.onExit(a,c))})}var aE,mv=V(()=>{"use strict";Qe();aE=16*1024});import{spawn as dE,spawnSync as cE}from"child_process";import*as br from"fs";import*as Pp from"path";function gv(t,e){let n=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${lE}1337;SetUserVar=${t}=${n}${uE}`)}function yv(t){if(process.env.TMUX_PANE)try{let e=dE("tmux",t,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function fE(){if(!process.stdin.isTTY)return null;let t=n=>{try{let s=br.readlinkSync(n);return s.startsWith("/dev/")&&s!=="/dev/tty"?Pp.basename(s):null}catch{return null}},e=t("/proc/self/fd/0")??t("/dev/fd/0");if(e)return e;try{let n=cE("tty",[],{encoding:"utf8",timeout:500});if(n.status!==0)return null;let s=n.stdout.trim();return!s.startsWith("/dev/")||s==="/dev/tty"?null:Pp.basename(s)}catch{return null}}function wv(){return Ep===void 0&&(Ep=fE()),Ep}function pE(t){let e=wv();if(e)try{br.mkdirSync(O.ttySessionDir(),{recursive:!0}),br.writeFileSync(O.ttySessionFile(e),t+`
245
- `,{mode:384})}catch{}}function hE(){let t=wv();if(!t)return null;try{let e=br.readFileSync(O.ttySessionFile(t),"utf8").trim();return e.length>0?e:null}catch{return null}}function Mp(t){gv("hydra_session",t),yv(["set-option","-pt",process.env.TMUX_PANE??"","@hydra_session",t]),pE(t)}function bv(){gv("hydra_session",""),yv(["set-option","-put",process.env.TMUX_PANE??"","@hydra_session"])}function vv(){return hE()}var lE,uE,Ep,Sv=V(()=>{"use strict";we();lE="\x1B]",uE="\x07"});function kv(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 Iv(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function xv(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 Av=V(()=>{"use strict"});import{readFileSync as mE}from"fs";import{nanoid as Cv}from"nanoid";import gE from"terminal-kit";import _p from"fs/promises";import ci from"path";function yE(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function wE(t){let e=Il(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function bE(t){let e=new Map,n=[];for(let s of t){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),n.push(r))}return n.map(s=>e.get(s))}function Il(t){if(t.options&&t.options.length>0){let e=t.options.filter(n=>n!==t.defaultAnswer);return t.options.includes(t.defaultAnswer)?[t.defaultAnswer,...e]:[t.defaultAnswer,...t.options]}return[t.defaultAnswer]}function vE(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function SE(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=Il(o.representative),d=e[a]??0,l=n[a]?Fp:c[d]??c[0]??"";return{label:vE(o.representative.question,r),value:l}});return{title:`Open questions (${t.length})`,options:i,selectedIndex:Math.max(0,Math.min(t.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function kE(t,e,n){return t===Fp?{type:"dismiss",method:vb,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:bb,params:{sessionId:n,questionId:e.id,answer:t}}}function IE(t,e,n,s,r){let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(!a||!n[o])continue;let c=s[o]?Fp:Il(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},f=kE(c,l,r);f!==null&&i.push(f)}}return i}function xE(t,e,n,s,r,i,o,a){if(!e||n===null||n.length===0)return{type:"noop"};if(t.type==="char"){if(t.ch==="d"||t.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(t.ch)){let d=parseInt(t.ch,10)-1;if(d<n.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(t.type!=="key")return{type:"noop"};let c=d=>{let l=n[o];if(!l)return{type:"noop"};let f=Il(l.representative);if(f.length===0)return{type:"noop"};let p=((s[o]??0)+d+f.length)%f.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(t.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(n.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:IE(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Rv(t){if(!Array.isArray(t))return;let e=ss({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function $p(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}}function RE(t,e){e.has(t)?e.delete(t):e.add(t)}function TE(){if(Tv)return;Tv=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{oe({src:"uncaughtException",stack:t(e)}),wr(),process.stderr.write(`
240
+ `)})};de();let ce=new AbortController,Te={onKey:Ue=>{if(Ue==="ESCAPE"||Ue==="CTRL_C"){ce.abort(),Ce();return}},onResize:()=>de()};ve(Te),(async()=>{try{let Ue=await ln(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(F.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!Ue.ok)throw new Error(`daemon returned HTTP ${Ue.status}`);let ze=await Ue.json(),at=On(ze),tn=Ef(at,F.status);z=Bc(tn,!1).replace(/\n$/,"").split(`
241
+ `)}catch(Ue){if(ce.signal.aborted)return;ue=`failed to load info: ${Ue.message}`}finally{J=!1,!yt&&ie[ie.length-1]===Te&&de()}})()},Pl=()=>{if(a.length===0){Z="no sessions to search",$e();return}P=new _s({history:[],collapsePastes:!1}),B=[],_=!1,D=0,N=0,vt=0,L=null,K=!1,E="input",A=!0,kr(),Cn(),ve({onKey:(z,ue,J)=>{if(E==="input"){if(K)return;if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="ENTER"||z==="KP_ENTER"){if(Ws().trim().length===0)return;Tn();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&B.length>0){E="results",D=0,N=0,Le(()=>{bi(),bs(0,!0),ki(),t.hideCursor()});return}let de=P.state(),ce=[...de.buffer],Te=de.row,Ue=de.col,ze=null;if(z==="")ze={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")ze={type:"key",name:"alt-underscore"};else if(J?.isCharacter)ze={type:"char",ch:z};else{let Ke=ml(z);Ke!==null&&(ze={type:"key",name:Ke})}if(ze===null){t.moveTo(ut(),Ir());return}P.feed(ze);let at=P.state();if(ce.length===at.buffer.length&&ce.every((Ke,je)=>Ke===at.buffer[je])&&Te===at.row&&Ue===at.col){t.moveTo(ut(),Ir());return}let Vn=ge;kr(),ge!==Vn?Cn():vi();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="CTRL_F"){E="input",id(),ki(),bi();return}if(z==="ENTER"||z==="KP_ENTER"){let ce=B[D];if(!ce)return;let Te=a.find(ze=>ze.sessionId===ce.sessionId);if(!!Te?.importedFromMachine&&!Te.upstreamSessionId){St();let ze={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(ze.agentId=Te.agentId),T(ze);return}(async()=>{let ze=await sv(t,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},et);if(ze==="cancel"){St(),T({kind:"abort"});return}if(ze==="back")return;St();let at={kind:"attach",sessionId:ce.sessionId,readonly:ze==="view"};Te?.agentId!==void 0&&(at.agentId=Te.agentId),T(at)})();return}if(J?.isCharacter&&(z==="n"||z==="N")){let ce=B[D];if(!ce||ce.snippets.length<=1)return;N=(N+1)%ce.snippets.length,bs(D,!0);return}if(J?.isCharacter&&(z==="p"||z==="P")){let ce=B[D];if(!ce||ce.snippets.length<=1)return;N=(N-1+ce.snippets.length)%ce.snippets.length,bs(D,!0);return}let de=ce=>{if(ce<0&&D===0){E="input",Le(()=>{bs(0,!1),ki(),bi()});return}let Te=Math.min(B.length-1,Math.max(0,D+ce));if(Te===D)return;let Ue=D,ze=vt;D=Te,N=0,sd(),vt!==ze?id():(Le(()=>{bs(Ue,!1),bs(D,!0)}),ki())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":de(-1);return;case"DOWN":case"TAB":case"CTRL_N":de(1);return;case"PAGE_UP":de(-ws());return;case"PAGE_DOWN":de(ws());return;case"HOME":de(-D);return;case"END":de(B.length);return}return}},onResize:()=>Cn()})},Ml=(F,z,ue)=>{if(S!=="busy"){if(F==="CTRL_O"){Qe();return}if(F==="CTRL_L"){qo();return}if(S==="rename"&&X){if(F==="ENTER"||F==="KP_ENTER"){let J=X.text.trim();if(J.length===0){S="normal",k=null,X=null,$e();return}Er(J);return}if(F==="ESCAPE"||F==="CTRL_C"){S="normal",k=null,X=null,$e();return}if(X.handleKey(F,ue?.isCharacter===!0)){$e();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(F==="y"||F==="Y")){Mr(S==="confirm-kill"?"kill":"delete");return}if(F==="ESCAPE"||F==="CTRL_C"||F==="ENTER"||F==="KP_ENTER"||ue?.isCharacter&&(F==="n"||F==="N")){S="normal",k=null,$e();return}return}if(Pn(),Je&&(Je=!1,u=0,Le(()=>{Wt(),Xt()})),F==="CTRL_F"&&u!==0){Pl();return}if(u===0&&!h){if(F==="ESCAPE"){En();return}if(F==="ENTER"||F==="KP_ENTER"){let je=He.expandedText(),kt=mt();je.trim().length>0&&(kt.prompt=je),kt.installStatus=Dt(),T(kt);return}if(F==="UP"&&w){let je=Date.now(),kt=je-b;if(b=je,kt<y){fn();return}w=!1}if(F==="DOWN"){let je=He.state(),kt=je.historyIndex!==-1||je.queueIndex!==-1,gt=un.length===0||Ns===un.length-1;if(!kt&&gt&&a.length>0){rt(1);return}}if(F==="PAGE_DOWN"&&(un.length===0||Ns===un.length-1)&&a.length>0){rt(1);return}if(F==="CTRL_P"){a.length>0&&rt(1);return}if(w=!1,F==="TAB"){let je=He.state(),kt=je.buffer[je.row]??"",gt=bl(kt,je.col);if(gt!==null){let Pt=vl(gt.token,r);if(Pt!==null){if(Pt.replacement!==gt.token&&(He.replaceRangeOnCurrentLine(gt.start,je.col,Pt.replacement),Cr()),Pt.candidates.length>1){let Xs=Pt.candidates.join(" ");Q=`${Pt.candidates.length} matches: ${Xs}`,pn()}else zs();fn();return}}}zs();let J=He.state(),de=[...J.buffer],ce=J.row,Te=J.col,Ue=null;if(F==="")Ue={type:"key",name:"ctrl-underscore"};else if(F==="\x1B_"||F==="\x1B")Ue={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)Ue={type:"char",ch:F};else{let je=ml(F);je!==null&&(Ue={type:"key",name:je})}if(Ue===null){fn();return}let ze=He.feed(Ue),at=He.state(),tn=de.length===at.buffer.length&&de.every((je,kt)=>je===at.buffer[kt])&&ce===at.row&&Te===at.col;if(ze.some(je=>je.type==="exit")){En();return}for(let je of ze)je.type==="attachment-request"&&Ii();if(tn){fn();return}let Vn=ls(at.buffer,Ls);if(Fs(Vn,at,Qa).rendered!==bt){Ze();return}Cr();return}if(!h&&ue?.isCharacter&&F==="?"){Yn();return}if(h){if(ue?.isCharacter){m+=F,Rt(),Ze();return}if(F==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Rt(),Ze()):(h=!1,Rt(),Ze());return}if(F==="ESCAPE"||F==="CTRL_C"){h=!1,m="",Rt(),Ze();return}}if(ue?.isCharacter){if(F==="/"){h=!0,m="",Rt(),Ze();return}if(F==="n"||F==="N"){rt(1);return}if(F==="p"||F==="P"){rt(-1);return}if(F==="c"||F==="C"){let J=u>0?a[u-1]:void 0,de=mt();J?.cwd&&(de.cwd=J.cwd),de.installStatus=Dt(),T(de);return}if(F==="q"||F==="Q"){En();return}if(F==="o"||F==="O"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Rt(),ps(J),Ze();return}if(F==="h"||F==="H"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=uv(s.filters.hostFilter,i),Rt(),ps(J),Ze();return}if(F==="i"&&u>0){let J=a[u-1];if(!J)return;Qs(J);return}if(F==="I"){let J=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Rt(),ps(J),Ze();return}if(F==="r"||F==="R"){let J=u>0?a[u-1]?.sessionId:void 0;en(J);return}if(F==="s"||F==="S"){Vs();return}if((F==="v"||F==="V")&&u>0){let J=a[u-1];if(!J)return;let de={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Dt(),T(de);return}if((F==="f"||F==="F")&&u>0){let J=a[u-1];if(!J)return;St();let de={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(de.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(de.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(de.sourceUpstreamSessionId=J.upstreamSessionId),T(de);return}if((F==="k"||F==="K")&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",$e();return}if(F==="t"&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},X=new Bo(J.title??""),S="rename",$e();return}if(F==="T"&&u>0){let J=a[u-1];if(!J)return;Ti({sessionId:J.sessionId});return}if(F==="*"&&u>0){let J=a[u-1];if(!J)return;Pr(J);return}if((F==="d"||F==="D")&&u>0){let J=a[u-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",$e();return}Je=!1,u=0,He.feed({type:"char",ch:F}),Ze();return}switch(F){case"UP":case"SHIFT_TAB":case"CTRL_P":F==="UP"&&(u===1&&(w=!0),b=Date.now()),rt(-1);return;case"DOWN":case"TAB":case"CTRL_N":rt(1);return;case"PAGE_UP":rt(-qe);return;case"PAGE_DOWN":rt(qe);return;case"HOME":rt(1-u);return;case"END":rt(f);return;case"RIGHT":if(Je||u===0)break;case"ENTER":case"KP_ENTER":{if(Je){let ce=He.expandedText(),Te=mt();ce.trim().length>0&&(Te.prompt=ce),Te.installStatus=Dt(),T(Te);return}if(u===0){let ce=mt();ce.installStatus=Dt(),T(ce);return}let J=a[u-1];if(!J){St(),T({kind:"abort"});return}let de={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Dt(),T(de);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":En();return}}};ve({onKey:(F,z,ue)=>Ml(F,z,ue),onResize:()=>{yt||Ze()}});let _r=(F,z)=>{if(yt||ie.length!==1||S!=="normal")return;let ue=F==="MOUSE_MOTION",J=F==="MOUSE_LEFT_BUTTON_PRESSED",de=F==="MOUSE_LEFT_BUTTON_RELEASED",ce=F==="MOUSE_WHEEL_UP",Te=F==="MOUSE_WHEEL_DOWN",Ue=We&&Date.now()-od<ad,ze=!We||Ue;if(J){Rr={x:z?.x??-1,y:z?.y??-1},xi=ze;return}if(ue&&ze)return;let at=de&&Rr!==null&&z?.x===Rr.x&&z?.y===Rr.y,tn=at&&!xi,Vn=at&&xi;if(de&&(Rr=null,xi=!1,!at))return;if(ce||Te){if(a.length===0)return;let Be=ce?-3:3,Mt=Math.max(0,a.length-qe),Zs=Math.min(Mt,Math.max(0,p+Be));if(Zs===p)return;if(p=Zs,u>0){let Pi=u-1;Pi<p?u=p+1:Pi>=p+qe&&(u=p+qe)}Xt();return}if(!ue&&!tn)return;let Ke=z?.y;if(typeof Ke!="number")return;{let Be=z?.x,Mt=Jn!==null&&Ke===Wn()&&typeof Be=="number"&&Be>=Jn.start&&Be<=Jn.end,Zs=Zt!==null&&Ke===Wn()&&typeof Be=="number"&&Be>=Zt.start&&Be<=Zt.end;(Mt!==Ai||Zs!==Ks)&&(Ai=Mt,Ks=Zs,$e(),u===0?(fn(),t.hideCursor(!1)):t.hideCursor(!0))}if(tn&&Jn!==null&&Ke===Wn()){let Be=z?.x;if(typeof Be=="number"&&Be>=Jn.start&&Be<=Jn.end){En();return}}if(tn&&Zt!==null&&Ke===Wn()){let Be=z?.x;if(typeof Be=="number"&&Be>=Zt.start&&Be<=Zt.end){let Mt=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=uv(s.filters.hostFilter,i),Rt(),ps(Mt),Ze();return}}if(Ke>=xn&&Ke<=qn()){let Be=null;if(Ke===xn){let Mt=z?.x;typeof Mt=="number"&&(gs!==null&&Mt>=gs.start&&Mt<=gs.end?Be="agent":Us!==null&&Mt>=Us.start&&Mt<=Us.end&&(Be="cwd"))}if(Be!==Bt&&(Bt=Be,Wt()),tn&&Ke===xn){if(Bt==="agent"){Js();return}if(Bt==="cwd"){Qe();return}}if((tn||Vn)&&u!==0){Je=!1;let Mt=u;u=0,Le(()=>{Xt(),ot(Mt,u)});return}ue&&!Je&&u!==0&&(Je=!0,Le(()=>{Wt(),Xt()}));return}Bt!==null&&(Bt=null,Wt()),Je&&(Je=!1,Le(()=>{Wt(),Xt()}));let kt=Qt()+1,gt=kt+qe-1;if(Ke<kt||Ke>gt)return;let Pt=p+(Ke-kt);if(Pt<0||Pt>=a.length)return;let Xs=a[Pt];if(!Xs)return;let Is=Pt+1;if(ue&&u===0)return;let dd=u===0,_l=u===Is;if(Vn&&u!==Is){let Be=u;u=Is,An(),Le(()=>{Xt(),ot(Be,u)});return}if(Vn)return;if(u!==Is){let Be=u;u=Is,An(),Le(()=>{Xt(),ot(Be,u)})}if(!tn||dd||!_l)return;let Ei={kind:"attach",sessionId:Xs.sessionId};Xs.agentId!==void 0&&(Ei.agentId=Xs.agentId),Ei.installStatus=Dt(),T(Ei)},$r=()=>{t.grabInput({mouse:"motion"}),oe({src:"grab",site:"picker.installGrab",on:!0});let F=t;F.stdin&&typeof F.onStdin=="function"&&(zt=F.onStdin,F.stdin.removeListener("data",F.onStdin),F.stdin.on("data",Ri),process.stdout.write(Kc),process.stdout.write(Vc)),t.on("key",Nt),t.on("mouse",_r),t.on("resize",Ss)},Gs=()=>{process.stdout.write(Ps),process.stdout.write(Fa);let F=t;F.stdin&&zt&&(F.stdin.removeListener("data",Ri),F.stdin.on("data",zt),zt=null),hn=!1,Kn="",t.off("key",Nt),t.off("mouse",_r),t.off("resize",Ss),t.grabInput(!1),oe({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if($r(),process.platform!=="win32"){let F=!1,z=()=>{F&&(F=!1,t.fullscreen(!0),n(),t.hideCursor(),$r(),yt||qo())};Ci=()=>{F||yt||(F=!0,Gs(),t.fullscreen(!1),process.stdout.write(`${$a}${Jc}
242
+ `),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(mn,3e3)})}function nE(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+Ta(dt(t),s)}function kl(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",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 sE(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function uv(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 rE(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[pt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,dt(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Rp,Qa,ZT,lv,eE,tE,fv=V(()=>{"use strict";_c();we();es();Ge();Ra();Zf();jd();dl();ip();Sp();kp();xp();Ip();Ap();ri();op();ap();Oa();Kr();Pf();Hr();Cp();Rp=2,Qa=4,ZT=4,lv=4,eE=20,tE=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],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)"],["^o","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 warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import iE from"wrap-ansi";async function pv(t,e,n,s){Bn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
243
+ `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(t),l=Ms(t),f=Math.min(oE,Math.max(20,d-4)),u=Math.max(1,f-1),p=o.flatMap(A=>iE(A,u,{hard:!0,trim:!1}).split(`
244
+ `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,w=y.length+(m?1:0)+4,b=Nn(t,{contentHeight:w,contentWidth:f,title:"Agent failed to start"}),S=b.contentW,k=0;t.moveTo(b.contentX,b.contentY+k),t.brightWhite.bold.noFormat(Xe(` ${i}`,S)),k+=2;for(let A of y)t.moveTo(b.contentX,b.contentY+k),t.brightRed.noFormat(Xe(` ${A}`,S)),k++;return m&&(t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(Xe(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(Xe(` ${a}`,S)),b};return ds({term:t,render:()=>{c()},onKey:(d,l,f,u)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){u("retry");return}if(d==="ESCAPE"){u(r?"back":"cancel");return}d==="CTRL_C"&&u("cancel")}})}var oE,hv=V(()=>{"use strict";ri();oE=100});import{spawn as aE}from"child_process";function dE(t,e){let n="";for(let s=0;s<t.length;s++){let r=t[s];if(r!=="%"||s===t.length-1){n+=r;continue}switch(t[s+1]){case"%":n+="%",s++;break;case"s":n+=e.sessionId,s++;break;case"c":n+=e.cwd,s++;break;case"a":n+=e.agentId,s++;break;case"u":n+=e.baseUrl,s++;break;case"t":n+=e.tokenFile,s++;break;default:n+=r;break}}return n}function cE(t){if(Array.isArray(t))return[...t];let e=t;return e.trim().length===0?[]:e.trim().split(/\s+/)}function lE(t,e){let n=cE(t.command);if(n.length===0)return null;let s=n.map(a=>tt(dE(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function uE(t){let e={stdout:"",stderr:"",bytes:0,truncated:!1},n=(s,r)=>{if(e.truncated)return;let i=t-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>n(s,"stdout"),onStderr:s=>n(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${t} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function mv(t,e,n){let s=lE(t,e);if(s===null){n.notify("hotkey: empty command");return}let r=uE(n.maxOutputBytes??fE),i=n.spawnFn??aE,o;try{o=i(s.program,s.args,{cwd:n.cwd,env:{...n.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){n.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{n.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{n.emitLines(r.onExit(a,c))})}var fE,gv=V(()=>{"use strict";Ge();fE=16*1024});import{spawn as pE,spawnSync as hE}from"child_process";import*as Os from"fs";import*as Il from"path";function yv(t,e){let n=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${mE}1337;SetUserVar=${t}=${n}${gE}`)}function wv(t){if(process.env.TMUX_PANE)try{let e=pE("tmux",t,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function yE(){if(!process.stdin.isTTY)return null;let t=n=>{try{let s=Os.readlinkSync(n);return s.startsWith("/dev/")&&s!=="/dev/tty"?Il.basename(s):null}catch{return null}},e=t("/proc/self/fd/0")??t("/dev/fd/0");if(e)return e;try{let n=hE("tty",[],{encoding:"utf8",timeout:500});if(n.status!==0)return null;let s=n.stdout.trim();return!s.startsWith("/dev/")||s==="/dev/tty"?null:Il.basename(s)}catch{return null}}function bv(){return Pp===void 0&&(Pp=yE()),Pp}function wE(t){let e=bv();if(e)try{Os.mkdirSync(O.ttySessionDir(),{recursive:!0});let n=`${process.pid}:${process.ppid}:${t}
245
+ `;Os.writeFileSync(O.ttySessionFile(e),n,{mode:384})}catch{}}function bE(t){let e=t.trim();if(e.length===0)return null;if(!e.includes(":"))return{hydraPid:0,parentPid:0,sessionId:e};let n=e.split(":");if(n.length<3)return null;let s=Number.parseInt(n[0],10),r=Number.parseInt(n[1],10),i=n.slice(2).join(":");return!Number.isFinite(s)||!Number.isFinite(r)||i.length===0?null:{hydraPid:s,parentPid:r,sessionId:i}}function vE(){let t=bv();if(!t)return null;try{let e=Os.readFileSync(O.ttySessionFile(t),"utf8");return bE(e)}catch{return null}}function SE(){let t=vE();return!t||t.parentPid>0&&t.parentPid!==process.ppid?null:t.sessionId}function Mp(t){yv("hydra_session",t),wv(["set-option","-pt",process.env.TMUX_PANE??"","@hydra_session",t]),wE(t)}function vv(){yv("hydra_session",""),wv(["set-option","-put",process.env.TMUX_PANE??"","@hydra_session"])}function Sv(){return SE()}var mE,gE,Pp,kv=V(()=>{"use strict";we();mE="\x1B]",gE="\x07"});function Iv(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 xv(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Av(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 Cv=V(()=>{"use strict"});import{readFileSync as kE}from"fs";import{nanoid as Rv}from"nanoid";import IE from"terminal-kit";import _p from"fs/promises";import ci from"path";function xE(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function AE(t){let e=xl(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function CE(t){let e=new Map,n=[];for(let s of t){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),n.push(r))}return n.map(s=>e.get(s))}function xl(t){if(t.options&&t.options.length>0){let e=t.options.filter(n=>n!==t.defaultAnswer);return t.options.includes(t.defaultAnswer)?[t.defaultAnswer,...e]:[t.defaultAnswer,...t.options]}return[t.defaultAnswer]}function RE(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function TE(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=xl(o.representative),d=e[a]??0,l=n[a]?Fp:c[d]??c[0]??"";return{label:RE(o.representative.question,r),value:l}});return{title:`Open questions (${t.length})`,options:i,selectedIndex:Math.max(0,Math.min(t.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function EE(t,e,n){return t===Fp?{type:"dismiss",method:Sb,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:vb,params:{sessionId:n,questionId:e.id,answer:t}}}function PE(t,e,n,s,r){let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(!a||!n[o])continue;let c=s[o]?Fp:xl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},f=EE(c,l,r);f!==null&&i.push(f)}}return i}function ME(t,e,n,s,r,i,o,a){if(!e||n===null||n.length===0)return{type:"noop"};if(t.type==="char"){if(t.ch==="d"||t.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(t.ch)){let d=parseInt(t.ch,10)-1;if(d<n.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(t.type!=="key")return{type:"noop"};let c=d=>{let l=n[o];if(!l)return{type:"noop"};let f=xl(l.representative);if(f.length===0)return{type:"noop"};let p=((s[o]??0)+d+f.length)%f.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(t.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(n.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:PE(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Tv(t){if(!Array.isArray(t))return;let e=ss({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function $p(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}}function FE(t,e){e.has(t)?e.delete(t):e.add(t)}function OE(){if(Ev)return;Ev=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{oe({src:"uncaughtException",stack:t(e)}),br(),process.stderr.write(`
246
246
  uncaught: ${t(e)}
247
- `),process.exit(1)}),process.on("unhandledRejection",e=>{oe({src:"unhandledRejection",stack:t(e)}),wr(),process.stderr.write(`
247
+ `),process.exit(1)}),process.on("unhandledRejection",e=>{oe({src:"unhandledRejection",stack:t(e)}),br(),process.stderr.write(`
248
248
  unhandled rejection: ${t(e)}
249
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&oe({src:"process-exit",code:e})})}async function Mv(t){TE();let e=await Ae(),n=t.target??await Ht(e);if(bh(e.tui.logMaxBytes),n.isLocal&&!t.target&&await cr(e),t.agentId)try{let p=await Gr(n),h=Ma(t.agentId,p.map(m=>m.id));h!==void 0&&h!==t.agentId&&(t.agentId=h)}catch{}let s=gE.terminal;Zb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Yp(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Rp(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(wr(),s.fullscreen(!1),a=!1,process.stdout.write(`
250
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await PE(s,e,n,f,r,i,o)}finally{bv(),d(),process.off("exit",l)}let u=await Na();if(u&&process.stderr.write(`\u2728 ${Da(u)}
251
- `),process.stdout.isTTY){let p=await Yr(e);if(p?.version!==void 0){let h=p.version!==be,m=ir(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let w=h?`daemon ${p.version} \u2260 cli ${be}`:"config changed since daemon started",b=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(b(`! ${w} \u2014 run \`${Gn()} daemon restart\` to apply.`)+`
249
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&oe({src:"process-exit",code:e})})}async function _v(t){OE();let e=await Ae(),n=t.target??await Ht(e);if(bh(e.tui.logMaxBytes),n.isLocal&&!t.target&&await lr(e),t.agentId)try{let p=await Gr(n),h=Ma(t.agentId,p.map(m=>m.id));h!==void 0&&h!==t.agentId&&(t.agentId=h)}catch{}let s=IE.terminal;ev(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Yp(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Tp(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(br(),s.fullscreen(!1),a=!1,process.stdout.write(`
250
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await BE(s,e,n,f,r,i,o)}finally{vv(),d(),process.off("exit",l)}let u=await Na();if(u&&process.stderr.write(`\u2728 ${Da(u)}
251
+ `),process.stdout.isTTY){let p=await Yr(e);if(p?.version!==void 0){let h=p.version!==be,m=or(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let w=h?`daemon ${p.version} \u2260 cli ${be}`:"config changed since daemon started",b=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(b(`! ${w} \u2014 run \`${Gn()} daemon restart\` to apply.`)+`
252
252
  `)}}}if(r.sessionId&&process.stdout.isTTY){let p=pt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Gn()} --session ${p}${h}
253
- `)}}function EE(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let _=Math.max(0,c-a),D=e.slice(_),N=[];for(let L=0;L<_;L++){let K=e[L];if(K===void 0)continue;let X=n.get(K);X&&!If(X.status)&&N.push(K)}l=[...N,...D]}let f=c-l.length,u=r===null,p=r??Date.now(),h=p-s,m=!u&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",w=y?`amended \xB7 ${as(h)}`:`stopped (${m}) \xB7 ${as(h)}`,b;if(c===0)m!==null?b=w:b=u?`thinking \xB7 ${as(h)}`:`thought \xB7 ${as(h)}`;else{let _=c===1?"tool":"tools",D=m!==null?w:u?as(h):`took ${as(h)}`,N=[`${c} ${_}`,D];u&&d&&f>0&&N.push(`${f} hidden`),b=N.join(" \xB7 ")}let S=c===0&&u,k=y?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],B=[null];for(let _ of l){let D=n.get(_);if(D){let N=Pa(D,p);for(let L of N)L.hoverSubKey=_;if(P.push(...N),B.push(...N.map(()=>_)),o?.has(_)){let L=Vy(D);for(let K of L)K.hoverSubKey=_;P.push(...L),B.push(...L.map(()=>_))}}}return{lines:P,rowOwners:B}}async function PE(t,e,n,s,r,i,o){let a=await ME(t,e,n,s,o,i);if(!a)return t.grabInput(!1),oe({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=s.installStatus;s.installStatus&&delete s.installStatus;let l=a.installStatus??d??Sl(c,dv(t));l.write(c);let f=n.isLocal?async()=>(await Ht(await Ae())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],p=null,h=null,m=new _o({url:f,subprotocols:u,onConnect:async g=>{g||p&&await p()},onDisconnect:g=>{h&&h(g)},log:g=>oe({src:"resilient-ws",line:g})}),y=new Kt(m);await m.start(),y.onNotification(Rd,g=>{let v=tm.safeParse(g);v.success&&l.applyProgress(v.data)});let w=[],b=null,S=!1,k=!1,A=(g,v)=>{g&&(b?b(g,v):w.push({event:g,rawUpdate:v}))},E,P=g=>{g!==E&&(E=g,g!==void 0&&x.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},B=null,_=null,D=!1,N=0,L=0,K=!1,X=!1,Z,Q=null,fe=null,Me=null,In=null,De=()=>setInterval(()=>{if(Q===null||G===null)return;let g=In===null?0:Date.now()-In;G.setBanner({elapsedMs:Date.now()-Q,stalled:g>=AE}),gt()},1e3),us=!1,ke=g=>{let v=L;L=Math.max(0,L+g);let I=typeof G<"u"&&G!==null;v===0&&L>0?(X=!1,Q=Date.now(),In=Date.now(),xe?.setTurnRunning(!0),I&&G.setBanner({status:"busy",elapsedMs:0,stalled:!1}),fe===null&&I&&(fe=De())):v>0&&L===0?(X=!1,Q=null,In=null,xe?.setTurnRunning(!1),fe!==null&&(clearInterval(fe),fe=null),I&&G.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&X&&(X=!1,I&&G.setBanner({status:"busy",stalled:!1}))},G=null,xe=null,je,Yt=null,Os=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),un=g=>{let{update:v}=g??{},I=ss(v,{cwd:qe});_E(v,I),In=Date.now();let R=v?.sessionUpdate;if(typeof R=="string"&&!Os.has(R)){let C=v??{};typeof C.messageId=="string"&&(je=C.messageId)}if(R==="prompt_received"?ke(1):I?.kind==="turn-complete"&&(ke(-1),D=!0),R==="permission_resolved"){Do(v);return}if(R==="hydra_compaction"){No(v);return}if(R==="clarifier_question_asked"){let C=v,$=typeof C.question?.question=="string"?C.question.question:"",W=$.length>50?$.slice(0,49)+"\u2026":$;x.notify(W?`new question: ${W} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(A(I,v),td(v))};y.onNotification("session/update",g=>{if(!S){if(Yt!==null){Yt.push(g);return}un(g)}}),y.onNotification("hydra-acp/session/closed",()=>{if(S)return;L>0&&ke(-L),typeof G<"u"&&G!==null&&G.setBanner({status:"cold",elapsedMs:void 0})});let bt=new Map,Ls=200,Bs=0,fs=!1,li=4e3;y.onNotification("hydra-acp/prompt_queue/added",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let R=v.messageId,C=v.prompt,$=setTimeout(()=>{S||(bt.delete(R),Y.set(R,U(R,C)),G&&xe&&et())},Ls);bt.set(R,$)}else Y.set(v.messageId,U(v.messageId,v.prompt)),G&&xe&&et();if(Ds!==void 0&&v.originator?.clientId===Ds){let R=re.shift();R&&(R.messageId=v.messageId,ie.set(v.messageId,R))}}),y.onNotification("hydra-acp/prompt_queue/updated",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string"||!Y.has(v.messageId))return;Y.set(v.messageId,U(v.messageId,v.prompt));let I=ie.get(v.messageId);if(I){let R=Array.isArray(v.prompt)?v.prompt:[],C="",$=[];for(let W of R){if(!W||typeof W!="object")continue;let H=W;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&typeof H.data=="string"&&typeof H.mimeType=="string"&&$.push({data:H.data,mimeType:H.mimeType,sizeBytes:Math.floor(H.data.length*3/4)})}I.text=C,I.attachments=$}G&&xe&&et()}),y.onNotification("hydra-acp/prompt_queue/removed",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(Z=v.messageId);let I=bt.get(v.messageId);I!==void 0&&(clearTimeout(I),bt.delete(v.messageId)),Y.delete(v.messageId)&&G&&xe&&et();let C=ie.get(v.messageId);C&&(ie.delete(v.messageId),v.reason==="started"&&(C.flushed=!0,A({kind:"user-text",text:C.displayText,attachments:C.attachments}),Ce=C))}),y.onNotification("hydra-acp/cancel_failed",g=>{if(S)return;let v=g??{};if(!(typeof G<"u"&&G!==null))return;Bs=Date.now(),fs=!0;let R=typeof v.code=="number"?` (${v.code})`:"",C=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${R}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),y.onNotification("hydra-acp/prompt/amended",g=>{if(S)return;let v=g??{};if(typeof v.cancelledMessageId!="string")return;let I=v.cancelledMessageId;ve.add(I),Ce!==null&&Ce.messageId!==void 0&&Ce.messageId===I&&(A({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Ce=null,ve.delete(I))});let No=g=>{let v=g??{},I=typeof v.phase=="string"?v.phase:void 0;if(I==="started")x.setCompactionIndicator("compacting...");else if(I==="iteration")x.setCompactionIndicator("compacting...");else if(I==="deferred")x.setCompactionIndicator("compaction queued (waiting for idle)");else if(I==="swapped")x.setCompactionIndicator(null),x.notify("compacted",2e3);else if(I==="rolled_back")x.setCompactionIndicator(null),x.notify("rolled back",2e3);else if(I==="failed"){x.setCompactionIndicator(null);let R=typeof v.error=="string"?v.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;x.notify(`compaction failed: ${C}`,5e3)}},xn=()=>{Me===null&&(Me=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState===void 0?(x.setSynthesisIndicator(null),x.notify("synthesis complete",2e3),Me!==null&&(clearInterval(Me),Me=null)):v.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3),Me!==null&&(clearInterval(Me),Me=null))}catch{}},5e3))},ed=()=>{Me!==null&&(clearInterval(Me),Me=null)},Do=g=>{let v=g??{},I=typeof v.toolCallId=="string"?v.toolCallId:void 0,R;v.outcome&&typeof v.outcome=="object"?R=v.outcome:typeof v.chosenOptionId=="string"&&(R={kind:"selected",optionId:v.chosenOptionId}),Ns(I,R?{outcome:R}:void 0)},ge=null,Ns=(g,v)=>{if(!ge||ge.toolCallId&&g&&ge.toolCallId!==g)return;let I=ge.resolve;ge=null,x.setPermissionPrompt(null),I(v??{outcome:{outcome:"cancelled"}})},td=g=>{if(!ge?.toolCallId)return;let v=g??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===ge.toolCallId&&(!v.status||v.status==="pending"||Ns(v.toolCallId,void 0))},ui=()=>{if(!ge){x.setPermissionPrompt(null);return}x.setPermissionPrompt({title:ge.title,detail:ge.detail,options:ge.options.map(g=>({label:g.name})),selectedIndex:ge.selectedIndex})},fi=g=>{if(!ge)return;let{options:v,resolve:I}=ge;if(ge=null,x.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};y.onRequest("session/request_permission",async g=>{if(S)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ii(g);let v=g??{},R=(Array.isArray(v.options)?v.options:[]).map(ee=>({optionId:ee.optionId,name:Pe(ee.name??""),...ee.kind!==void 0?{kind:ee.kind}:{}})),C=v.toolCall?.title??v.toolCall?.name??"tool",$=Pe(C),W=Pe(Vw(Yw(g))),H=v.toolCall?.toolCallId;return R.length===0?(x.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${$} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(ee=>{ge={title:$,detail:W,options:R,selectedIndex:0,resolve:ee,toolCallId:H},ui()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let pi,Rt,ps=!0,An=!1;try{let g=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}});Rt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ps=!1),An=rn(g?._meta??void 0).prompt?.amending===!0}catch{}let he=a.sessionId,Ke=a.agentId,qe=a.cwd,yt,Ds,hs,ms,hi,Hs,gs,Bt,mi,Un,Ho=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let v={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Ft]:g}}:{}},I;try{I=await Dw({request:()=>y.request("session/new",v),showBanner:($,W,H)=>Hw(t,$,W,H,{authenticate:ee=>y.request("authenticate",{methodId:ee})}),resolveOnboarding:async $=>{if($)try{return(await Gr(n)).find(ee=>ee.id===$)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch($){t.grabInput(!1),oe({src:"grab",site:"runSession.session-new-failed",on:!1}),m.close().catch(()=>{});let W=$ instanceof Error?$.message:String($);oe({src:"session-new-failed",agentId:s.agentId??null,message:W});let H=await fv(t,s.agentId,W,{canGoBack:!s.forceNew});if(H==="cancel")return null;let ee={...s};return delete ee.sessionId,delete ee.resume,H==="retry"?ee.forceNew=!0:(delete ee.forceNew,delete ee.agentId),ee}if(I.kind==="cancel")return t.grabInput(!1),oe({src:"grab",site:"runSession.auth-cancel",on:!1}),m.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),oe({src:"grab",site:"runSession.auth-back",on:!1}),m.close().catch(()=>{});let $={...s};return delete $.sessionId,delete $.forceNew,delete $.resume,delete $.agentId,$}let R=I.result;l.write(c),he=R.sessionId,Mp(he),r.sessionId=he,r.readonly=!1;let C=rn(R._meta??void 0);C.clientId&&(Ds=C.clientId),pi=C.upstreamSessionId,C.agentId&&(Ke=C.agentId),C.cwd&&(qe=C.cwd),C.title&&(yt=C.title),hs=C.currentModel,ms=C.currentMode,mi=C.currentUsage,Un=C.turnStartedAt,C.availableCommands&&(hi=oc(C.availableCommands)),C.availableModes&&(Hs=C.availableModes),gs=Rv(R.configOptions),Bt=C.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let v=await y.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:be},...Object.keys(g).length>0?{_meta:{[Ft]:g}}:{}});he=v.sessionId,Mp(he),v.clientId&&(Ds=v.clientId),r.sessionId=he,r.readonly=s.readonly===!0;let I=rn(v._meta??void 0);Ho=I.resurrected===!0,pi=I.upstreamSessionId,I.agentId&&(Ke=I.agentId),I.cwd&&(qe=I.cwd),I.title&&(yt=I.title),hs=I.currentModel,ms=I.currentMode,mi=I.currentUsage,Un=I.turnStartedAt,I.availableCommands&&(hi=oc(I.availableCommands)),I.availableModes&&(Hs=I.availableModes),gs=Rv(v.configOptions),Bt=I.queue}let Us=O.tuiHistoryFile(he),gi=O.globalTuiHistoryFile(),Tt=await la(Us).catch(()=>[]),Vt=await la(gi).catch(()=>[]);Vt.length>e.tui.promptHistoryMaxEntries&&(Vt=Vt.slice(Vt.length-e.tui.promptHistoryMaxEntries));let jn=[...Tt],Re=new _s({history:Ud(Vt,jn)});xe=Re;let nd=!1,$e=(g,v)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let R=(v??g).replace(/\n+$/,""),C=ua(Tt,I),$=C!==Tt;Tt=C,jn=ua(jn,R);let W=ua(Vt,I,e.tui.promptHistoryMaxEntries),H=W!==Vt;Vt=W,Re.setHistory(Ud(Vt,jn)),$&&zr(Us,Tt).catch(()=>{}),H&&Zm(gi,I).catch(()=>{})};L>0&&Re.setTurnRunning(!0);let Et=null,qn=null;Qb(Gb(e.tui.ambiguousWidth,process.env)),Gy(e.tui.diffContextLines);let Qt=!1,x,Wn=()=>{Qt&&(Qt=!1,x.start())},fn=()=>{Qt||(Qt=!0,x.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Wn);let js=null,yi=null;x=new hl({term:t,dispatcher:Re,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:e.tui.openFileCommand,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?fn:void 0,onBlockClick:(g,v)=>{Qv(g,v)},onBlockDoubleClick:(g,v)=>Vv(g,v),onHydraLinkClick:g=>(Ci(g),!0),onBlockVisible:g=>{Kv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let v=Mr.get(g);if(v!==void 0&&v.length>0)return new Set(v);let I=x.contiguousRun(g,new Set(Ys.keys()));return I.length>0?new Set(I):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){js=x.bannerHitAt(g.x,g.y),yi=js?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let I=yi,R=js;if(yi=null,js=null,R!==null&&I!==null&&I.x===g.x&&I.y===g.y&&x.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Nt(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&$p(C))return;Tr(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let v={type:"attachment-request",source:"primary"};s.readonly===!0&&$p(v)||Tr(v)},onKey:g=>{for(let v of g){if(K&&ki(v)){v.type==="key"&&oe({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(ge&&rd(v)){v.type==="key"&&oe({src:"key-swallowed",site:"permission",name:v.name});continue}if(id(v)){v.type==="key"&&oe({src:"key-swallowed",site:"help",name:v.name});continue}if(Jn(v)){v.type==="key"&&oe({src:"key-swallowed",site:"questions",name:v.name});continue}if(xi(v)){v.type==="key"&&oe({src:"key-swallowed",site:"options",name:v.name});continue}if(sd(v)){v.type==="key"&&oe({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Cl(v)){v.type==="key"&&oe({src:"key-swallowed",site:"completion",name:v.name});continue}if(ws(v)){v.type==="key"&&oe({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&x.isScrolledBack()){x.scrollToBottom();continue}if(v.type==="attachment-paths"){Ri(v.paths);continue}if(v.type==="key"&&kr(v.name)){oe({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let I=Re.feed(v);for(let R of I)s.readonly===!0&&$p(R)||Tr(R)}qt(),x.setBannerSearchIndicator(Re.state().historySearchQuery),x.setAttachments(Re.state().attachments),x.refreshPrompt()}}),G=x,x.setStickyBottomKey("plan");let Uo=[{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:"/session",description:"Switch session: /session <id|next|prev> (no arg opens 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:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],Sr=hi??[],zn=Hs??[],jo=gs??[],wi=()=>jo.find(g=>g.id==="agent"),Ze=()=>{let g=new Set,v=[];for(let I of[...Uo,...Sr])g.has(I.name)||(g.add(I.name),v.push(I));return v},qo=()=>{let g=Re.state().buffer,v=g[0]??"";if(!v.startsWith("/"))return[];if(g.length>1)return[];let I=v.indexOf(" "),R=I===-1?v:v.slice(0,I);if(R.lastIndexOf("/")>0)return[];let C=Ze().filter($=>$.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},ys=[],qt=()=>{let g=qo();if(g.length>0){ys=[],x.setCompletions(g);return}x.setCompletions(ys)},Cl=g=>{if(g.type!=="key"||g.name!=="tab")return ys.length>0&&(ys=[]),!1;let v=qo();if(x.isOverlayOpen()&&v.length===0)return x.toggleFocusedPane(),!0;if(v.length>0){ys=[];let I=Re.state().buffer[0]??"",R=sv({matches:v.map(C=>C.name),firstLine:I});return R===null||Re.replaceFirstLine(R),!0}return vt()},vt=()=>{let g=Re.state(),v=g.buffer[g.row]??"",I=bl(v,g.col);if(I===null)return!1;let R=vl(I.token,qe);return R===null?!1:(R.replacement!==I.token&&Re.replaceRangeOnCurrentLine(I.start,g.col,R.replacement),ys=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},ws=g=>!x.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay(),!0),sd=g=>{if(!x.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&x.isScrolledBack()?(x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let v=x.scrollbackSearchTerm()+g.ch;return x.updateScrollbackSearchTerm(v),!0}if(g.type==="paste"){let v=x.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return x.updateScrollbackSearchTerm(v),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return x.advanceScrollbackSearch(),!0;case"ctrl-s":return x.retreatScrollbackSearch(),!0;case"backspace":{let v=x.scrollbackSearchTerm();return v.length===0?x.cancelScrollbackSearch():x.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return x.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return x.cancelScrollbackSearch(),!0;default:return!0}return!0},rd=g=>{if(!ge)return!1;let v=ge.options;if(g.type==="key")switch(g.name){case"up":return ge.selectedIndex=Math.max(0,ge.selectedIndex-1),ui(),!0;case"down":return ge.selectedIndex=Math.min(v.length-1,ge.selectedIndex+1),ui(),!0;case"enter":{let I=v[ge.selectedIndex];return I&&fi(I.optionId),!0}case"escape":case"ctrl-c":return fi(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,R=v[I];return R&&fi(R.optionId),!0}return!0},kr=g=>{let v=e.tui.hotkeys[g];return v?(hv(v,{sessionId:he,cwd:qe,agentId:Ke||Rt||"",baseUrl:n.baseUrl,tokenFile:O.authToken()},{notify:I=>x.notify(I),cwd:qe,emitLines:I=>{x.appendLines(I.map(R=>{let C;switch(R.style){case"meta":C="dim";break;case"stderr":case"error":C="tool-status-fail";break;default:C="info"}return{prefix:" ",body:R.text,bodyStyle:C}}))}}),!0):!1},Wo=Ke||Rt||"?",Gt={...mi??{}};l.finalize(),x.start({skipFullscreen:!0}),x.setHideThoughts(!i.showThoughts),x.setSessionbar({agent:Wo,cwd:qe,sessionId:he,title:yt,model:hs,usage:{...Gt}}),ms&&x.setBanner({currentMode:ms}),Na().then(g=>{g&&x.notify(`\u2728 ${Da(g)}`,3e4)}).catch(()=>{});let ut=null,Ir=new Promise(g=>{ut=g}),bi=()=>{y.notify("session/cancel",{sessionId:he}).catch(()=>{})},vi=()=>{G!==null&&L===1&&(X=!0,G.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},xr=()=>{if(Et){Et.cancel(),vi();return}if(L>0){bi(),vi();return}Si()},Si=()=>{Zt(0)},zo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",v]],...CE]},Ko=()=>{if(x.isHelpPromptActive()){x.setHelpPrompt(null);return}x.setHelpPrompt({title:"Hotkeys",entries:zo(),hint:"any key dismisses \xB7 /help lists commands"})},Ar=()=>{K=!1,x.setCompactionPrompt(null),x.setCompactionIndicator("compaction queued...");let g=he;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},Cn=()=>{K=!1,x.setCompactionPrompt(null)},bs=g=>{let v=x.compactionPromptSpec();if(!v)return;let I=v.options.length;if(I===0)return;let R=((v.selectedIndex+g)%I+I)%I;R!==v.selectedIndex&&x.setCompactionPrompt({...v,selectedIndex:R})},ki=g=>{if(!K)return!1;if(g.type==="key"){if(g.name==="escape")return Cn(),!0;if(g.name==="up")return bs(-1),!0;if(g.name==="down")return bs(1),!0;if(g.name==="enter"){let v=x.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Ar():Cn(),!0}}if(g.type==="char"){let v=g.ch.toLowerCase();if(v==="y"||v==="1")return Ar(),!0;if(v==="n"||v==="2")return Cn(),!0}return!0},id=g=>x.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",x.setHelpPrompt(null),!0):!1,qs=["tools","plan","thoughts","diffs","mouse","enter"],Rn=0,Tn=null,vs=[],Wt=[],pn=[],Ws=0,Cr=g=>{switch(g){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}},Ii=g=>{switch(g){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"}},Rl=()=>({title:"Session options",options:qs.map(g=>({label:Ii(g),value:Cr(g)})),selectedIndex:Rn}),Xt=()=>{x.isOptionsPromptActive()&&Tn===null&&x.setOptionsPrompt(Rl())},Tl=()=>{if(x.isOptionsPromptActive()){x.setOptionsPrompt(null);return}Rn=0,x.setOptionsPrompt(Rl())},hn=()=>{if(Tn===null)return;let g=SE(Tn,vs,pn,Ws);x.setOptionsPrompt(g)},Kn=()=>{Tn=null,vs=[],Wt=[],pn=[],Ws=0,x.setOptionsPrompt(null)},od=async()=>{if(Tn!==null){Kn();return}try{let v=await y.request(wb,{sessionId:he}),I=yE(v.questions??[]);if(I.length===0){x.notify("no open questions");return}let R=bE(I);Tn=R,Ws=0,vs=R.map(C=>wE(C.representative)),Wt=R.map(()=>!1),pn=R.map(()=>!1),hn()}catch(g){x.notify("clarifier unavailable"),oe({src:"questions",step:"list_failed",error:g.message})}},ad=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Er.clear(),Ti.clear(),Gs();break;case"plan":i.planExpanded=!i.planExpanded,Vs=null,$r();break;case"thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",mn.clear(),Jv();break;case"mouse":{let v=!x.isMouseEnabled();x.setMouseEnabled(v),i.mouseEnabled=v;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Xt()},Rr=g=>{(async()=>{try{switch(g){case"tools":case"plan":x.notify(`${Ii(g)} is session-only \u2014 not saved`);return;case"thoughts":await Qo("showThoughts",i.showThoughts);break;case"diffs":await Qo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Qo("mouse",i.mouseEnabled);break;case"enter":await Qo("defaultEnterAction",i.defaultEnterAction);break}x.notify(`saved default: ${Ii(g)} ${Cr(g)}`)}catch(v){x.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},xi=g=>{if(Tn!==null||!x.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Rn=Math.max(0,Rn-1),Xt(),!0;case"down":return Rn=Math.min(qs.length-1,Rn+1),Xt(),!0;case"enter":{let v=qs[Rn];return v&&ad(v),!0}case"ctrl-o":case"escape":case"ctrl-c":return x.setOptionsPrompt(null),!0;case"ctrl-d":return x.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let v=parseInt(g.ch,10)-1,I=qs[v];return I&&(Rn=v,ad(I)),!0}if(g.ch==="s"||g.ch==="S"){let v=qs[Rn];return v&&Rr(v),!0}}return!0},Jn=g=>{if(Tn===null)return!1;let v=xE(g,!0,Tn,vs,Wt,pn,Ws,he);switch(v.type){case"noop":return!0;case"row":return Ws=v.selectedRow,hn(),!0;case"cycle":return vs[v.selectedRow]=v.newValueIndex,Wt[v.selectedRow]=!0,pn[v.selectedRow]=!1,hn(),!0;case"dismiss-toggle":{let I=v.selectedRow;return pn[I]?(pn[I]=!1,Wt[I]=!1):(pn[I]=!0,Wt[I]=!0),hn(),!0}case"discard":return Kn(),!0;case"save":{let I=v.dispatches;return Kn(),I.length===0||(async()=>{let R=0,C=0,$=0;for(let H of I)try{await y.request(H.method,H.params),H.type==="dismiss"?C++:R++}catch(ee){$++,oe({src:"questions",step:"dispatch_failed",method:H.method,error:ee.message})}let W=[];R>0&&W.push(`${R} answered`),C>0&&W.push(`${C} dismissed`),$>0&&W.push(`${$} failed`),W.length>0&&x.notify(`clarifier: ${W.join(", ")}`)})(),!0}}return!1},Ai=()=>{S=!0,B?(B.cancel(),B=null,_=null):_!==null&&(os(n,_).catch(()=>{}),_=null),process.off("SIGINT",xr),process.platform!=="win32"&&process.off("SIGCONT",Wn),fe!==null&&(clearInterval(fe),fe=null),Me!==null&&(clearInterval(Me),Me=null);for(let g of bt.values())clearTimeout(g);bt.clear(),x.clearWindowTitle(),x.stop({keepFullscreen:!0}),zr(Us,Tt).catch(()=>{}),m.close().catch(()=>{})},Zt=(g=0)=>{Ai(),ut&&(ut(null),ut=null),g!==0&&process.exit(g)},zs=async()=>{if(oe({src:"switch-session",step:"entered",finishSessionNull:ut===null}),!ut)return;B?(B.cancel(),B=null,_=null):_!==null&&(os(n,_).catch(()=>{}),_=null),ed(),x.setSynthesisIndicator(null);let g=Re.state().buffer.join(`
254
- `);g.replace(/\s+$/,"").length>0&&$e(g),x.pauseRepaint(),x.stop({keepFullscreen:!0}),zr(Us,Tt).catch(()=>{});let v=!1;try{let I=null,R=null;for(;I===null;){let H=await Ln(n,{includeNonInteractive:!0}),ee=s.agentId??i.lastChosenAgent??e.defaultAgent,Ee=ee?e.defaultModels?.[ee]:void 0,Se=[];try{Se=await Gr(n)}catch{}let ae=await Tp(t,{cwd:qe,sessions:H,config:e,target:n,currentSessionId:he,prefs:o,...ee?{composerAgentId:ee}:{},...Ee?{composerModel:Ee}:{},...Se.length>0?{availableAgents:Se}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){v=!0,Zt(0);return}if(ae.kind==="new"){I={choice:ae,sessions:H};break}if(ae.kind==="fork"){let Mn=await Fv(t,n,ae,H);if(Mn.kind==="cancel")return;if(Mn.kind==="back")continue;I={choice:{kind:"attach",sessionId:Mn.ctx.sessionId,...Mn.ctx.agentId?{agentId:Mn.ctx.agentId}:{}},sessions:H},R={readonly:!1,cwd:Mn.ctx.cwd},Mn.ctx.resumeHint!==void 0&&(R.resumeHint=Mn.ctx.resumeHint);break}let ye=H.find(Mn=>Mn.sessionId===ae.sessionId);if(!(ye!==void 0&&!!ye.importedFromMachine&&!ye.upstreamSessionId&&ae.readonly!==!0)){if(n.isLocal&&ye&&!ye.importedFromMachine&&ae.readonly!==!0&&!(await Ua(ye.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let Yo=await di(t,ye,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Yo.kind==="cancel")return;if(Yo.kind==="back")continue;I={choice:ae,sessions:H},R={readonly:!1,cwd:Yo.path,resumeHint:{agentId:ae.agentId??ye.agentId??"",cwd:Yo.path,upstreamSessionId:""}};break}I={choice:ae,sessions:H};break}let Qn={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let Jo=await _v(t,n,ye,ae,Qn);if(Jo.kind==="cancel")return;Jo.kind!=="back"&&(I={choice:ae,sessions:H},R={readonly:Qn.readonly===!0,cwd:Jo.ctx.cwd},Jo.ctx.resumeHint!==void 0&&(R.resumeHint=Jo.ctx.resumeHint))}let{choice:C}=I,$=ut;if(ut=null,process.off("SIGINT",xr),m.close().catch(()=>{}),v=!0,C.kind==="new"){let{sessionId:H,agentId:ee,...Ee}=s,Se={...Ee,cwd:C.cwd??qe,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Se.initialPrompt=C.prompt),C.attachments&&C.attachments.length>0&&(Se.initialAttachments=C.attachments),C.agentId!==void 0&&(Se.agentId=C.agentId,i.lastChosenAgent=C.agentId),C.model!==void 0&&(Se.model=C.model),C.installStatus!==void 0&&(Se.installStatus=C.installStatus),$(Se);return}if(C.kind!=="attach")return;let W={...s,sessionId:C.sessionId,cwd:R?.cwd??qe,readonly:R?.readonly??C.readonly===!0};C.agentId!==void 0&&(W.agentId=C.agentId),R?.resumeHint!==void 0?W.resumeHint=R.resumeHint:delete W.resumeHint,C.installStatus!==void 0?W.installStatus=C.installStatus:delete W.installStatus,$(W)}finally{!v&&ut&&(x.start({skipFullscreen:!0}),x.resumeRepaint())}},zt=async(g="next")=>{if(!ut)return;let I=(await Ln(n)).filter(Se=>Se.status==="warm");if(I.length<=1)return;let R=I.findIndex(Se=>Se.sessionId===he),W=((R===-1?0:R)+(g==="prev"?-1:1)+I.length)%I.length,H=I[W],ee=ut;ut=null,process.off("SIGINT",xr),m.close().catch(()=>{});let Ee={...s,sessionId:H.sessionId,cwd:qe,readonly:!1};H.agentId!==void 0&&(Ee.agentId=H.agentId),ee(Ee)},Ci=async g=>{if(!ut)return;let v=await Ln(n,{includeNonInteractive:!0}),I=g.trim();if(!I){x.notify("usage: /session <id|next|prev>");return}let R=I.startsWith(jt)?[I]:[I,jt+I],C=v.find(H=>R.includes(H.sessionId));if(!C){let H=v.filter(ee=>R.some(Ee=>ee.sessionId.startsWith(Ee)));if(H.length===1)C=H[0];else if(H.length>1){x.notify(`ambiguous session id: ${I} (${H.length} matches)`);return}}if(!C){x.notify(`no session matches: ${I}`);return}if(C.sessionId===he){x.notify("already on that session");return}let $=ut;ut=null,process.off("SIGINT",xr),m.close().catch(()=>{});let W={...s,sessionId:C.sessionId,cwd:C.cwd??qe,readonly:!1};C.agentId!==void 0&&(W.agentId=C.agentId),delete W.resumeHint,$(W)},Tr=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ks(g.text,g.attachments,g.displayText):Ve(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ve(g.text,g.attachments,g.displayText):Ks(g.text,g.attachments,g.displayText);return;case"queue-edit":{let v=mt(g.index);if(!v)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let R of g.attachments)I.push({type:"image",data:R.data,mimeType:R.mimeType});y.request("hydra-acp/prompt/update",{sessionId:he,messageId:v,prompt:I}).then(R=>{let C=R;!C.updated&&C.reason!=="ok"&&x.notify(`queue edit skipped (${C.reason})`)}).catch(R=>{x.notify(`queue edit failed: ${R.message}`)});return}case"queue-remove":{let v=mt(g.index);if(!v)return;y.request("hydra-acp/prompt/cancel",{sessionId:he,messageId:v}).then(I=>{let R=I;!R.cancelled&&R.reason!=="ok"&&x.notify(`queue cancel skipped (${R.reason})`)}).catch(I=>{x.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(x.isOverlayOpen()){B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay();return}if(g.prefill&&Et){let v=Y.size===0,I=Re.state().buffer.every(R=>R==="");v&&I&&(qn={text:Et.text,attachments:Et.attachments})}Et?Et.cancel():L>0&&bi(),vi();return}case"exit":Si();return;case"plan-toggle":Nt(g.on);return;case"redraw-banner":x.setBanner({});return;case"redraw":x.fullRedraw();return;case"scroll-to-top":x.scrollToTop();return;case"scroll-to-bottom":x.scrollToBottom();return;case"switch-session":zs().catch(v=>{oe({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":zt().catch(()=>{});return;case"toggle-options":Tl();return;case"toggle-questions":od();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts),x.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let v=!x.isMouseEnabled();x.setMouseEnabled(v),i.mouseEnabled=v,x.notify(v?"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":Ko();return;case"escalate-search":x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(g.query);return;case"attachment-request":T(g.source);return}},Ri=async g=>{if(!ps){x.notify("agent does not accept image attachments");return}let v=0;for(let I of g){if(I.startsWith("data:")){let C=Zf(I);if(!C){x.notify("unsupported data: URI");continue}if(C.sizeBytes>cs){x.notify(`image too large (${kn(C.sizeBytes)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),v++;continue}let R=qa(I);if(!R){x.notify(`unsupported image type: ${ci.basename(I)}`);continue}try{let C=await _p.readFile(I);if(C.length>cs){x.notify(`image too large (${kn(C.length)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:R,data:C.toString("base64"),name:ci.basename(I),sizeBytes:C.length}),v++}catch(C){x.notify(`cannot read ${ci.basename(I)}: ${C.message}`)}}v>0&&(x.setAttachments(Re.state().attachments),x.refreshPrompt())},T=async(g="clipboard")=>{let v=g==="primary"?await Eb():await al();if(!v.ok){x.notify(v.reason);return}if(v.kind==="image"){if(!ps){x.notify("agent does not accept image attachments");return}Re.addAttachment(v.attachment),x.setAttachments(Re.state().attachments),x.refreshPrompt();return}let I=Re.feed({type:"paste",text:v.text});for(let R of I)Tr(R);x.refreshPrompt()},M=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,U=(g,v)=>{let I=Array.isArray(v)?v:[],R="",C=0;for(let $ of I){if(!$||typeof $!="object")continue;let W=$;W.type==="text"&&typeof W.text=="string"?R+=W.text:W.type==="image"&&(C+=1)}return{messageId:g,text:Pe(R),attachmentCount:C}},Y=new Map,re=[],ie=new Map,ve=new Set,Ce=null,et=()=>{let g=[...Y.values()],v=g.map(M);x.setQueuedPrompts(v),x.setBanner({queued:g.length}),Re.setQueue(g.map(I=>I.text))},mt=g=>[...Y.values()][g]?.messageId;if(Bt&&Bt.length>0){for(let g of Bt){if(g.position===0){Z=g.messageId;continue}Y.set(g.messageId,U(g.messageId,g.prompt))}Y.size>0&&et()}let Ve=(g,v,I)=>{x.scrollToBottom(),!Ss(g)&&($e(g,I),ks(g,v,I))},Ks=(g,v,I)=>{if(x.scrollToBottom(),Ss(g))return;if($e(g,I),!An||Z===void 0){ks(g,v,I);return}let R=Z,C=[];g.length>0&&C.push({type:"text",text:g});for(let H of v)C.push({type:"image",data:H.data,mimeType:H.mimeType});let $={text:g,displayText:I??g,attachments:v,flushed:!1};re.push($);let W=()=>{let H=re.indexOf($);H>=0&&re.splice(H,1),$.messageId!==void 0&&ie.delete($.messageId)};y.request("hydra-acp/prompt/amend",{sessionId:he,targetMessageId:R,prompt:C}).then(H=>{let ee=H;if(ee.amended&&ee.reason==="ok"){ke(1);return}if(W(),ee.reason==="target_completed"){x.notify("previous response finished \u2014 press Enter to send as a new turn"),Re.setBuffer(g,v),x.refreshPrompt();return}if(ee.reason==="target_cancelled"){x.notify("amend skipped \u2014 previous turn was cancelled"),Re.setBuffer(g,v),x.refreshPrompt();return}if(ee.reason==="target_not_found"){x.notify("amend skipped \u2014 no matching prompt"),Re.setBuffer(g,v),x.refreshPrompt();return}}).catch(H=>{W(),x.notify(`amend failed: ${H.message}`),Re.setBuffer(g,v),x.refreshPrompt()})},Nt=async g=>{if(zn.length===0){x.notify("no modes advertised by agent");return}let v=x.currentModeId(),I=zn.findIndex($=>$.id===v),R=I===-1?0:(I+1)%zn.length,C=zn[R]?.id;if(C){x.setBanner({currentMode:C});try{await y.request("session/set_mode",{sessionId:he,modeId:C})}catch($){x.notify(`set_mode failed: ${$.message}`)}}},Ss=g=>{let v=g.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
255
- `))return!1;let I=v.indexOf(" ");switch(I===-1?v:v.slice(0,I)){case"/quit":case"/exit":return Si(),!0;case"/clear":return ft.clear(),Js.clear(),Dt.length=0,ot=null,rt=null,Pn=null,St.clear(),mn.clear(),en.clear(),Er.clear(),Ys.clear(),Mr.clear(),x.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let $ of Uo)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"});if(Sr.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let $ of Sr)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"})}return x.appendLines(C),!0}case"/agent":{let C=I===-1?"":v.slice(I+1).trim(),$=wi();if(!$)return x.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let ee of $.options){let Ee=ee.value===$.currentValue?"* ":" ";H.push({prefix:" ",body:`${Ee}${ee.value.padEnd(16)} ${ee.name}`,bodyStyle:"info"})}return x.appendLines(H),!0}let W=$.options.find(H=>H.value===C)?.value;if(!W){let H=C.toLowerCase(),ee=$.options.filter(Ee=>Ee.value.toLowerCase().startsWith(H));ee.length===1&&(W=ee[0].value)}return W?W===$.currentValue?(x.notify(`already on agent ${W}`),!0):(x.notify(`switching to ${W}\u2026`),y.request("session/set_config_option",{sessionId:he,configId:"agent",value:W}).catch(H=>{x.notify(`set_config_option failed: ${H.message}`)}),!0):(x.notify(`unknown agent: ${C}`),!0)}case"/sessions":return x.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return zs().catch(C=>{oe({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=I===-1?"":v.slice(I+1).trim();return C?C==="next"||C==="prev"?(zt(C).catch($=>{x.notify(`session ${C} failed: ${$.message}`)}),!0):(Ci(C).catch($=>{x.notify(`session switch failed: ${$.message}`)}),!0):(zs().catch($=>{oe({src:"switch-session-failed",stack:$ instanceof Error?$.stack??$.message:String($)})}),!0)}case"/rename":{let C=I===-1?"":v.slice(I+1).trim(),$=C.length>0?`/hydra title ${C}`:"/hydra title";return $e(v,v),ks($,[],v),!0}case"/btw":{let C=I===-1?"":v.slice(I+1).trim();if(!C)return x.isOverlayOpen()?(B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay(),!0):(x.reopenBtwOverlay()||x.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(he==="__new__")return x.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let $=N;B&&(B.cancel(),B=null);let W=null;_!==null&&!D?W=_:_!==null&&(os(n,_).catch(()=>{}),_=null),D=!1,x.openBtwOverlay(),x.setBtwOverlayStatus({label:"busy",style:"busy"});let H=new rl({getMaxWidth:()=>{let ae=x.width();return ae>0?ae:void 0}});H.on("changed",()=>{x.setBtwOverlayContent(H.getLines())});let ee={};H.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let Ee=ae=>{H.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},Se={};return W!==null&&(Se.reuseSessionId=W),kb(n,he,C,Se).then(ae=>{if($!==N){ae.cancel();return}B=ae,_=ae.sessionId,x.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",ye=>{if($===N)if(ye.kind==="update"){H.append(ye.update);let it=ss(ye.update);if(it&&it.kind==="usage-update"){let Qn=!1;it.used!==void 0&&ee.used!==it.used&&(ee.used=it.used,Qn=!0),it.size!==void 0&&ee.size!==it.size&&(ee.size=it.size,Qn=!0),it.costAmount!==void 0&&ee.costAmount!==it.costAmount&&(ee.costAmount=it.costAmount,Qn=!0),it.costCurrency!==void 0&&ee.costCurrency!==it.costCurrency&&(ee.costCurrency=it.costCurrency,Qn=!0),Qn&&x.setBtwOverlayMeta({usage:{...ee}})}}else ye.kind==="completed"?(x.setBtwOverlayStatus({label:"done",style:"done"}),B=null):ye.kind==="cancelled"?(x.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),B=null,_=null):ye.kind==="errored"&&(x.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw errored: ${ye.error.message}`),_!==null&&os(n,_).catch(()=>{}),B=null,_=null)})}).catch(ae=>{if($!==N)return;let ye=ae instanceof Error?ae.message:String(ae);x.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw startup failed: ${ye}`),x.appendLines([{prefix:" ",body:`btw startup failed: ${ye}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(he==="__new__")return x.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=I===-1?"":v.slice(I+1).trim(),$=he;return(async()=>{try{let W=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent($)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!W.ok){let ye=await W.text().catch(()=>"");x.appendLines([{prefix:" ",body:`/export failed: HTTP ${W.status} ${ye}`.trim(),bodyStyle:"info"}]);return}let H=await W.text(),ee=new Date().toISOString().replace(/[:.]/g,"-"),Ee=`hydra-${pt($)}-${ee}.md`,Se=C.length>0?tt(C):Ee,ae=ci.resolve(Se);await _p.mkdir(ci.dirname(ae),{recursive:!0}),await _p.writeFile(ae,H,{encoding:"utf8",mode:384}),x.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(W){x.appendLines([{prefix:" ",body:`/export failed: ${W.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},ks=async(g,v,I)=>{let R=[];g.length>0&&R.push({type:"text",text:g});for(let Se of v)R.push({type:"image",data:Se.data,mimeType:Se.mimeType});ke(1);let C={text:g,displayText:I??g,attachments:v,flushed:!1};re.push(C),fs=!1;let $=!1,W=null,H=Se=>{typeof G<"u"&&G!==null&&G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Se,bodyStyle:"tool-status-fail"}])},ee=!1;Et={text:g,attachments:v,cancel:()=>{if(fs){fs=!1,ee=!0,H("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),y.request("hydra-acp/session/force_cancel",{sessionId:he}).catch(ae=>{H(`force-stop failed: ${ae.message}`)});return}if($)return;$=!0,y.notify("session/cancel",{sessionId:he}).catch(()=>{});let Se=Date.now();W=setTimeout(()=>{Et!==null&&(Bs>=Se||(fs=!0,H("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},li)}};let Ee;try{let Se=await y.request("session/prompt",{sessionId:he,prompt:R});Se&&typeof Se.stopReason=="string"&&(Ee=Se.stopReason)}catch(Se){let ae=re.indexOf(C);ae>=0&&re.splice(ae,1),C.messageId!==void 0&&ie.delete(C.messageId),ee?x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):x.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Se.message,bodyStyle:"tool-status-fail"}])}finally{if(Et=null,W!==null&&(clearTimeout(W),W=null),ke(-1),C.flushed&&Ce===C){let Se=C.messageId!==void 0&&ve.has(C.messageId);Se&&C.messageId!==void 0&&ve.delete(C.messageId);let ae={kind:"turn-complete"};Ee!==void 0&&(ae.stopReason=Ee),Se&&(ae.amended=!0),A(ae),Ce=null}if(qn!==null){let{text:Se,attachments:ae}=qn;qn=null,Re.state().buffer.every(it=>it==="")&&(Re.setBuffer(Se,ae),x.refreshPrompt())}}},ft=new Map,St=new Map,mn=new Map,Js=new Map,Dt=[],En=0,gn=`tools:${En}`,en=new Map,Er=new Map,Ti=new Set,Pr=new Map,Ys=new Map,Mr=new Map,ot=null,rt=null,Pn=null,Yn=null,Vs=null,El=e.tui.maxToolItems,Pl=e.tui.maxPlanItems,_r=()=>({maxPlanItems:Vs??i.planExpanded?1/0:Pl}),$r=()=>{if(Yn===null)return;let g=pr(Yn,_r());g.length>0&&x.upsertLines("plan",[{body:""},...g])},Qs="",F=null,z=0,ue=()=>{if(F===null)return;let g=x.width(),v=hr(Qs,g>0?{maxWidth:g}:void 0);v.length!==0&&x.upsertLines(F,v)},J=g=>{g.length!==0&&(F===null&&(x.ensureSeparator(),F=`agent:${z}`,z+=1,Qs=""),Qs+=g,ue())},de=()=>{F=null,Qs=""},ce="",Te=null,He=0,We=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),at=()=>{if(Te===null||ce.length===0)return;let g=xo(ce);g.length!==0&&x.upsertLines(Te,g)},tn=g=>{let v=Ys.get(g);if(v===void 0)return[];let I=xo(v.text);return v.workerTaskId&&I.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"dim"}),I},Vn=(g,v)=>{g.length!==0&&(Te===null&&(x.ensureSeparator("thought"),Te=`thought:${He}`,He+=1,ce=""),ce+=g,Ys.set(Te,{text:ce,workerTaskId:v}),at())},ze=()=>{Te=null,ce=""},Ue=g=>EE({...g,collapsedLimit:El}),kt=g=>Er.get(g)??i.toolsExpanded,gt=()=>{if(ot===null)return;let{lines:g,rowOwners:v}=Ue({order:Dt,states:ft,startedAt:ot,endedAt:rt,stopReason:Pn,expanded:kt(gn),perToolExpanded:Ti});x.upsertLines(gn,g),Pr.set(gn,v)},Pt=g=>{let v=en.get(g);if(!v)return;let{lines:I,rowOwners:R}=Ue({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:kt(g),perToolExpanded:Ti});x.upsertLines(g,I),Pr.set(g,R)},Gs=()=>{ot!==null&&!en.has(gn)&&gt();for(let g of en.keys())Pt(g)},Is=()=>{ot!==null&&en.set(gn,{order:[...Dt],states:new Map(ft),startedAt:ot,endedAt:rt??Date.now(),stopReason:Pn,rowOwners:Pr.get(gn)??[]})},dd=()=>{En+=1,gn=`tools:${En}`,ot=Date.now(),rt=null,Pn=null,gt()};function Ml(g){if(!g||typeof g!="object")return null;let v=g,I=Array.isArray(v.content)?v.content:void 0;if(!I)return null;let R=[],C=$=>{if(typeof $=="string"){R.push({text:wt($)});return}if($&&typeof $=="object"){let W=$;typeof W.__hydraBlob=="string"&&R.push({hash:W.__hydraBlob})}};for(let $ of I){if(!$||typeof $!="object")continue;let W=$;if(W.type==="content"&&W.content&&typeof W.content=="object"){let H=W.content;if(H.text!==void 0){C(H.text);continue}}if(W.type==="text"&&W.text!==void 0){C(W.text);continue}W.text!==void 0&&C(W.text)}return R.length>0?R:null}let Ei=(g,v)=>{let I=v.map($=>"text"in $?$.text:"").join(`
256
- `);if(I.length===0)return;let{text:R,truncated:C}=Yy(I);g.resultText=R,g.resultTruncated=C},Le=new Set,Mt=(g,v)=>{!v.some(R=>"hash"in R)||Le.has(g)||(Le.add(g),(async()=>{let R=await Promise.all(v.map(async $=>"text"in $?$:{text:await Pi($.hash)??""}));Le.delete(g);let C=ft.get(g);if(!C)for(let $ of en.values()){let W=$.states.get(g);if(W){C=W;break}}if(C){Ei(C,R),ft.has(g)&&gt();for(let[$,W]of en)W.states.has(g)&&Pt($);x.repaintNow()}})().catch(()=>{Le.delete(g)}))},Xs=(g,v,I,R,C,$,W,H,ee,Ee)=>{let Se=!ft.has(g),ae=ft.get(g),ye=ae??{initialTitle:v??"tool",latestTitle:v??"tool",status:I??"pending",startedAt:Date.now()};if(!ae&&ee!==void 0&&(ye.workerTaskId=ee),ae&&v!==void 0&&(ye.latestTitle=v),$!==void 0&&ye.detail===void 0&&(ye.detail=$),W!==void 0&&ye.detailFull===void 0&&(ye.detailFull=W),H!==void 0&&H.length>0&&(ye.locations=H),ae&&I!==void 0&&(ye.status=I),ae||(ye.status=I??"pending"),ye.endedAt===void 0&&If(ye.status)&&(ye.endedAt=Date.now()),R!==void 0&&(ye.errorText=R),C!==void 0&&(ye.editDiff=C),Ee!==void 0){let it=Ml(Ee);it!==null&&(Ei(ye,it),it.some(Qn=>"hash"in Qn)&&Mt(g,it))}ft.set(g,ye),Se&&(ot===null&&(En+=1,gn=`tools:${En}`,ot=Date.now(),rt=null,Pn=null),Dt.push(g))},Pi=async g=>{try{let v=await y.request("hydra-acp/session/tool_content",{sessionId:he,hash:g});return typeof v?.content=="string"?v.content:null}catch{return null}},cd=new Set,zv=(g,v)=>{cd.has(g)||v.oldRef===void 0&&v.newRef===void 0||(cd.add(g),(async()=>{let[I,R]=await Promise.all([v.oldRef?Pi(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?Pi(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&I===null||v.newRef!==void 0&&R===null){cd.delete(g);let Ee=Sf(v,"diff",{deferredStatus:"error"});Ee.length>0&&(x.upsertLines(`editdiff:${g}`,Ee),x.repaintNow());return}let $={...v.path!==void 0?{path:v.path}:{},oldText:I??"",newText:R??""};St.set(g,$);let W=ft.get(g);W?.editDiff&&(W.editDiff=$),cd.delete(g);let H=mn.get(g),ee=H===void 0?i.showFileUpdates:H?"diff":"edit";ee!=="none"&&(ld(g,$,ee==="diff"?"diff":"edit"),x.repaintNow())})())},ld=(g,v,I)=>{let R=`editdiff:${g}`,C=Sf(v,I);if(C.length===0){x.removeKey(R);return}x.upsertLines(R,C),I==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&x.notifyWhenVisible(R)},Kv=g=>{if(!g.startsWith("editdiff:"))return;let v=g.slice(9),I=St.get(v);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&zv(v,I)},Hp=g=>{let v=`editdiff:${g}`,I=i.showFileUpdates,R=ft.get(g),C;if(I==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let W=mn.get(g);C=W!==void 0?W?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){x.removeKey(v);return}let $=R.editDiff;St.set(g,$),ld(g,$,C)},Jv=()=>{let g=i.showFileUpdates;for(let[v,I]of St){let R=`editdiff:${v}`,C=mn.get(v),$=C===void 0?g:C?"diff":"edit";if($==="none"){x.removeKey(R);continue}ld(v,I,$==="diff"?"diff":"edit")}},Yv=g=>{if(!g.path)return null;let v=wt(g.oldText).split(`
253
+ `)}}function LE(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let _=Math.max(0,c-a),D=e.slice(_),N=[];for(let L=0;L<_;L++){let K=e[L];if(K===void 0)continue;let X=n.get(K);X&&!xf(X.status)&&N.push(K)}l=[...N,...D]}let f=c-l.length,u=r===null,p=r??Date.now(),h=p-s,m=!u&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",w=y?`amended \xB7 ${as(h)}`:`stopped (${m}) \xB7 ${as(h)}`,b;if(c===0)m!==null?b=w:b=u?`thinking \xB7 ${as(h)}`:`thought \xB7 ${as(h)}`;else{let _=c===1?"tool":"tools",D=m!==null?w:u?as(h):`took ${as(h)}`,N=[`${c} ${_}`,D];u&&d&&f>0&&N.push(`${f} hidden`),b=N.join(" \xB7 ")}let S=c===0&&u,k=y?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],B=[null];for(let _ of l){let D=n.get(_);if(D){let N=Pa(D,p);for(let L of N)L.hoverSubKey=_;if(P.push(...N),B.push(...N.map(()=>_)),o?.has(_)){let L=Qy(D);for(let K of L)K.hoverSubKey=_;P.push(...L),B.push(...L.map(()=>_))}}}return{lines:P,rowOwners:B}}async function BE(t,e,n,s,r,i,o){let a=await NE(t,e,n,s,o,i);if(!a)return t.grabInput(!1),oe({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=s.installStatus;s.installStatus&&delete s.installStatus;let l=a.installStatus??d??Sl(c,cv(t));l.write(c);let f=n.isLocal?async()=>(await Ht(await Ae())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],p=null,h=null,m=new _o({url:f,subprotocols:u,onConnect:async g=>{g||p&&await p()},onDisconnect:g=>{h&&h(g)},log:g=>oe({src:"resilient-ws",line:g})}),y=new Kt(m);await m.start(),y.onNotification(Rd,g=>{let v=tm.safeParse(g);v.success&&l.applyProgress(v.data)});let w=[],b=null,S=!1,k=!1,A=(g,v)=>{g&&(b?b(g,v):w.push({event:g,rawUpdate:v}))},E,P=g=>{g!==E&&(E=g,g!==void 0&&x.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},B=null,_=null,D=!1,N=0,L=0,K=!1,X=!1,Z,Q=null,fe=null,Me=null,In=null,He=()=>setInterval(()=>{if(Q===null||G===null)return;let g=In===null?0:Date.now()-In;G.setBanner({elapsedMs:Date.now()-Q,stalled:g>=_E}),gt()},1e3),us=!1,ke=g=>{let v=L;L=Math.max(0,L+g);let I=typeof G<"u"&&G!==null;v===0&&L>0?(X=!1,Q=Date.now(),In=Date.now(),xe?.setTurnRunning(!0),I&&G.setBanner({status:"busy",elapsedMs:0,stalled:!1}),fe===null&&I&&(fe=He())):v>0&&L===0?(X=!1,Q=null,In=null,xe?.setTurnRunning(!1),fe!==null&&(clearInterval(fe),fe=null),I&&G.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&X&&(X=!1,I&&G.setBanner({status:"busy",stalled:!1}))},G=null,xe=null,qe,Yt=null,Ls=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),un=g=>{let{update:v}=g??{},I=ss(v,{cwd:We});DE(v,I),In=Date.now();let R=v?.sessionUpdate;if(typeof R=="string"&&!Ls.has(R)){let C=v??{};typeof C.messageId=="string"&&(qe=C.messageId)}if(R==="prompt_received"?ke(1):I?.kind==="turn-complete"&&(ke(-1),D=!0),R==="permission_resolved"){Do(v);return}if(R==="hydra_compaction"){No(v);return}if(R==="clarifier_question_asked"){let C=v,$=typeof C.question?.question=="string"?C.question.question:"",W=$.length>50?$.slice(0,49)+"\u2026":$;x.notify(W?`new question: ${W} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(A(I,v),td(v))};y.onNotification("session/update",g=>{if(!S){if(Yt!==null){Yt.push(g);return}un(g)}}),y.onNotification("hydra-acp/session/closed",()=>{if(S)return;L>0&&ke(-L),typeof G<"u"&&G!==null&&G.setBanner({status:"cold",elapsedMs:void 0})});let bt=new Map,Bs=200,Ns=0,fs=!1,li=4e3;y.onNotification("hydra-acp/prompt_queue/added",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let R=v.messageId,C=v.prompt,$=setTimeout(()=>{S||(bt.delete(R),Y.set(R,U(R,C)),G&&xe&&et())},Bs);bt.set(R,$)}else Y.set(v.messageId,U(v.messageId,v.prompt)),G&&xe&&et();if(Hs!==void 0&&v.originator?.clientId===Hs){let R=re.shift();R&&(R.messageId=v.messageId,ie.set(v.messageId,R))}}),y.onNotification("hydra-acp/prompt_queue/updated",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string"||!Y.has(v.messageId))return;Y.set(v.messageId,U(v.messageId,v.prompt));let I=ie.get(v.messageId);if(I){let R=Array.isArray(v.prompt)?v.prompt:[],C="",$=[];for(let W of R){if(!W||typeof W!="object")continue;let H=W;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&typeof H.data=="string"&&typeof H.mimeType=="string"&&$.push({data:H.data,mimeType:H.mimeType,sizeBytes:Math.floor(H.data.length*3/4)})}I.text=C,I.attachments=$}G&&xe&&et()}),y.onNotification("hydra-acp/prompt_queue/removed",g=>{if(S)return;let v=g??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(Z=v.messageId);let I=bt.get(v.messageId);I!==void 0&&(clearTimeout(I),bt.delete(v.messageId)),Y.delete(v.messageId)&&G&&xe&&et();let C=ie.get(v.messageId);C&&(ie.delete(v.messageId),v.reason==="started"&&(C.flushed=!0,A({kind:"user-text",text:C.displayText,attachments:C.attachments}),Ce=C))}),y.onNotification("hydra-acp/cancel_failed",g=>{if(S)return;let v=g??{};if(!(typeof G<"u"&&G!==null))return;Ns=Date.now(),fs=!0;let R=typeof v.code=="number"?` (${v.code})`:"",C=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${R}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),y.onNotification("hydra-acp/prompt/amended",g=>{if(S)return;let v=g??{};if(typeof v.cancelledMessageId!="string")return;let I=v.cancelledMessageId;ve.add(I),Ce!==null&&Ce.messageId!==void 0&&Ce.messageId===I&&(A({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Ce=null,ve.delete(I))});let No=g=>{let v=g??{},I=typeof v.phase=="string"?v.phase:void 0;if(I==="started")x.setCompactionIndicator("compacting...");else if(I==="iteration")x.setCompactionIndicator("compacting...");else if(I==="deferred")x.setCompactionIndicator("compaction queued (waiting for idle)");else if(I==="swapped")x.setCompactionIndicator(null),x.notify("compacted",2e3);else if(I==="rolled_back")x.setCompactionIndicator(null),x.notify("rolled back",2e3);else if(I==="failed"){x.setCompactionIndicator(null);let R=typeof v.error=="string"?v.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;x.notify(`compaction failed: ${C}`,5e3)}},xn=()=>{Me===null&&(Me=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState===void 0?(x.setSynthesisIndicator(null),x.notify("synthesis complete",2e3),Me!==null&&(clearInterval(Me),Me=null)):v.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3),Me!==null&&(clearInterval(Me),Me=null))}catch{}},5e3))},ed=()=>{Me!==null&&(clearInterval(Me),Me=null)},Do=g=>{let v=g??{},I=typeof v.toolCallId=="string"?v.toolCallId:void 0,R;v.outcome&&typeof v.outcome=="object"?R=v.outcome:typeof v.chosenOptionId=="string"&&(R={kind:"selected",optionId:v.chosenOptionId}),Ds(I,R?{outcome:R}:void 0)},ge=null,Ds=(g,v)=>{if(!ge||ge.toolCallId&&g&&ge.toolCallId!==g)return;let I=ge.resolve;ge=null,x.setPermissionPrompt(null),I(v??{outcome:{outcome:"cancelled"}})},td=g=>{if(!ge?.toolCallId)return;let v=g??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===ge.toolCallId&&(!v.status||v.status==="pending"||Ds(v.toolCallId,void 0))},ui=()=>{if(!ge){x.setPermissionPrompt(null);return}x.setPermissionPrompt({title:ge.title,detail:ge.detail,options:ge.options.map(g=>({label:g.name})),selectedIndex:ge.selectedIndex})},fi=g=>{if(!ge)return;let{options:v,resolve:I}=ge;if(ge=null,x.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};y.onRequest("session/request_permission",async g=>{if(S)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ii(g);let v=g??{},R=(Array.isArray(v.options)?v.options:[]).map(ee=>({optionId:ee.optionId,name:Pe(ee.name??""),...ee.kind!==void 0?{kind:ee.kind}:{}})),C=v.toolCall?.title??v.toolCall?.name??"tool",$=Pe(C),W=Pe(Qw(Vw(g))),H=v.toolCall?.toolCallId;return R.length===0?(x.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${$} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(ee=>{ge={title:$,detail:W,options:R,selectedIndex:0,resolve:ee,toolCallId:H},ui()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let pi,Rt,ps=!0,An=!1;try{let g=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}});Rt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ps=!1),An=rn(g?._meta??void 0).prompt?.amending===!0}catch{}let he=a.sessionId,Je=a.agentId,We=a.cwd,yt,Hs,hs,ms,hi,Us,gs,Bt,mi,Un,Ho=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let v={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Ft]:g}}:{}},I;try{I=await Hw({request:()=>y.request("session/new",v),showBanner:($,W,H)=>Uw(t,$,W,H,{authenticate:ee=>y.request("authenticate",{methodId:ee})}),resolveOnboarding:async $=>{if($)try{return(await Gr(n)).find(ee=>ee.id===$)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch($){t.grabInput(!1),oe({src:"grab",site:"runSession.session-new-failed",on:!1}),m.close().catch(()=>{});let W=$ instanceof Error?$.message:String($);oe({src:"session-new-failed",agentId:s.agentId??null,message:W});let H=await pv(t,s.agentId,W,{canGoBack:!s.forceNew});if(H==="cancel")return null;let ee={...s};return delete ee.sessionId,delete ee.resume,H==="retry"?ee.forceNew=!0:(delete ee.forceNew,delete ee.agentId),ee}if(I.kind==="cancel")return t.grabInput(!1),oe({src:"grab",site:"runSession.auth-cancel",on:!1}),m.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),oe({src:"grab",site:"runSession.auth-back",on:!1}),m.close().catch(()=>{});let $={...s};return delete $.sessionId,delete $.forceNew,delete $.resume,delete $.agentId,$}let R=I.result;l.write(c),he=R.sessionId,Mp(he),r.sessionId=he,r.readonly=!1;let C=rn(R._meta??void 0);C.clientId&&(Hs=C.clientId),pi=C.upstreamSessionId,C.agentId&&(Je=C.agentId),C.cwd&&(We=C.cwd),C.title&&(yt=C.title),hs=C.currentModel,ms=C.currentMode,mi=C.currentUsage,Un=C.turnStartedAt,C.availableCommands&&(hi=oc(C.availableCommands)),C.availableModes&&(Us=C.availableModes),gs=Tv(R.configOptions),Bt=C.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let v=await y.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:be},...Object.keys(g).length>0?{_meta:{[Ft]:g}}:{}});he=v.sessionId,Mp(he),v.clientId&&(Hs=v.clientId),r.sessionId=he,r.readonly=s.readonly===!0;let I=rn(v._meta??void 0);Ho=I.resurrected===!0,pi=I.upstreamSessionId,I.agentId&&(Je=I.agentId),I.cwd&&(We=I.cwd),I.title&&(yt=I.title),hs=I.currentModel,ms=I.currentMode,mi=I.currentUsage,Un=I.turnStartedAt,I.availableCommands&&(hi=oc(I.availableCommands)),I.availableModes&&(Us=I.availableModes),gs=Tv(v.configOptions),Bt=I.queue}let js=O.tuiHistoryFile(he),gi=O.globalTuiHistoryFile(),Tt=await la(js).catch(()=>[]),Vt=await la(gi).catch(()=>[]);Vt.length>e.tui.promptHistoryMaxEntries&&(Vt=Vt.slice(Vt.length-e.tui.promptHistoryMaxEntries));let jn=[...Tt],Re=new _s({history:Ud(Vt,jn)});xe=Re;let nd=!1,$e=(g,v)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let R=(v??g).replace(/\n+$/,""),C=ua(Tt,I),$=C!==Tt;Tt=C,jn=ua(jn,R);let W=ua(Vt,I,e.tui.promptHistoryMaxEntries),H=W!==Vt;Vt=W,Re.setHistory(Ud(Vt,jn)),$&&zr(js,Tt).catch(()=>{}),H&&eg(gi,I).catch(()=>{})};L>0&&Re.setTurnRunning(!0);let Et=null,qn=null;Gb(Xb(e.tui.ambiguousWidth,process.env)),Xy(e.tui.diffContextLines);let Qt=!1,x,Wn=()=>{Qt&&(Qt=!1,x.start())},fn=()=>{Qt||(Qt=!0,x.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Wn);let qs=null,yi=null;x=new hl({term:t,dispatcher:Re,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:e.tui.openFileCommand,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?fn:void 0,onBlockClick:(g,v)=>{Gv(g,v)},onBlockDoubleClick:(g,v)=>Qv(g,v),onHydraLinkClick:g=>(Ci(g),!0),onBlockVisible:g=>{Jv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let v=Mr.get(g);if(v!==void 0&&v.length>0)return new Set(v);let I=x.contiguousRun(g,new Set(Vs.keys()));return I.length>0?new Set(I):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){qs=x.bannerHitAt(g.x,g.y),yi=qs?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let I=yi,R=qs;if(yi=null,qs=null,R!==null&&I!==null&&I.x===g.x&&I.y===g.y&&x.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Nt(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&$p(C))return;Tr(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let v={type:"attachment-request",source:"primary"};s.readonly===!0&&$p(v)||Tr(v)},onKey:g=>{for(let v of g){if(K&&ki(v)){v.type==="key"&&oe({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(ge&&rd(v)){v.type==="key"&&oe({src:"key-swallowed",site:"permission",name:v.name});continue}if(id(v)){v.type==="key"&&oe({src:"key-swallowed",site:"help",name:v.name});continue}if(Jn(v)){v.type==="key"&&oe({src:"key-swallowed",site:"questions",name:v.name});continue}if(xi(v)){v.type==="key"&&oe({src:"key-swallowed",site:"options",name:v.name});continue}if(sd(v)){v.type==="key"&&oe({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Rl(v)){v.type==="key"&&oe({src:"key-swallowed",site:"completion",name:v.name});continue}if(ws(v)){v.type==="key"&&oe({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&x.isScrolledBack()){x.scrollToBottom();continue}if(v.type==="attachment-paths"){Ri(v.paths);continue}if(v.type==="key"&&kr(v.name)){oe({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let I=Re.feed(v);for(let R of I)s.readonly===!0&&$p(R)||Tr(R)}qt(),x.setBannerSearchIndicator(Re.state().historySearchQuery),x.setAttachments(Re.state().attachments),x.refreshPrompt()}}),G=x,x.setStickyBottomKey("plan");let Uo=[{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:"/session",description:"Switch session: /session <id|next|prev> (no arg opens 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:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],Sr=hi??[],zn=Us??[],jo=gs??[],wi=()=>jo.find(g=>g.id==="agent"),Ze=()=>{let g=new Set,v=[];for(let I of[...Uo,...Sr])g.has(I.name)||(g.add(I.name),v.push(I));return v},qo=()=>{let g=Re.state().buffer,v=g[0]??"";if(!v.startsWith("/"))return[];if(g.length>1)return[];let I=v.indexOf(" "),R=I===-1?v:v.slice(0,I);if(R.lastIndexOf("/")>0)return[];let C=Ze().filter($=>$.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},ys=[],qt=()=>{let g=qo();if(g.length>0){ys=[],x.setCompletions(g);return}x.setCompletions(ys)},Rl=g=>{if(g.type!=="key"||g.name!=="tab")return ys.length>0&&(ys=[]),!1;let v=qo();if(x.isOverlayOpen()&&v.length===0)return x.toggleFocusedPane(),!0;if(v.length>0){ys=[];let I=Re.state().buffer[0]??"",R=rv({matches:v.map(C=>C.name),firstLine:I});return R===null||Re.replaceFirstLine(R),!0}return vt()},vt=()=>{let g=Re.state(),v=g.buffer[g.row]??"",I=bl(v,g.col);if(I===null)return!1;let R=vl(I.token,We);return R===null?!1:(R.replacement!==I.token&&Re.replaceRangeOnCurrentLine(I.start,g.col,R.replacement),ys=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},ws=g=>!x.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay(),!0),sd=g=>{if(!x.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&x.isScrolledBack()?(x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let v=x.scrollbackSearchTerm()+g.ch;return x.updateScrollbackSearchTerm(v),!0}if(g.type==="paste"){let v=x.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return x.updateScrollbackSearchTerm(v),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return x.advanceScrollbackSearch(),!0;case"ctrl-s":return x.retreatScrollbackSearch(),!0;case"backspace":{let v=x.scrollbackSearchTerm();return v.length===0?x.cancelScrollbackSearch():x.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return x.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return x.cancelScrollbackSearch(),!0;default:return!0}return!0},rd=g=>{if(!ge)return!1;let v=ge.options;if(g.type==="key")switch(g.name){case"up":return ge.selectedIndex=Math.max(0,ge.selectedIndex-1),ui(),!0;case"down":return ge.selectedIndex=Math.min(v.length-1,ge.selectedIndex+1),ui(),!0;case"enter":{let I=v[ge.selectedIndex];return I&&fi(I.optionId),!0}case"escape":case"ctrl-c":return fi(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,R=v[I];return R&&fi(R.optionId),!0}return!0},kr=g=>{let v=e.tui.hotkeys[g];return v?(mv(v,{sessionId:he,cwd:We,agentId:Je||Rt||"",baseUrl:n.baseUrl,tokenFile:O.authToken()},{notify:I=>x.notify(I),cwd:We,emitLines:I=>{x.appendLines(I.map(R=>{let C;switch(R.style){case"meta":C="dim";break;case"stderr":case"error":C="tool-status-fail";break;default:C="info"}return{prefix:" ",body:R.text,bodyStyle:C}}))}}),!0):!1},Wo=Je||Rt||"?",Gt={...mi??{}};l.finalize(),x.start({skipFullscreen:!0}),x.setHideThoughts(!i.showThoughts),x.setSessionbar({agent:Wo,cwd:We,sessionId:he,title:yt,model:hs,usage:{...Gt}}),ms&&x.setBanner({currentMode:ms}),Na().then(g=>{g&&x.notify(`\u2728 ${Da(g)}`,3e4)}).catch(()=>{});let ut=null,Ir=new Promise(g=>{ut=g}),bi=()=>{y.notify("session/cancel",{sessionId:he}).catch(()=>{})},vi=()=>{G!==null&&L===1&&(X=!0,G.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},xr=()=>{if(Et){Et.cancel(),vi();return}if(L>0){bi(),vi();return}Si()},Si=()=>{Zt(0)},zo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",v]],...$E]},Ko=()=>{if(x.isHelpPromptActive()){x.setHelpPrompt(null);return}x.setHelpPrompt({title:"Hotkeys",entries:zo(),hint:"any key dismisses \xB7 /help lists commands"})},Ar=()=>{K=!1,x.setCompactionPrompt(null),x.setCompactionIndicator("compaction queued...");let g=he;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},Cn=()=>{K=!1,x.setCompactionPrompt(null)},bs=g=>{let v=x.compactionPromptSpec();if(!v)return;let I=v.options.length;if(I===0)return;let R=((v.selectedIndex+g)%I+I)%I;R!==v.selectedIndex&&x.setCompactionPrompt({...v,selectedIndex:R})},ki=g=>{if(!K)return!1;if(g.type==="key"){if(g.name==="escape")return Cn(),!0;if(g.name==="up")return bs(-1),!0;if(g.name==="down")return bs(1),!0;if(g.name==="enter"){let v=x.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Ar():Cn(),!0}}if(g.type==="char"){let v=g.ch.toLowerCase();if(v==="y"||v==="1")return Ar(),!0;if(v==="n"||v==="2")return Cn(),!0}return!0},id=g=>x.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",x.setHelpPrompt(null),!0):!1,Ws=["tools","plan","thoughts","diffs","mouse","enter"],Rn=0,Tn=null,vs=[],Wt=[],pn=[],zs=0,Cr=g=>{switch(g){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}},Ii=g=>{switch(g){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"}},Tl=()=>({title:"Session options",options:Ws.map(g=>({label:Ii(g),value:Cr(g)})),selectedIndex:Rn}),Xt=()=>{x.isOptionsPromptActive()&&Tn===null&&x.setOptionsPrompt(Tl())},El=()=>{if(x.isOptionsPromptActive()){x.setOptionsPrompt(null);return}Rn=0,x.setOptionsPrompt(Tl())},hn=()=>{if(Tn===null)return;let g=TE(Tn,vs,pn,zs);x.setOptionsPrompt(g)},Kn=()=>{Tn=null,vs=[],Wt=[],pn=[],zs=0,x.setOptionsPrompt(null)},od=async()=>{if(Tn!==null){Kn();return}try{let v=await y.request(bb,{sessionId:he}),I=xE(v.questions??[]);if(I.length===0){x.notify("no open questions");return}let R=CE(I);Tn=R,zs=0,vs=R.map(C=>AE(C.representative)),Wt=R.map(()=>!1),pn=R.map(()=>!1),hn()}catch(g){x.notify("clarifier unavailable"),oe({src:"questions",step:"list_failed",error:g.message})}},ad=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Er.clear(),Ti.clear(),Xs();break;case"plan":i.planExpanded=!i.planExpanded,Qs=null,$r();break;case"thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",mn.clear(),Yv();break;case"mouse":{let v=!x.isMouseEnabled();x.setMouseEnabled(v),i.mouseEnabled=v;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Xt()},Rr=g=>{(async()=>{try{switch(g){case"tools":case"plan":x.notify(`${Ii(g)} is session-only \u2014 not saved`);return;case"thoughts":await Qo("showThoughts",i.showThoughts);break;case"diffs":await Qo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Qo("mouse",i.mouseEnabled);break;case"enter":await Qo("defaultEnterAction",i.defaultEnterAction);break}x.notify(`saved default: ${Ii(g)} ${Cr(g)}`)}catch(v){x.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},xi=g=>{if(Tn!==null||!x.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Rn=Math.max(0,Rn-1),Xt(),!0;case"down":return Rn=Math.min(Ws.length-1,Rn+1),Xt(),!0;case"enter":{let v=Ws[Rn];return v&&ad(v),!0}case"ctrl-o":case"escape":case"ctrl-c":return x.setOptionsPrompt(null),!0;case"ctrl-d":return x.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let v=parseInt(g.ch,10)-1,I=Ws[v];return I&&(Rn=v,ad(I)),!0}if(g.ch==="s"||g.ch==="S"){let v=Ws[Rn];return v&&Rr(v),!0}}return!0},Jn=g=>{if(Tn===null)return!1;let v=ME(g,!0,Tn,vs,Wt,pn,zs,he);switch(v.type){case"noop":return!0;case"row":return zs=v.selectedRow,hn(),!0;case"cycle":return vs[v.selectedRow]=v.newValueIndex,Wt[v.selectedRow]=!0,pn[v.selectedRow]=!1,hn(),!0;case"dismiss-toggle":{let I=v.selectedRow;return pn[I]?(pn[I]=!1,Wt[I]=!1):(pn[I]=!0,Wt[I]=!0),hn(),!0}case"discard":return Kn(),!0;case"save":{let I=v.dispatches;return Kn(),I.length===0||(async()=>{let R=0,C=0,$=0;for(let H of I)try{await y.request(H.method,H.params),H.type==="dismiss"?C++:R++}catch(ee){$++,oe({src:"questions",step:"dispatch_failed",method:H.method,error:ee.message})}let W=[];R>0&&W.push(`${R} answered`),C>0&&W.push(`${C} dismissed`),$>0&&W.push(`${$} failed`),W.length>0&&x.notify(`clarifier: ${W.join(", ")}`)})(),!0}}return!1},Ai=()=>{S=!0,B?(B.cancel(),B=null,_=null):_!==null&&(os(n,_).catch(()=>{}),_=null),process.off("SIGINT",xr),process.platform!=="win32"&&process.off("SIGCONT",Wn),fe!==null&&(clearInterval(fe),fe=null),Me!==null&&(clearInterval(Me),Me=null);for(let g of bt.values())clearTimeout(g);bt.clear(),x.clearWindowTitle(),x.stop({keepFullscreen:!0}),zr(js,Tt).catch(()=>{}),m.close().catch(()=>{})},Zt=(g=0)=>{Ai(),ut&&(ut(null),ut=null),g!==0&&process.exit(g)},Ks=async()=>{if(oe({src:"switch-session",step:"entered",finishSessionNull:ut===null}),!ut)return;B?(B.cancel(),B=null,_=null):_!==null&&(os(n,_).catch(()=>{}),_=null),ed(),x.setSynthesisIndicator(null);let g=Re.state().buffer.join(`
254
+ `);g.replace(/\s+$/,"").length>0&&$e(g),x.pauseRepaint(),x.stop({keepFullscreen:!0}),zr(js,Tt).catch(()=>{});let v=!1;try{let I=null,R=null;for(;I===null;){let H=await Ln(n,{includeNonInteractive:!0}),ee=s.agentId??i.lastChosenAgent??e.defaultAgent,Ee=ee?e.defaultModels?.[ee]:void 0,Se=[];try{Se=await Gr(n)}catch{}let ae=await Ep(t,{cwd:We,sessions:H,config:e,target:n,currentSessionId:he,prefs:o,...ee?{composerAgentId:ee}:{},...Ee?{composerModel:Ee}:{},...Se.length>0?{availableAgents:Se}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){v=!0,Zt(0);return}if(ae.kind==="new"){I={choice:ae,sessions:H};break}if(ae.kind==="fork"){let Mn=await Ov(t,n,ae,H);if(Mn.kind==="cancel")return;if(Mn.kind==="back")continue;I={choice:{kind:"attach",sessionId:Mn.ctx.sessionId,...Mn.ctx.agentId?{agentId:Mn.ctx.agentId}:{}},sessions:H},R={readonly:!1,cwd:Mn.ctx.cwd},Mn.ctx.resumeHint!==void 0&&(R.resumeHint=Mn.ctx.resumeHint);break}let ye=H.find(Mn=>Mn.sessionId===ae.sessionId);if(!(ye!==void 0&&!!ye.importedFromMachine&&!ye.upstreamSessionId&&ae.readonly!==!0)){if(n.isLocal&&ye&&!ye.importedFromMachine&&ae.readonly!==!0&&!(await Ua(ye.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let Yo=await di(t,ye,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Yo.kind==="cancel")return;if(Yo.kind==="back")continue;I={choice:ae,sessions:H},R={readonly:!1,cwd:Yo.path,resumeHint:{agentId:ae.agentId??ye.agentId??"",cwd:Yo.path,upstreamSessionId:""}};break}I={choice:ae,sessions:H};break}let Qn={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let Jo=await $v(t,n,ye,ae,Qn);if(Jo.kind==="cancel")return;Jo.kind!=="back"&&(I={choice:ae,sessions:H},R={readonly:Qn.readonly===!0,cwd:Jo.ctx.cwd},Jo.ctx.resumeHint!==void 0&&(R.resumeHint=Jo.ctx.resumeHint))}let{choice:C}=I,$=ut;if(ut=null,process.off("SIGINT",xr),m.close().catch(()=>{}),v=!0,C.kind==="new"){let{sessionId:H,agentId:ee,...Ee}=s,Se={...Ee,cwd:C.cwd??We,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Se.initialPrompt=C.prompt),C.attachments&&C.attachments.length>0&&(Se.initialAttachments=C.attachments),C.agentId!==void 0&&(Se.agentId=C.agentId,i.lastChosenAgent=C.agentId),C.model!==void 0&&(Se.model=C.model),C.installStatus!==void 0&&(Se.installStatus=C.installStatus),$(Se);return}if(C.kind!=="attach")return;let W={...s,sessionId:C.sessionId,cwd:R?.cwd??We,readonly:R?.readonly??C.readonly===!0};C.agentId!==void 0&&(W.agentId=C.agentId),R?.resumeHint!==void 0?W.resumeHint=R.resumeHint:delete W.resumeHint,C.installStatus!==void 0?W.installStatus=C.installStatus:delete W.installStatus,$(W)}finally{!v&&ut&&(x.start({skipFullscreen:!0}),x.resumeRepaint())}},zt=async(g="next")=>{if(!ut)return;let I=(await Ln(n)).filter(Se=>Se.status==="warm");if(I.length<=1)return;let R=I.findIndex(Se=>Se.sessionId===he),W=((R===-1?0:R)+(g==="prev"?-1:1)+I.length)%I.length,H=I[W],ee=ut;ut=null,process.off("SIGINT",xr),m.close().catch(()=>{});let Ee={...s,sessionId:H.sessionId,cwd:We,readonly:!1};H.agentId!==void 0&&(Ee.agentId=H.agentId),ee(Ee)},Ci=async g=>{if(!ut)return;let v=await Ln(n,{includeNonInteractive:!0}),I=g.trim();if(!I){x.notify("usage: /session <id|next|prev>");return}let R=I.startsWith(jt)?[I]:[I,jt+I],C=v.find(H=>R.includes(H.sessionId));if(!C){let H=v.filter(ee=>R.some(Ee=>ee.sessionId.startsWith(Ee)));if(H.length===1)C=H[0];else if(H.length>1){x.notify(`ambiguous session id: ${I} (${H.length} matches)`);return}}if(!C){x.notify(`no session matches: ${I}`);return}if(C.sessionId===he){x.notify("already on that session");return}let $=ut;ut=null,process.off("SIGINT",xr),m.close().catch(()=>{});let W={...s,sessionId:C.sessionId,cwd:C.cwd??We,readonly:!1};C.agentId!==void 0&&(W.agentId=C.agentId),delete W.resumeHint,$(W)},Tr=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Js(g.text,g.attachments,g.displayText):Qe(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Qe(g.text,g.attachments,g.displayText):Js(g.text,g.attachments,g.displayText);return;case"queue-edit":{let v=mt(g.index);if(!v)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let R of g.attachments)I.push({type:"image",data:R.data,mimeType:R.mimeType});y.request("hydra-acp/prompt/update",{sessionId:he,messageId:v,prompt:I}).then(R=>{let C=R;!C.updated&&C.reason!=="ok"&&x.notify(`queue edit skipped (${C.reason})`)}).catch(R=>{x.notify(`queue edit failed: ${R.message}`)});return}case"queue-remove":{let v=mt(g.index);if(!v)return;y.request("hydra-acp/prompt/cancel",{sessionId:he,messageId:v}).then(I=>{let R=I;!R.cancelled&&R.reason!=="ok"&&x.notify(`queue cancel skipped (${R.reason})`)}).catch(I=>{x.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(x.isOverlayOpen()){B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay();return}if(g.prefill&&Et){let v=Y.size===0,I=Re.state().buffer.every(R=>R==="");v&&I&&(qn={text:Et.text,attachments:Et.attachments})}Et?Et.cancel():L>0&&bi(),vi();return}case"exit":Si();return;case"plan-toggle":Nt(g.on);return;case"redraw-banner":x.setBanner({});return;case"redraw":x.fullRedraw();return;case"scroll-to-top":x.scrollToTop();return;case"scroll-to-bottom":x.scrollToBottom();return;case"switch-session":Ks().catch(v=>{oe({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":zt().catch(()=>{});return;case"toggle-options":El();return;case"toggle-questions":od();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts),x.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let v=!x.isMouseEnabled();x.setMouseEnabled(v),i.mouseEnabled=v,x.notify(v?"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":Ko();return;case"escalate-search":x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(g.query);return;case"attachment-request":T(g.source);return}},Ri=async g=>{if(!ps){x.notify("agent does not accept image attachments");return}let v=0;for(let I of g){if(I.startsWith("data:")){let C=ep(I);if(!C){x.notify("unsupported data: URI");continue}if(C.sizeBytes>cs){x.notify(`image too large (${kn(C.sizeBytes)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),v++;continue}let R=qa(I);if(!R){x.notify(`unsupported image type: ${ci.basename(I)}`);continue}try{let C=await _p.readFile(I);if(C.length>cs){x.notify(`image too large (${kn(C.length)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:R,data:C.toString("base64"),name:ci.basename(I),sizeBytes:C.length}),v++}catch(C){x.notify(`cannot read ${ci.basename(I)}: ${C.message}`)}}v>0&&(x.setAttachments(Re.state().attachments),x.refreshPrompt())},T=async(g="clipboard")=>{let v=g==="primary"?await Pb():await al();if(!v.ok){x.notify(v.reason);return}if(v.kind==="image"){if(!ps){x.notify("agent does not accept image attachments");return}Re.addAttachment(v.attachment),x.setAttachments(Re.state().attachments),x.refreshPrompt();return}let I=Re.feed({type:"paste",text:v.text});for(let R of I)Tr(R);x.refreshPrompt()},M=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,U=(g,v)=>{let I=Array.isArray(v)?v:[],R="",C=0;for(let $ of I){if(!$||typeof $!="object")continue;let W=$;W.type==="text"&&typeof W.text=="string"?R+=W.text:W.type==="image"&&(C+=1)}return{messageId:g,text:Pe(R),attachmentCount:C}},Y=new Map,re=[],ie=new Map,ve=new Set,Ce=null,et=()=>{let g=[...Y.values()],v=g.map(M);x.setQueuedPrompts(v),x.setBanner({queued:g.length}),Re.setQueue(g.map(I=>I.text))},mt=g=>[...Y.values()][g]?.messageId;if(Bt&&Bt.length>0){for(let g of Bt){if(g.position===0){Z=g.messageId;continue}Y.set(g.messageId,U(g.messageId,g.prompt))}Y.size>0&&et()}let Qe=(g,v,I)=>{x.scrollToBottom(),!Ss(g)&&($e(g,I),ks(g,v,I))},Js=(g,v,I)=>{if(x.scrollToBottom(),Ss(g))return;if($e(g,I),!An||Z===void 0){ks(g,v,I);return}let R=Z,C=[];g.length>0&&C.push({type:"text",text:g});for(let H of v)C.push({type:"image",data:H.data,mimeType:H.mimeType});let $={text:g,displayText:I??g,attachments:v,flushed:!1};re.push($);let W=()=>{let H=re.indexOf($);H>=0&&re.splice(H,1),$.messageId!==void 0&&ie.delete($.messageId)};y.request("hydra-acp/prompt/amend",{sessionId:he,targetMessageId:R,prompt:C}).then(H=>{let ee=H;if(ee.amended&&ee.reason==="ok"){ke(1);return}if(W(),ee.reason==="target_completed"){x.notify("previous response finished \u2014 press Enter to send as a new turn"),Re.setBuffer(g,v),x.refreshPrompt();return}if(ee.reason==="target_cancelled"){x.notify("amend skipped \u2014 previous turn was cancelled"),Re.setBuffer(g,v),x.refreshPrompt();return}if(ee.reason==="target_not_found"){x.notify("amend skipped \u2014 no matching prompt"),Re.setBuffer(g,v),x.refreshPrompt();return}}).catch(H=>{W(),x.notify(`amend failed: ${H.message}`),Re.setBuffer(g,v),x.refreshPrompt()})},Nt=async g=>{if(zn.length===0){x.notify("no modes advertised by agent");return}let v=x.currentModeId(),I=zn.findIndex($=>$.id===v),R=I===-1?0:(I+1)%zn.length,C=zn[R]?.id;if(C){x.setBanner({currentMode:C});try{await y.request("session/set_mode",{sessionId:he,modeId:C})}catch($){x.notify(`set_mode failed: ${$.message}`)}}},Ss=g=>{let v=g.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
255
+ `))return!1;let I=v.indexOf(" ");switch(I===-1?v:v.slice(0,I)){case"/quit":case"/exit":return Si(),!0;case"/clear":return ft.clear(),Ys.clear(),Dt.length=0,ot=null,rt=null,Pn=null,St.clear(),mn.clear(),en.clear(),Er.clear(),Vs.clear(),Mr.clear(),x.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let $ of Uo)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"});if(Sr.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let $ of Sr)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"})}return x.appendLines(C),!0}case"/agent":{let C=I===-1?"":v.slice(I+1).trim(),$=wi();if(!$)return x.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let ee of $.options){let Ee=ee.value===$.currentValue?"* ":" ";H.push({prefix:" ",body:`${Ee}${ee.value.padEnd(16)} ${ee.name}`,bodyStyle:"info"})}return x.appendLines(H),!0}let W=$.options.find(H=>H.value===C)?.value;if(!W){let H=C.toLowerCase(),ee=$.options.filter(Ee=>Ee.value.toLowerCase().startsWith(H));ee.length===1&&(W=ee[0].value)}return W?W===$.currentValue?(x.notify(`already on agent ${W}`),!0):(x.notify(`switching to ${W}\u2026`),y.request("session/set_config_option",{sessionId:he,configId:"agent",value:W}).catch(H=>{x.notify(`set_config_option failed: ${H.message}`)}),!0):(x.notify(`unknown agent: ${C}`),!0)}case"/sessions":return x.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return Ks().catch(C=>{oe({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=I===-1?"":v.slice(I+1).trim();return C?C==="next"||C==="prev"?(zt(C).catch($=>{x.notify(`session ${C} failed: ${$.message}`)}),!0):(Ci(C).catch($=>{x.notify(`session switch failed: ${$.message}`)}),!0):(Ks().catch($=>{oe({src:"switch-session-failed",stack:$ instanceof Error?$.stack??$.message:String($)})}),!0)}case"/rename":{let C=I===-1?"":v.slice(I+1).trim(),$=C.length>0?`/hydra title ${C}`:"/hydra title";return $e(v,v),ks($,[],v),!0}case"/btw":{let C=I===-1?"":v.slice(I+1).trim();if(!C)return x.isOverlayOpen()?(B&&(B.cancel(),B=null,_=null),x.closeBtwOverlay(),!0):(x.reopenBtwOverlay()||x.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(he==="__new__")return x.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let $=N;B&&(B.cancel(),B=null);let W=null;_!==null&&!D?W=_:_!==null&&(os(n,_).catch(()=>{}),_=null),D=!1,x.openBtwOverlay(),x.setBtwOverlayStatus({label:"busy",style:"busy"});let H=new rl({getMaxWidth:()=>{let ae=x.width();return ae>0?ae:void 0}});H.on("changed",()=>{x.setBtwOverlayContent(H.getLines())});let ee={};H.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let Ee=ae=>{H.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},Se={};return W!==null&&(Se.reuseSessionId=W),Ib(n,he,C,Se).then(ae=>{if($!==N){ae.cancel();return}B=ae,_=ae.sessionId,x.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",ye=>{if($===N)if(ye.kind==="update"){H.append(ye.update);let it=ss(ye.update);if(it&&it.kind==="usage-update"){let Qn=!1;it.used!==void 0&&ee.used!==it.used&&(ee.used=it.used,Qn=!0),it.size!==void 0&&ee.size!==it.size&&(ee.size=it.size,Qn=!0),it.costAmount!==void 0&&ee.costAmount!==it.costAmount&&(ee.costAmount=it.costAmount,Qn=!0),it.costCurrency!==void 0&&ee.costCurrency!==it.costCurrency&&(ee.costCurrency=it.costCurrency,Qn=!0),Qn&&x.setBtwOverlayMeta({usage:{...ee}})}}else ye.kind==="completed"?(x.setBtwOverlayStatus({label:"done",style:"done"}),B=null):ye.kind==="cancelled"?(x.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),B=null,_=null):ye.kind==="errored"&&(x.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw errored: ${ye.error.message}`),_!==null&&os(n,_).catch(()=>{}),B=null,_=null)})}).catch(ae=>{if($!==N)return;let ye=ae instanceof Error?ae.message:String(ae);x.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw startup failed: ${ye}`),x.appendLines([{prefix:" ",body:`btw startup failed: ${ye}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(he==="__new__")return x.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=I===-1?"":v.slice(I+1).trim(),$=he;return(async()=>{try{let W=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent($)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!W.ok){let ye=await W.text().catch(()=>"");x.appendLines([{prefix:" ",body:`/export failed: HTTP ${W.status} ${ye}`.trim(),bodyStyle:"info"}]);return}let H=await W.text(),ee=new Date().toISOString().replace(/[:.]/g,"-"),Ee=`hydra-${pt($)}-${ee}.md`,Se=C.length>0?tt(C):Ee,ae=ci.resolve(Se);await _p.mkdir(ci.dirname(ae),{recursive:!0}),await _p.writeFile(ae,H,{encoding:"utf8",mode:384}),x.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(W){x.appendLines([{prefix:" ",body:`/export failed: ${W.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},ks=async(g,v,I)=>{let R=[];g.length>0&&R.push({type:"text",text:g});for(let Se of v)R.push({type:"image",data:Se.data,mimeType:Se.mimeType});ke(1);let C={text:g,displayText:I??g,attachments:v,flushed:!1};re.push(C),fs=!1;let $=!1,W=null,H=Se=>{typeof G<"u"&&G!==null&&G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Se,bodyStyle:"tool-status-fail"}])},ee=!1;Et={text:g,attachments:v,cancel:()=>{if(fs){fs=!1,ee=!0,H("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),y.request("hydra-acp/session/force_cancel",{sessionId:he}).catch(ae=>{H(`force-stop failed: ${ae.message}`)});return}if($)return;$=!0,y.notify("session/cancel",{sessionId:he}).catch(()=>{});let Se=Date.now();W=setTimeout(()=>{Et!==null&&(Ns>=Se||(fs=!0,H("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},li)}};let Ee;try{let Se=await y.request("session/prompt",{sessionId:he,prompt:R});Se&&typeof Se.stopReason=="string"&&(Ee=Se.stopReason)}catch(Se){let ae=re.indexOf(C);ae>=0&&re.splice(ae,1),C.messageId!==void 0&&ie.delete(C.messageId),ee?x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):x.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Se.message,bodyStyle:"tool-status-fail"}])}finally{if(Et=null,W!==null&&(clearTimeout(W),W=null),ke(-1),C.flushed&&Ce===C){let Se=C.messageId!==void 0&&ve.has(C.messageId);Se&&C.messageId!==void 0&&ve.delete(C.messageId);let ae={kind:"turn-complete"};Ee!==void 0&&(ae.stopReason=Ee),Se&&(ae.amended=!0),A(ae),Ce=null}if(qn!==null){let{text:Se,attachments:ae}=qn;qn=null,Re.state().buffer.every(it=>it==="")&&(Re.setBuffer(Se,ae),x.refreshPrompt())}}},ft=new Map,St=new Map,mn=new Map,Ys=new Map,Dt=[],En=0,gn=`tools:${En}`,en=new Map,Er=new Map,Ti=new Set,Pr=new Map,Vs=new Map,Mr=new Map,ot=null,rt=null,Pn=null,Yn=null,Qs=null,Pl=e.tui.maxToolItems,Ml=e.tui.maxPlanItems,_r=()=>({maxPlanItems:Qs??i.planExpanded?1/0:Ml}),$r=()=>{if(Yn===null)return;let g=hr(Yn,_r());g.length>0&&x.upsertLines("plan",[{body:""},...g])},Gs="",F=null,z=0,ue=()=>{if(F===null)return;let g=x.width(),v=mr(Gs,g>0?{maxWidth:g}:void 0);v.length!==0&&x.upsertLines(F,v)},J=g=>{g.length!==0&&(F===null&&(x.ensureSeparator(),F=`agent:${z}`,z+=1,Gs=""),Gs+=g,ue())},de=()=>{F=null,Gs=""},ce="",Te=null,Ue=0,ze=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),at=()=>{if(Te===null||ce.length===0)return;let g=xo(ce);g.length!==0&&x.upsertLines(Te,g)},tn=g=>{let v=Vs.get(g);if(v===void 0)return[];let I=xo(v.text);return v.workerTaskId&&I.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"dim"}),I},Vn=(g,v)=>{g.length!==0&&(Te===null&&(x.ensureSeparator("thought"),Te=`thought:${Ue}`,Ue+=1,ce=""),ce+=g,Vs.set(Te,{text:ce,workerTaskId:v}),at())},Ke=()=>{Te=null,ce=""},je=g=>LE({...g,collapsedLimit:Pl}),kt=g=>Er.get(g)??i.toolsExpanded,gt=()=>{if(ot===null)return;let{lines:g,rowOwners:v}=je({order:Dt,states:ft,startedAt:ot,endedAt:rt,stopReason:Pn,expanded:kt(gn),perToolExpanded:Ti});x.upsertLines(gn,g),Pr.set(gn,v)},Pt=g=>{let v=en.get(g);if(!v)return;let{lines:I,rowOwners:R}=je({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:kt(g),perToolExpanded:Ti});x.upsertLines(g,I),Pr.set(g,R)},Xs=()=>{ot!==null&&!en.has(gn)&&gt();for(let g of en.keys())Pt(g)},Is=()=>{ot!==null&&en.set(gn,{order:[...Dt],states:new Map(ft),startedAt:ot,endedAt:rt??Date.now(),stopReason:Pn,rowOwners:Pr.get(gn)??[]})},dd=()=>{En+=1,gn=`tools:${En}`,ot=Date.now(),rt=null,Pn=null,gt()};function _l(g){if(!g||typeof g!="object")return null;let v=g,I=Array.isArray(v.content)?v.content:void 0;if(!I)return null;let R=[],C=$=>{if(typeof $=="string"){R.push({text:wt($)});return}if($&&typeof $=="object"){let W=$;typeof W.__hydraBlob=="string"&&R.push({hash:W.__hydraBlob})}};for(let $ of I){if(!$||typeof $!="object")continue;let W=$;if(W.type==="content"&&W.content&&typeof W.content=="object"){let H=W.content;if(H.text!==void 0){C(H.text);continue}}if(W.type==="text"&&W.text!==void 0){C(W.text);continue}W.text!==void 0&&C(W.text)}return R.length>0?R:null}let Ei=(g,v)=>{let I=v.map($=>"text"in $?$.text:"").join(`
256
+ `);if(I.length===0)return;let{text:R,truncated:C}=Vy(I);g.resultText=R,g.resultTruncated=C},Be=new Set,Mt=(g,v)=>{!v.some(R=>"hash"in R)||Be.has(g)||(Be.add(g),(async()=>{let R=await Promise.all(v.map(async $=>"text"in $?$:{text:await Pi($.hash)??""}));Be.delete(g);let C=ft.get(g);if(!C)for(let $ of en.values()){let W=$.states.get(g);if(W){C=W;break}}if(C){Ei(C,R),ft.has(g)&&gt();for(let[$,W]of en)W.states.has(g)&&Pt($);x.repaintNow()}})().catch(()=>{Be.delete(g)}))},Zs=(g,v,I,R,C,$,W,H,ee,Ee)=>{let Se=!ft.has(g),ae=ft.get(g),ye=ae??{initialTitle:v??"tool",latestTitle:v??"tool",status:I??"pending",startedAt:Date.now()};if(!ae&&ee!==void 0&&(ye.workerTaskId=ee),ae&&v!==void 0&&(ye.latestTitle=v),$!==void 0&&ye.detail===void 0&&(ye.detail=$),W!==void 0&&ye.detailFull===void 0&&(ye.detailFull=W),H!==void 0&&H.length>0&&(ye.locations=H),ae&&I!==void 0&&(ye.status=I),ae||(ye.status=I??"pending"),ye.endedAt===void 0&&xf(ye.status)&&(ye.endedAt=Date.now()),R!==void 0&&(ye.errorText=R),C!==void 0&&(ye.editDiff=C),Ee!==void 0){let it=_l(Ee);it!==null&&(Ei(ye,it),it.some(Qn=>"hash"in Qn)&&Mt(g,it))}ft.set(g,ye),Se&&(ot===null&&(En+=1,gn=`tools:${En}`,ot=Date.now(),rt=null,Pn=null),Dt.push(g))},Pi=async g=>{try{let v=await y.request("hydra-acp/session/tool_content",{sessionId:he,hash:g});return typeof v?.content=="string"?v.content:null}catch{return null}},cd=new Set,Kv=(g,v)=>{cd.has(g)||v.oldRef===void 0&&v.newRef===void 0||(cd.add(g),(async()=>{let[I,R]=await Promise.all([v.oldRef?Pi(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?Pi(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&I===null||v.newRef!==void 0&&R===null){cd.delete(g);let Ee=kf(v,"diff",{deferredStatus:"error"});Ee.length>0&&(x.upsertLines(`editdiff:${g}`,Ee),x.repaintNow());return}let $={...v.path!==void 0?{path:v.path}:{},oldText:I??"",newText:R??""};St.set(g,$);let W=ft.get(g);W?.editDiff&&(W.editDiff=$),cd.delete(g);let H=mn.get(g),ee=H===void 0?i.showFileUpdates:H?"diff":"edit";ee!=="none"&&(ld(g,$,ee==="diff"?"diff":"edit"),x.repaintNow())})())},ld=(g,v,I)=>{let R=`editdiff:${g}`,C=kf(v,I);if(C.length===0){x.removeKey(R);return}x.upsertLines(R,C),I==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&x.notifyWhenVisible(R)},Jv=g=>{if(!g.startsWith("editdiff:"))return;let v=g.slice(9),I=St.get(v);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Kv(v,I)},Hp=g=>{let v=`editdiff:${g}`,I=i.showFileUpdates,R=ft.get(g),C;if(I==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let W=mn.get(g);C=W!==void 0?W?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){x.removeKey(v);return}let $=R.editDiff;St.set(g,$),ld(g,$,C)},Yv=()=>{let g=i.showFileUpdates;for(let[v,I]of St){let R=`editdiff:${v}`,C=mn.get(v),$=C===void 0?g:C?"diff":"edit";if($==="none"){x.removeKey(R);continue}ld(v,I,$==="diff"?"diff":"edit")}},Vv=g=>{if(!g.path)return null;let v=wt(g.oldText).split(`
257
257
  `),I=wt(g.newText).split(`
258
- `),R=0,C=Math.min(v.length,I.length);for(;R<C&&v[R]===I[R];)R++;let $=I[R];if(!$)return null;let W=ci.isAbsolute(g.path)?g.path:ci.resolve(qe,g.path),H;try{H=mE(W,"utf8")}catch{return null}let ee=H.split(`
259
- `);for(let Ee=0;Ee<ee.length;Ee++)if(ee[Ee]===$)return Ee+1;return null},Vv=(g,v)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),R=St.get(I),$=ft.get(I)?.locations?.[0],W=$?.path??R?.path;if(!W)return!1;let H=null;$?.line!==void 0?H=$.line:R&&(H=Yv(R));let ee=H===null?"":`:${H}`;return x.tryOpenPathString(W+ee)}if(g.startsWith("tools:")){if(v===0)return!1;let I=Pr.get(g),R=I?I[v]:void 0;if(!R)return!1;let C=ft.get(R),$=C?.locations?.[0];if($){let H=$.line===void 0?"":`:${$.line}`;if(x.tryOpenPathString($.path+H))return!0}let W=C?.detailFull??C?.detail;if(W)return x.tryOpenPathString(W)}return!1},Qv=(g,v)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),R=St.get(I);if(!R)return;let C=mn.get(I)??i.showFileUpdates==="diff";mn.set(I,!C),ld(I,R,C?"edit":"diff"),x.repaintNow();return}if(g==="plan"){if(Yn===null)return;Vs=!(Vs??i.planExpanded),$r(),x.repaintNow();return}if(g.startsWith("tools:")){if(v===0){let C=Er.get(g)??i.toolsExpanded;Er.set(g,!C),g===gn&&ot!==null?gt():Pt(g),x.repaintNow();return}let I=Pr.get(g);if(!I)return;let R=I[v];if(!R)return;RE(R,Ti),Pt(g),x.repaintNow();return}if(g.startsWith("thought:")){if(!Ys.has(g))return;let I=Mr.get(g);if(I!==void 0){Mr.delete(g),x.setRunCollapsed(I,!1,tn(g)),x.repaintNow();return}let R=x.contiguousRun(g,new Set(Ys.keys()));if(R.length===0)return;let C=R[0];Mr.set(C,R),x.setRunCollapsed(R,!0,[We()]),x.repaintNow();return}};b=(g,v)=>{if(g.kind==="available-commands"){Sr=g.commands,qt();return}if(g.kind==="available-modes"){zn=g.modes;return}if(g.kind==="config-options"){jo=g.options;let R=g.options.find($=>$.id==="agent");R&&R.currentValue&&R.currentValue!==Ke&&(Ke=R.currentValue,x.setSessionbar({agent:R.currentValue}));let C=g.options.find($=>$.id==="mode");C&&(zn=C.options.map($=>({id:$.value,name:$.name??$.value,...$.description!==void 0?{description:$.description}:{}})));return}if(g.kind==="mode-changed"){x.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&x.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Ke&&(Ke=g.agentId,x.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?x.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(x.setCompactionIndicator(null),g.agentId!==void 0&&x.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let R=!1;g.used!==void 0&&Gt.used!==g.used&&(Gt.used=g.used,R=!0),g.size!==void 0&&Gt.size!==g.size&&(Gt.size=g.size,R=!0),g.costAmount!==void 0&&Gt.costAmount!==g.costAmount&&(Gt.costAmount=g.costAmount,R=!0),g.costCurrency!==void 0&&Gt.costCurrency!==g.costCurrency&&(Gt.costCurrency=g.costCurrency,R=!0),R&&x.setSessionbar({usage:{...Gt}});return}if(g.kind==="user-text"){nd&&$e(g.text),de(),ze(),ot!==null&&(rt=Date.now(),gt()),Ce=null,x.ensureSeparator();let R=pr(g);R.length>0&&x.appendLines(R),Is(),x.clearKey("plan"),Yn=null,Vs=null,ft.clear(),Js.clear(),Dt.length=0,rt=null,dd(),x.redraw();return}if(g.kind==="agent-text"){ze(),F===null&&P(g.workerTaskId),J(g.text);return}if(g.kind==="agent-thought"){de(),Te===null&&P(g.workerTaskId),Vn(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),ze();let R=Js.get(g.toolCallId),C={plan:g.plan??R?.plan??"",status:g.status??R?.status};if(Js.set(g.toolCallId,C),C.plan.length===0)return;let $=ew(C);$.length>0&&x.upsertLines(g.toolCallId,$);return}if(g.kind==="tool-call"){de(),ze(),ft.has(g.toolCallId)||P(g.workerTaskId),Xs(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),gt(),Hp(g.toolCallId);return}if(g.kind==="plan"){de(),ze(),Yn=g;let R=pr(g,_r());R.length>0&&x.upsertLines("plan",[{body:""},...R]);let C=g.entries.length>0&&g.entries.every($=>($.status??"pending")==="completed");x.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){de(),ze(),Xs(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),g.upstreamInterrupted&&(us=!0),gt(),Hp(g.toolCallId);return}g.kind==="model-changed"&&x.setSessionbar({model:g.model});let I=pr(g);if(I.length>0&&x.appendLines(I),g.kind==="turn-complete"){Z=void 0,de(),ze();let R=g.amended?"amended":g.stopReason;if(!g.amended&&us&&(R===void 0||R==="end_turn")&&(R="error"),Yn!==null&&R!==void 0&&R!=="end_turn"){let C=pr({...Yn,stopped:!0,amended:g.amended===!0},_r());C.length>0&&x.upsertLines("plan",[{body:""},...C])}Yn=null,Vs=null,x.clearKey("plan"),x.setStickyBottomKey("plan"),ot!==null?(rt=Date.now(),Pn=R??null,gt(),Is()):R!==void 0&&R!=="end_turn"&&R!=="amended"&&x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${R}`,bodyStyle:"tool-status-fail"}]),ft.clear(),Js.clear(),Dt.length=0,ot=null,rt=null,Pn=null,us=!1,x.ensureSeparator(),Iv({pendingTurns:L,queueSize:Y.size,ownTurnInFlight:Et!==null,hasInFlightHead:Z!==void 0,replayDraining:k,amended:g.amended===!0})&&ke(-L)}};let Up=w;w=[];let ud=[];for(let{event:g}of Up)g.kind==="user-text"&&typeof g.text=="string"&&ud.push(g.text);x.pauseRepaint(),k=!0;try{for(let{event:g,rawUpdate:v}of Up)b(g,v)}finally{k=!1,x.resumeRepaint()}if(ud.length>0){let g=ju(Tt,ud);g!==Tt&&(Tt=g,jn=ju(jn,ud),Re.setHistory(Ud(Vt,jn)),zr(Us,Tt).catch(()=>{}))}nd=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json(),I=v.compactionState?.status;if(I==="requested"||I==="running"?x.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&x.setCompactionIndicator("compaction queued (waiting for idle)"),!Ho||v.shouldCompact!==!0)return;let R=v.approxTokens??0;K=!0,x.setCompactionPrompt({message:`This session has ~${wg(R)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState==="running"?(x.setSynthesisIndicator("synthesizing context\u2026"),xn()):v.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Un!==void 0&&L>0?(Q=Un,x.setBanner({status:"busy",elapsedMs:Date.now()-Un}),fe===null&&(fe=De()),ot===null&&dd(),ot=Un,gt()):Un===void 0&&L>0&&ke(-L);let Gv=()=>{if(ge){let g=ge.resolve;ge=null,x.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),ze()},jp=()=>{ot!==null&&(rt=Date.now(),Pn="reconnect-recovery-failed",gt(),Is(),ft.clear(),Js.clear(),Dt.length=0,ot=null,rt=null,Pn=null)};return h=g=>{oe({src:"reconnect",step:"disconnect",message:g?.message}),x.setBanner({status:"disconnected",elapsedMs:void 0})},p=async()=>{if(oe({src:"reconnect",step:"begin",sessionId:he}),n.isLocal)try{let H=await Ht(await Ae());(H.baseUrl!==n.baseUrl||H.wsUrl!==n.wsUrl)&&(oe({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:H.baseUrl}),n.baseUrl=H.baseUrl,n.wsUrl=H.wsUrl,n.display=H.display)}catch(H){oe({src:"reconnect",step:"target-refresh-failed",message:H instanceof Error?H.message:String(H)})}Gv();let g={jsonrpc:"2.0",id:`tui-reinit-${Cv()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}}};oe({src:"reconnect",step:"initialize-send"});try{await m.request(g),oe({src:"reconnect",step:"initialize-ok"})}catch(H){oe({src:"reconnect",step:"initialize-fail",message:H.message})}let v=je!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Cv()}`,method:"session/attach",params:{sessionId:he,historyPolicy:v?"after_message":"none",...v?{afterMessageId:je}:{},clientInfo:{name:"hydra-acp-tui",version:be},...(()=>{let H={};return pi!==void 0&&(H.resume={upstreamSessionId:pi,agentId:Ke,cwd:qe}),e.tui.toolContent==="references"&&(H.toolContent="references"),Object.keys(H).length>0?{_meta:{[Ft]:H}}:{}})()}};Yt=[];let R,C,$;oe({src:"reconnect",step:"attach-send",useAfterMessage:v,lastSeenMessageId:je});try{let H=await m.request(I);if(oe({src:"reconnect",step:"attach-resp",hasError:!!H.error}),H.error)throw new Error(H.error.message);$=kv(H.result),R=$.appliedPolicy,$.clientId!==void 0&&(Ds=$.clientId)}catch(H){C=H,oe({src:"reconnect",step:"attach-fail",message:C.message})}let W=Yt??[];if(Yt=null,C)jp(),x.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(v&&R!=="after_message")jp(),x.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{k=!0;try{for(let H of W)un(H)}finally{k=!1}}if($){let H=xv({daemonTurnStartedAt:$.turnStartedAt,pendingTurns:L});H.pendingTurnsDelta!==0&&ke(H.pendingTurnsDelta),H.banner==="busy"&&H.busySince!==void 0?(Q=H.busySince,x.setBanner({status:"busy",elapsedMs:Date.now()-H.busySince}),fe===null&&(fe=De())):x.setBanner({status:"ready",elapsedMs:void 0})}else x.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});oe({src:"reconnect",step:"end"})},y.onClose(g=>{g&&t.red(`
258
+ `),R=0,C=Math.min(v.length,I.length);for(;R<C&&v[R]===I[R];)R++;let $=I[R];if(!$)return null;let W=ci.isAbsolute(g.path)?g.path:ci.resolve(We,g.path),H;try{H=kE(W,"utf8")}catch{return null}let ee=H.split(`
259
+ `);for(let Ee=0;Ee<ee.length;Ee++)if(ee[Ee]===$)return Ee+1;return null},Qv=(g,v)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),R=St.get(I),$=ft.get(I)?.locations?.[0],W=$?.path??R?.path;if(!W)return!1;let H=null;$?.line!==void 0?H=$.line:R&&(H=Vv(R));let ee=H===null?"":`:${H}`;return x.tryOpenPathString(W+ee)}if(g.startsWith("tools:")){if(v===0)return!1;let I=Pr.get(g),R=I?I[v]:void 0;if(!R)return!1;let C=ft.get(R),$=C?.locations?.[0];if($){let H=$.line===void 0?"":`:${$.line}`;if(x.tryOpenPathString($.path+H))return!0}let W=C?.detailFull??C?.detail;if(W)return x.tryOpenPathString(W)}return!1},Gv=(g,v)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),R=St.get(I);if(!R)return;let C=mn.get(I)??i.showFileUpdates==="diff";mn.set(I,!C),ld(I,R,C?"edit":"diff"),x.repaintNow();return}if(g==="plan"){if(Yn===null)return;Qs=!(Qs??i.planExpanded),$r(),x.repaintNow();return}if(g.startsWith("tools:")){if(v===0){let C=Er.get(g)??i.toolsExpanded;Er.set(g,!C),g===gn&&ot!==null?gt():Pt(g),x.repaintNow();return}let I=Pr.get(g);if(!I)return;let R=I[v];if(!R)return;FE(R,Ti),Pt(g),x.repaintNow();return}if(g.startsWith("thought:")){if(!Vs.has(g))return;let I=Mr.get(g);if(I!==void 0){Mr.delete(g),x.setRunCollapsed(I,!1,tn(g)),x.repaintNow();return}let R=x.contiguousRun(g,new Set(Vs.keys()));if(R.length===0)return;let C=R[0];Mr.set(C,R),x.setRunCollapsed(R,!0,[ze()]),x.repaintNow();return}};b=(g,v)=>{if(g.kind==="available-commands"){Sr=g.commands,qt();return}if(g.kind==="available-modes"){zn=g.modes;return}if(g.kind==="config-options"){jo=g.options;let R=g.options.find($=>$.id==="agent");R&&R.currentValue&&R.currentValue!==Je&&(Je=R.currentValue,x.setSessionbar({agent:R.currentValue}));let C=g.options.find($=>$.id==="mode");C&&(zn=C.options.map($=>({id:$.value,name:$.name??$.value,...$.description!==void 0?{description:$.description}:{}})));return}if(g.kind==="mode-changed"){x.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&x.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Je&&(Je=g.agentId,x.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?x.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(x.setCompactionIndicator(null),g.agentId!==void 0&&x.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let R=!1;g.used!==void 0&&Gt.used!==g.used&&(Gt.used=g.used,R=!0),g.size!==void 0&&Gt.size!==g.size&&(Gt.size=g.size,R=!0),g.costAmount!==void 0&&Gt.costAmount!==g.costAmount&&(Gt.costAmount=g.costAmount,R=!0),g.costCurrency!==void 0&&Gt.costCurrency!==g.costCurrency&&(Gt.costCurrency=g.costCurrency,R=!0),R&&x.setSessionbar({usage:{...Gt}});return}if(g.kind==="user-text"){nd&&$e(g.text),de(),Ke(),ot!==null&&(rt=Date.now(),gt()),Ce=null,x.ensureSeparator();let R=hr(g);R.length>0&&x.appendLines(R),Is(),x.clearKey("plan"),Yn=null,Qs=null,ft.clear(),Ys.clear(),Dt.length=0,rt=null,dd(),x.redraw();return}if(g.kind==="agent-text"){Ke(),F===null&&P(g.workerTaskId),J(g.text);return}if(g.kind==="agent-thought"){de(),Te===null&&P(g.workerTaskId),Vn(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),Ke();let R=Ys.get(g.toolCallId),C={plan:g.plan??R?.plan??"",status:g.status??R?.status};if(Ys.set(g.toolCallId,C),C.plan.length===0)return;let $=tw(C);$.length>0&&x.upsertLines(g.toolCallId,$);return}if(g.kind==="tool-call"){de(),Ke(),ft.has(g.toolCallId)||P(g.workerTaskId),Zs(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),gt(),Hp(g.toolCallId);return}if(g.kind==="plan"){de(),Ke(),Yn=g;let R=hr(g,_r());R.length>0&&x.upsertLines("plan",[{body:""},...R]);let C=g.entries.length>0&&g.entries.every($=>($.status??"pending")==="completed");x.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){de(),Ke(),Zs(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),g.upstreamInterrupted&&(us=!0),gt(),Hp(g.toolCallId);return}g.kind==="model-changed"&&x.setSessionbar({model:g.model});let I=hr(g);if(I.length>0&&x.appendLines(I),g.kind==="turn-complete"){Z=void 0,de(),Ke();let R=g.amended?"amended":g.stopReason;if(!g.amended&&us&&(R===void 0||R==="end_turn")&&(R="error"),Yn!==null&&R!==void 0&&R!=="end_turn"){let C=hr({...Yn,stopped:!0,amended:g.amended===!0},_r());C.length>0&&x.upsertLines("plan",[{body:""},...C])}Yn=null,Qs=null,x.clearKey("plan"),x.setStickyBottomKey("plan"),ot!==null?(rt=Date.now(),Pn=R??null,gt(),Is()):R!==void 0&&R!=="end_turn"&&R!=="amended"&&x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${R}`,bodyStyle:"tool-status-fail"}]),ft.clear(),Ys.clear(),Dt.length=0,ot=null,rt=null,Pn=null,us=!1,x.ensureSeparator(),xv({pendingTurns:L,queueSize:Y.size,ownTurnInFlight:Et!==null,hasInFlightHead:Z!==void 0,replayDraining:k,amended:g.amended===!0})&&ke(-L)}};let Up=w;w=[];let ud=[];for(let{event:g}of Up)g.kind==="user-text"&&typeof g.text=="string"&&ud.push(g.text);x.pauseRepaint(),k=!0;try{for(let{event:g,rawUpdate:v}of Up)b(g,v)}finally{k=!1,x.resumeRepaint()}if(ud.length>0){let g=qu(Tt,ud);g!==Tt&&(Tt=g,jn=qu(jn,ud),Re.setHistory(Ud(Vt,jn)),zr(js,Tt).catch(()=>{}))}nd=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json(),I=v.compactionState?.status;if(I==="requested"||I==="running"?x.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&x.setCompactionIndicator("compaction queued (waiting for idle)"),!Ho||v.shouldCompact!==!0)return;let R=v.approxTokens??0;K=!0,x.setCompactionPrompt({message:`This session has ~${bg(R)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState==="running"?(x.setSynthesisIndicator("synthesizing context\u2026"),xn()):v.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Un!==void 0&&L>0?(Q=Un,x.setBanner({status:"busy",elapsedMs:Date.now()-Un}),fe===null&&(fe=He()),ot===null&&dd(),ot=Un,gt()):Un===void 0&&L>0&&ke(-L);let Xv=()=>{if(ge){let g=ge.resolve;ge=null,x.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),Ke()},jp=()=>{ot!==null&&(rt=Date.now(),Pn="reconnect-recovery-failed",gt(),Is(),ft.clear(),Ys.clear(),Dt.length=0,ot=null,rt=null,Pn=null)};return h=g=>{oe({src:"reconnect",step:"disconnect",message:g?.message}),x.setBanner({status:"disconnected",elapsedMs:void 0})},p=async()=>{if(oe({src:"reconnect",step:"begin",sessionId:he}),n.isLocal)try{let H=await Ht(await Ae());(H.baseUrl!==n.baseUrl||H.wsUrl!==n.wsUrl)&&(oe({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:H.baseUrl}),n.baseUrl=H.baseUrl,n.wsUrl=H.wsUrl,n.display=H.display)}catch(H){oe({src:"reconnect",step:"target-refresh-failed",message:H instanceof Error?H.message:String(H)})}Xv();let g={jsonrpc:"2.0",id:`tui-reinit-${Rv()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}}};oe({src:"reconnect",step:"initialize-send"});try{await m.request(g),oe({src:"reconnect",step:"initialize-ok"})}catch(H){oe({src:"reconnect",step:"initialize-fail",message:H.message})}let v=qe!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Rv()}`,method:"session/attach",params:{sessionId:he,historyPolicy:v?"after_message":"none",...v?{afterMessageId:qe}:{},clientInfo:{name:"hydra-acp-tui",version:be},...(()=>{let H={};return pi!==void 0&&(H.resume={upstreamSessionId:pi,agentId:Je,cwd:We}),e.tui.toolContent==="references"&&(H.toolContent="references"),Object.keys(H).length>0?{_meta:{[Ft]:H}}:{}})()}};Yt=[];let R,C,$;oe({src:"reconnect",step:"attach-send",useAfterMessage:v,lastSeenMessageId:qe});try{let H=await m.request(I);if(oe({src:"reconnect",step:"attach-resp",hasError:!!H.error}),H.error)throw new Error(H.error.message);$=Iv(H.result),R=$.appliedPolicy,$.clientId!==void 0&&(Hs=$.clientId)}catch(H){C=H,oe({src:"reconnect",step:"attach-fail",message:C.message})}let W=Yt??[];if(Yt=null,C)jp(),x.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(v&&R!=="after_message")jp(),x.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{k=!0;try{for(let H of W)un(H)}finally{k=!1}}if($){let H=Av({daemonTurnStartedAt:$.turnStartedAt,pendingTurns:L});H.pendingTurnsDelta!==0&&ke(H.pendingTurnsDelta),H.banner==="busy"&&H.busySince!==void 0?(Q=H.busySince,x.setBanner({status:"busy",elapsedMs:Date.now()-H.busySince}),fe===null&&(fe=He())):x.setBanner({status:"ready",elapsedMs:void 0})}else x.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});oe({src:"reconnect",step:"end"})},y.onClose(g=>{g&&t.red(`
260
260
  connection lost: ${g.message}
261
- `),Zt(g?1:0)}),process.on("SIGINT",xr),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&Ve(s.initialPrompt??"",s.initialAttachments??[]),await Ir}async function ME(t,e,n,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await Pv(t,n,s,i)!=="ok"?null:Ev(s,o,e);if(s.resume){let a=vv();if(a){let f=(await Ln(n,{all:!0,includeNonInteractive:!0})).find(u=>u.sessionId===a);if(f)return{sessionId:f.sessionId,agentId:f.agentId??"",cwd:f.cwd??o}}let c=await Ln(n,{cwd:o,all:!0}),d=Ec(c,o);return d?{sessionId:d.sessionId,agentId:d.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
262
- `),null)}for(;;){let a=await Ln(n,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await Gr(n)}catch{}let f=await Tp(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(f.kind==="abort"||f.kind==="exit")return null;if(f.kind==="new"){f.agentId!==void 0&&(s.agentId=f.agentId,i.lastChosenAgent=f.agentId),f.model!==void 0&&(s.model=f.model),f.prompt!==void 0&&(s.initialPrompt=f.prompt),f.attachments&&f.attachments.length>0&&(s.initialAttachments=f.attachments),f.cwd!==void 0&&(o=f.cwd,s.cwd=f.cwd);let w=f.installStatus,b=await Pv(t,n,s,i,()=>{w&&(w.finalize(),w=void 0)});if(b==="cancel")return w&&w.finalize(),null;if(b==="back"){w&&w.finalize();continue}let S=Ev(s,o,e);return w&&(S.installStatus=w),S}if(f.kind==="fork"){let w=await Fv(t,n,f,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=f.readonly===!0;let u=f.installStatus,p=()=>{u&&(u.finalize(),u=void 0)},h=a.find(w=>w.sessionId===f.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await _v(t,n,h,f,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(n.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await Ua(h.cwd)).ok){p();let b=await di(t,h,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(b.kind==="cancel")return null;if(b.kind==="back")continue;let S=f.agentId??h.agentId??"";return{sessionId:f.sessionId,agentId:S,cwd:b.path,resumeHint:{agentId:S,cwd:b.path,upstreamSessionId:""}}}let y={sessionId:f.sessionId,agentId:f.agentId??"",cwd:o};return u&&(y.installStatus=u),y}}async function _v(t,e,n,s,r){for(;;){let i=await ev(t,n);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??n.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:n.cwd}}}let o=await $v(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await di(t,n);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function $v(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Gr(e)}catch{return{kind:"ok",agentId:n,changed:!1}}if(s.length===0||s.some(i=>i.id===n))return{kind:"ok",agentId:n,changed:!1};let r=await ja(t,s,n,{title:"Agent not available here",intro:`Source agent "${n}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Fv(t,e,n,s){let r=s.find(f=>f.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await $v(t,e,n.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let f=await di(t,r);if(f.kind==="cancel")return{kind:"cancel"};if(f.kind==="back")return{kind:"back"};o=f.path}let d=c??n.sourceAgentId??"",l;try{l=await Tc(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(f){return t.red(`
261
+ `),Zt(g?1:0)}),process.on("SIGINT",xr),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&Qe(s.initialPrompt??"",s.initialAttachments??[]),await Ir}async function NE(t,e,n,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await Mv(t,n,s,i)!=="ok"?null:Pv(s,o,e);if(s.resume){let a=Sv();if(a){let f=(await Ln(n,{all:!0,includeNonInteractive:!0})).find(u=>u.sessionId===a);if(f)return{sessionId:f.sessionId,agentId:f.agentId??"",cwd:f.cwd??o}}let c=await Ln(n,{cwd:o,all:!0}),d=Ec(c,o);return d?{sessionId:d.sessionId,agentId:d.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
262
+ `),null)}for(;;){let a=await Ln(n,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await Gr(n)}catch{}let f=await Ep(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(f.kind==="abort"||f.kind==="exit")return null;if(f.kind==="new"){f.agentId!==void 0&&(s.agentId=f.agentId,i.lastChosenAgent=f.agentId),f.model!==void 0&&(s.model=f.model),f.prompt!==void 0&&(s.initialPrompt=f.prompt),f.attachments&&f.attachments.length>0&&(s.initialAttachments=f.attachments),f.cwd!==void 0&&(o=f.cwd,s.cwd=f.cwd);let w=f.installStatus,b=await Mv(t,n,s,i,()=>{w&&(w.finalize(),w=void 0)});if(b==="cancel")return w&&w.finalize(),null;if(b==="back"){w&&w.finalize();continue}let S=Pv(s,o,e);return w&&(S.installStatus=w),S}if(f.kind==="fork"){let w=await Ov(t,n,f,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=f.readonly===!0;let u=f.installStatus,p=()=>{u&&(u.finalize(),u=void 0)},h=a.find(w=>w.sessionId===f.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await $v(t,n,h,f,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(n.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await Ua(h.cwd)).ok){p();let b=await di(t,h,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(b.kind==="cancel")return null;if(b.kind==="back")continue;let S=f.agentId??h.agentId??"";return{sessionId:f.sessionId,agentId:S,cwd:b.path,resumeHint:{agentId:S,cwd:b.path,upstreamSessionId:""}}}let y={sessionId:f.sessionId,agentId:f.agentId??"",cwd:o};return u&&(y.installStatus=u),y}}async function $v(t,e,n,s,r){for(;;){let i=await tv(t,n);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??n.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:n.cwd}}}let o=await Fv(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await di(t,n);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function Fv(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Gr(e)}catch{return{kind:"ok",agentId:n,changed:!1}}if(s.length===0||s.some(i=>i.id===n))return{kind:"ok",agentId:n,changed:!1};let r=await ja(t,s,n,{title:"Agent not available here",intro:`Source agent "${n}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Ov(t,e,n,s){let r=s.find(f=>f.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await Fv(t,e,n.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let f=await di(t,r);if(f.kind==="cancel")return{kind:"cancel"};if(f.kind==="back")return{kind:"back"};o=f.path}let d=c??n.sourceAgentId??"",l;try{l=await Tc(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(f){return t.red(`
263
263
  fork failed: ${f.message}
264
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Ev(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Pv(t,e,n,s,r){if(n.agentId||await eh())return"ok";let i;try{i=await Gr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Ae(),a=s.lastChosenAgent??o.defaultAgent,c=await ja(t,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(n.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await Li(c.agentId)}catch{}return"ok"}function _E(t,e){oe({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}var Fp,AE,CE,Tv,Ov=V(()=>{"use strict";jr();Ot();Wf();Qe();Vf();Dr();Vr();ba();Xo();Sb();es();we();Hr();an();Zc();Jf();jd();Ra();Ib();xb();uv();Ap();zc();Ip();Sp();Xf();qf();pv();vp();ef();rp();il();dl();mv();Sv();yl();xp();Av();or();Ao();Fp="dismiss";AE=12e4;CE=[["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 warm 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)"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^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"]];Tv=!1});var Lv={};_l(Lv,{runTui:()=>Mv});var Bv=V(()=>{"use strict";Ov()});import{readFileSync as $E}from"fs";import{fileURLToPath as FE}from"url";import{dirname as OE,resolve as LE}from"path";var qp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),Zv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Wp(t){for(let e of Object.keys(t))if(!qp.has(e)&&!Zv.has(e))return e}function $l(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 c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(qp.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 eS(t,e){let n=t[e];if(typeof n=="string")return n}function Mi(t,e){return t[e]===!0||t[e]==="true"}var tS="HYDRA_ACP_";function nS(t){return tS+t.toUpperCase().replace(/-/g,"_")}function It(t,e){let n=eS(t,e);return n!==void 0?n:process.env[nS(e)]}Qe();Dr();async function yh(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=Dl(n);return{target:await mh(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ae();return{target:await Ht(s),sessionId:n,fromUrl:!1}}function Ql(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}Hr();we();Qe();xs();import*as vh from"fs/promises";async function Sh(t){if(await vh.mkdir(O.home(),{recursive:!0}),await pd(),!await Fi()){let n=$i();await Oi(n),process.stdout.write(`Initialized ${O.authToken()}
264
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Pv(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Mv(t,e,n,s,r){if(n.agentId||await eh())return"ok";let i;try{i=await Gr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Ae(),a=s.lastChosenAgent??o.defaultAgent,c=await ja(t,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(n.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await Li(c.agentId)}catch{}return"ok"}function DE(t,e){oe({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}var Fp,_E,$E,Ev,Lv=V(()=>{"use strict";jr();Ot();zf();Ge();Qf();Dr();Vr();ba();Xo();kb();es();we();Hr();an();Zc();Yf();jd();Ra();xb();Ab();fv();Cp();zc();xp();kp();Zf();Wf();hv();Sp();tf();ip();il();dl();gv();kv();yl();Ap();Cv();ar();Ao();Fp="dismiss";_E=12e4;$E=[["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 warm 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)"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^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"]];Ev=!1});var Bv={};$l(Bv,{runTui:()=>_v});var Nv=V(()=>{"use strict";Lv()});import{readFileSync as HE}from"fs";import{fileURLToPath as UE}from"url";import{dirname as jE,resolve as qE}from"path";var qp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),eS=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Wp(t){for(let e of Object.keys(t))if(!qp.has(e)&&!eS.has(e))return e}function Fl(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 c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(qp.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 tS(t,e){let n=t[e];if(typeof n=="string")return n}function Mi(t,e){return t[e]===!0||t[e]==="true"}var nS="HYDRA_ACP_";function sS(t){return nS+t.toUpperCase().replace(/-/g,"_")}function It(t,e){let n=tS(t,e);return n!==void 0?n:process.env[sS(e)]}Ge();Dr();async function yh(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=Hl(n);return{target:await mh(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ae();return{target:await Ht(s),sessionId:n,fromUrl:!1}}function Gl(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}Hr();we();Ge();xs();import*as vh from"fs/promises";async function Sh(t){if(await vh.mkdir(O.home(),{recursive:!0}),await pd(),!await Fi()){let n=$i();await Oi(n),process.stdout.write(`Initialized ${O.authToken()}
265
265
  Service token: ${n}
266
266
  `);return}if(Mi(t,"rotate-token")){let n=$i();await Oi(n),process.stdout.write(`Rotated token in ${O.authToken()}
267
267
  New token: ${n}
268
268
  `);return}process.stdout.write(`Service token already exists at ${O.authToken()}.
269
269
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
270
- `)}we();Ni();Qe();xs();import{setTimeout as rC}from"timers/promises";import gy from"chalk";import*as ly from"fs";import*as is from"fs/promises";import*as uy from"net";import*as po from"path";import*as fy from"tls";import KA from"fastify";import JA from"@fastify/websocket";var kh="acp.v1";function Ih(t,e){return t.has(kh)?kh:!1}Qe();import dy from"pino";import YA from"pino-roll";we();import*as $t from"fs/promises";import{createHash as jS}from"crypto";import{gzip as qS,gunzip as WS}from"zlib";import{promisify as xh}from"util";var Ah=xh(qS),zS=xh(WS),Ch=/^[A-Za-z0-9_-]+$/,KS=/^[a-f0-9]{64}$/,Gl=!0;function Rh(t){Gl=t}function wd(t,e){return Ch.test(t)?e===void 0||KS.test(e):!1}function bd(t,e){return`${O.toolBlobFile(t,e)}.gz`}async function Xl(t,e){if(!wd(t))return null;let n=jS("sha256").update(e,"utf8").digest("hex"),s=bd(t,n),r=O.toolBlobFile(t,n);for(let a of[s,r])try{return await $t.access(a),n}catch{}await $t.mkdir(O.toolsDir(t),{recursive:!0});let i=Gl?s:r,o=Gl?await Ah(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await $t.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function vd(t,e){if(!wd(t,e))return null;try{let n=await $t.readFile(bd(t,e));return(await zS(n)).toString("utf8")}catch{}try{return await $t.readFile(O.toolBlobFile(t,e),"utf8")}catch{return null}}async function Th(t,e){if(!wd(t,e))return null;try{return await $t.readFile(bd(t,e))}catch{}try{let n=await $t.readFile(O.toolBlobFile(t,e));return await Ah(n)}catch{return null}}async function Eh(t,e,n){if(!wd(t,e))return;let s=bd(t,e);try{await $t.access(s);return}catch{}await $t.mkdir(O.toolsDir(t),{recursive:!0}),await $t.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ph(t){Ch.test(t)&&await $t.rm(O.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}we();Qe();Or();Ui();import*as Uh from"fs/promises";import*as kd from"path";import{z as le}from"zod";we();Ui();import*as sn from"fs/promises";import*as Xn from"path";import{spawn as ZS}from"child_process";var ru=t=>{process.stderr.write(t+`
271
- `)};function iu(t){ru=t??(e=>process.stderr.write(e+`
272
- `))}async function Lh(t){let e=wn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=O.agentNpmInstallDir(t.agentId,e,t.version),s=rk(t.packageSpec),r=ik(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Xn.join(n,"node_modules",".bin",t.bin);if(await Ur(o))return o;if(await Ur(n)){let f=await Oh(i);if(f)return f.binPath}await ek({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Oh(i);if(a)return a.binPath;let c=await Nh(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.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 ek(t){await sn.mkdir(Xn.dirname(t.installDir),{recursive:!0});let e=await sn.mkdtemp(`${t.installDir}.partial-`);try{ru(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),su(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await sk({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await sn.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Ur(t.installDir)){await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),su(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}ru(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),su(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function su(t,e){if(t)try{t(e)}catch{}}var tk=5,nk=25;function sk(t){return Bh(t,0)}async function Bh(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=ZS("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,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
273
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<tk)return await new Promise(r=>setTimeout(r,nk*(e+1))),Bh(t,e+1);throw n}}function rk(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 ik(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Nh(t,e){let n=Xn.join(t,"node_modules",e,"package.json");try{let s=await sn.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 Oh(t){let e=Xn.join(t.installDir,"node_modules",".bin"),n=Xn.join(e,t.hint);if(await Ur(n))return{binName:t.hint,binPath:n};let s=await Nh(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Xn.join(e,i);if(await Ur(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=Xn.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Xn.join(e,t.basename);if(await Ur(r))return{binName:t.basename,binPath:r}}}async function Ur(t){try{return await sn.access(t),!0}catch{return!1}}var ok=le.object({package:le.string(),bin:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ji=le.object({archive:le.string().url().optional(),cmd:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ak=le.object({"darwin-aarch64":ji.optional(),"darwin-x86_64":ji.optional(),"linux-aarch64":ji.optional(),"linux-x86_64":ji.optional(),"windows-x86_64":ji.optional(),"windows-aarch64":ji.optional()}),dk=le.object({package:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ck=le.object({command:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),lk=le.object({command:le.string().optional(),url:le.string().optional(),description:le.string().optional()}),uk=le.object({npx:ok.optional(),binary:ak.optional(),uvx:dk.optional(),exec:ck.optional()}),fk=le.object({id:le.string(),name:le.string(),version:le.string().optional(),description:le.string().optional(),authors:le.array(le.string()).optional(),license:le.string().optional(),icon:le.string().optional(),repository:le.string().optional(),website:le.string().optional(),distribution:uk,onboarding:lk.optional(),requiredEnv:le.array(le.string().min(1)).optional()}),Dh=le.object({version:le.string(),agents:le.array(fk),extensions:le.array(le.unknown()).optional()}),Sd=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(a=>a.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>ou(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[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:tt(n.command??e),args:n.args?.map(tt),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:pk(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=Dh.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 yn(O.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Dh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await nn(O.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function pk(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 ou(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 qi(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 au(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function au(t){let e=wn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=tu(t.distribution.binary,e);if(s?.cmd){let r=kd.resolve(O.agentInstallDir(t.id,e,n),s.cmd);if(await Hh(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??ou(t)??s.package,i=O.agentNpmInstallDir(t.id,e,n),o=kd.join(i,"node_modules",".bin",r);if(await Hh(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Hh(t){try{return await Uh.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??ou(t)??r.package,a=n.onInstallProgress;return{command:await Lh({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=tu(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${wn()??"this platform"}.`);let i=n.onInstallProgress,o=await Fh({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):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 wk}from"child_process";import*as Ed from"fs";import*as sm from"path";Ot();function Td(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
270
+ `)}we();Ni();Ge();xs();import{setTimeout as cC}from"timers/promises";import yy from"chalk";import*as uy from"fs";import*as is from"fs/promises";import*as fy from"net";import*as po from"path";import*as py from"tls";import GA from"fastify";import XA from"@fastify/websocket";var kh="acp.v1";function Ih(t,e){return t.has(kh)?kh:!1}Ge();import cy from"pino";import ZA from"pino-roll";we();import*as $t from"fs/promises";import{createHash as qS}from"crypto";import{gzip as WS,gunzip as zS}from"zlib";import{promisify as xh}from"util";var Ah=xh(WS),KS=xh(zS),Ch=/^[A-Za-z0-9_-]+$/,JS=/^[a-f0-9]{64}$/,Xl=!0;function Rh(t){Xl=t}function wd(t,e){return Ch.test(t)?e===void 0||JS.test(e):!1}function bd(t,e){return`${O.toolBlobFile(t,e)}.gz`}async function Zl(t,e){if(!wd(t))return null;let n=qS("sha256").update(e,"utf8").digest("hex"),s=bd(t,n),r=O.toolBlobFile(t,n);for(let a of[s,r])try{return await $t.access(a),n}catch{}await $t.mkdir(O.toolsDir(t),{recursive:!0});let i=Xl?s:r,o=Xl?await Ah(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await $t.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function vd(t,e){if(!wd(t,e))return null;try{let n=await $t.readFile(bd(t,e));return(await KS(n)).toString("utf8")}catch{}try{return await $t.readFile(O.toolBlobFile(t,e),"utf8")}catch{return null}}async function Th(t,e){if(!wd(t,e))return null;try{return await $t.readFile(bd(t,e))}catch{}try{let n=await $t.readFile(O.toolBlobFile(t,e));return await Ah(n)}catch{return null}}async function Eh(t,e,n){if(!wd(t,e))return;let s=bd(t,e);try{await $t.access(s);return}catch{}await $t.mkdir(O.toolsDir(t),{recursive:!0}),await $t.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ph(t){Ch.test(t)&&await $t.rm(O.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}we();Ge();Or();Ui();import*as Uh from"fs/promises";import*as kd from"path";import{z as le}from"zod";we();Ui();import*as sn from"fs/promises";import*as Xn from"path";import{spawn as ek}from"child_process";var iu=t=>{process.stderr.write(t+`
271
+ `)};function ou(t){iu=t??(e=>process.stderr.write(e+`
272
+ `))}async function Lh(t){let e=wn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=O.agentNpmInstallDir(t.agentId,e,t.version),s=ik(t.packageSpec),r=ok(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Xn.join(n,"node_modules",".bin",t.bin);if(await Ur(o))return o;if(await Ur(n)){let f=await Oh(i);if(f)return f.binPath}await tk({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Oh(i);if(a)return a.binPath;let c=await Nh(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.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 tk(t){await sn.mkdir(Xn.dirname(t.installDir),{recursive:!0});let e=await sn.mkdtemp(`${t.installDir}.partial-`);try{iu(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),ru(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await rk({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await sn.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Ur(t.installDir)){await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),ru(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}iu(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),ru(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function ru(t,e){if(t)try{t(e)}catch{}}var nk=5,sk=25;function rk(t){return Bh(t,0)}async function Bh(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=ek("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,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
273
+ stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<nk)return await new Promise(r=>setTimeout(r,sk*(e+1))),Bh(t,e+1);throw n}}function ik(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 ok(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Nh(t,e){let n=Xn.join(t,"node_modules",e,"package.json");try{let s=await sn.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 Oh(t){let e=Xn.join(t.installDir,"node_modules",".bin"),n=Xn.join(e,t.hint);if(await Ur(n))return{binName:t.hint,binPath:n};let s=await Nh(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Xn.join(e,i);if(await Ur(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=Xn.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Xn.join(e,t.basename);if(await Ur(r))return{binName:t.basename,binPath:r}}}async function Ur(t){try{return await sn.access(t),!0}catch{return!1}}var ak=le.object({package:le.string(),bin:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ji=le.object({archive:le.string().url().optional(),cmd:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),dk=le.object({"darwin-aarch64":ji.optional(),"darwin-x86_64":ji.optional(),"linux-aarch64":ji.optional(),"linux-x86_64":ji.optional(),"windows-x86_64":ji.optional(),"windows-aarch64":ji.optional()}),ck=le.object({package:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),lk=le.object({command:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),uk=le.object({command:le.string().optional(),url:le.string().optional(),description:le.string().optional()}),fk=le.object({npx:ak.optional(),binary:dk.optional(),uvx:ck.optional(),exec:lk.optional()}),pk=le.object({id:le.string(),name:le.string(),version:le.string().optional(),description:le.string().optional(),authors:le.array(le.string()).optional(),license:le.string().optional(),icon:le.string().optional(),repository:le.string().optional(),website:le.string().optional(),distribution:fk,onboarding:uk.optional(),requiredEnv:le.array(le.string().min(1)).optional()}),Dh=le.object({version:le.string(),agents:le.array(pk),extensions:le.array(le.unknown()).optional()}),Sd=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(a=>a.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>au(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[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:tt(n.command??e),args:n.args?.map(tt),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:hk(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=Dh.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 yn(O.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Dh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await nn(O.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function hk(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 au(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 qi(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 du(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function du(t){let e=wn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=nu(t.distribution.binary,e);if(s?.cmd){let r=kd.resolve(O.agentInstallDir(t.id,e,n),s.cmd);if(await Hh(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??au(t)??s.package,i=O.agentNpmInstallDir(t.id,e,n),o=kd.join(i,"node_modules",".bin",r);if(await Hh(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Hh(t){try{return await Uh.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??au(t)??r.package,a=n.onInstallProgress;return{command:await Lh({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=nu(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${wn()??"this platform"}.`);let i=n.onInstallProgress,o=await Fh({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):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 bk}from"child_process";import*as Ed from"fs";import*as sm from"path";Ot();function Td(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
274
274
  `);for(;c!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),d.length>0)try{let l=JSON.parse(d);for(let f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:j.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
275
275
  `)}}),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 c=JSON.stringify(a)+`
276
- `;await new Promise((d,l)=>{e.write(c,f=>{if(f){l(f);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}jr();we();var bk=4096,nr=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}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??bk,this.killEscalationMs=e.killEscalationMs??vk,this.logger=e.logger,this.fileLog=Sk(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()} ---
276
+ `;await new Promise((d,l)=>{e.write(c,f=>{if(f){l(f);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}jr();we();var vk=4096,sr=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}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??vk,this.killEscalationMs=e.killEscalationMs??Sk,this.logger=e.logger,this.fileLog=kk(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()} ---
277
277
  `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=Td(n.stdout,n.stdin);this.connection=new Kt(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()} ---
278
278
  `),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()} ---
279
279
  `),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}
280
- stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=wk(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()} ---
280
+ stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=bk(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()} ---
281
281
  `),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()} ---
282
- `),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)})}},vk=2e3;function Sk(t){try{let e=O.agentLogFile(t);Ed.mkdirSync(sm.dirname(e),{recursive:!0});let n=Ed.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Jr from"fs/promises";import*as zd from"os";import*as ma from"path";import{customAlphabet as FI}from"nanoid";fu();es();_u();we();Or();import*as Rs from"fs/promises";import{z as ts}from"zod";var mI=ts.object({version:ts.literal(1),agentId:ts.string(),upstreamSessionId:ts.string(),deletedAt:ts.string(),upstreamUpdatedAt:ts.string().optional(),cwd:ts.string().optional(),title:ts.string().optional(),reason:ts.enum(["user","expired"]).optional(),interactive:ts.boolean().optional()}),Ld=class{async add(e){let n={version:1,...e};await nn(O.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await Rs.access(O.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=O.tombstoneFile(e,n),r=await yn(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 mI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await Rs.unlink(O.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await Rs.rmdir(O.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 Rs.readdir(O.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 Rs.readdir(O.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 _m(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as zm from"fs/promises";Ot();an();Fd();_d();var wI=12e4;async function Fm(t,e,n){let s=t.timeoutMs??wI,r,i,o=!1;try{let a=(async()=>{r=nr.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:be}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let h=vI(d);if(h.size===0||h.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(m){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${m.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",h=>{let m=bI(h);m.length>0&&f.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let u=f.join(""),p=n(u);if(!p){let h=JSON.stringify(u.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${u.length} preview=${h})`);let m=u.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${u.length} chars): ${m}${u.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Nd(t){let e=Qi(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
282
+ `),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)})}},Sk=2e3;function kk(t){try{let e=O.agentLogFile(t);Ed.mkdirSync(sm.dirname(e),{recursive:!0});let n=Ed.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Jr from"fs/promises";import*as zd from"os";import*as ma from"path";import{customAlphabet as DI}from"nanoid";pu();es();$u();we();Or();import*as Rs from"fs/promises";import{z as ts}from"zod";var gI=ts.object({version:ts.literal(1),agentId:ts.string(),upstreamSessionId:ts.string(),deletedAt:ts.string(),upstreamUpdatedAt:ts.string().optional(),cwd:ts.string().optional(),title:ts.string().optional(),reason:ts.enum(["user","expired"]).optional(),interactive:ts.boolean().optional()}),Ld=class{async add(e){let n={version:1,...e};await nn(O.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await Rs.access(O.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=O.tombstoneFile(e,n),r=await yn(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 gI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await Rs.unlink(O.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await Rs.rmdir(O.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 Rs.readdir(O.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 Rs.readdir(O.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 _m(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as zm from"fs/promises";Ot();an();Fd();_d();var bI=12e4;async function Fm(t,e,n){let s=t.timeoutMs??bI,r,i,o=!1;try{let a=(async()=>{r=sr.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:be}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let h=SI(d);if(h.size===0||h.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(m){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${m.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",h=>{let m=vI(h);m.length>0&&f.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let u=f.join(""),p=n(u);if(!p){let h=JSON.stringify(u.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${u.length} preview=${h})`);let m=u.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${u.length} chars): ${m}${u.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Nd(t){let e=Qi(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
283
283
 
284
284
  ${e}
285
285
 
286
- ${xu}`:`${n}
286
+ ${Au}`:`${n}
287
287
 
288
- ${xu}`;return Fm(t,s,Em)}async function Om(t){let e=Qi(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
288
+ ${Au}`;return Fm(t,s,Em)}async function Om(t){let e=Qi(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
289
289
 
290
290
  ${e}
291
291
 
292
- ${Au}`:`${n}
292
+ ${Cu}`:`${n}
293
293
 
294
- ${Au}`;return Fm(t,s,Pm)}function bI(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 vI(t){let e=new Set;$m(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&$m(e,n.availableModels),e}function $m(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)}}}Ou();we();var SI=2,Dd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??SI}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,n){if(this.stopped)return;let s=n?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>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={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){let s=n.kind,r=n.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await bn(d,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,u=s==="compaction"?this.opts.compactionModel??(f?i.currentModel:void 0):this.opts.synopsisModel,p=O.sessionDir(e);if(await zm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(u??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,w,b=0,S,k=Date.now(),A={targetAgentId:r},E=B=>this.opts.onCompactionStateChange?.(e,B,A)??Promise.resolve(),P=B=>{this.opts.broadcastHydraCompaction?.(e,B,A)};await E({status:"requested",requestedAt:k}),P({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let B=await this.opts.histories.load(e,{maxEntries:1/0});if(B.length===y)break;let _=await Om({agentId:c,cwd:p,plan:l,history:B,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(N,L)=>{E({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:N,pid:L??0}})},onFailure:N=>{S=N}});if(_){let N=jm(_.synopsis,B);N&&qm(N)&&(await this.opts.persistSynopsis(e,N,B.length),w=N,b=B.length,S=void 0,await E({status:"running",requestedAt:k,iter:m}),P({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:B.length}),await this.opts.onSynthesisArtifact?.(e,N,b,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Wm(N)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=B.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(w)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${b} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let B=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:k,iter:m,lastError:B}),P({sessionUpdate:"hydra_compaction",phase:"failed",error:B})}}catch(B){let _=B instanceof Error?B.message:String(B);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await E({status:"failed",requestedAt:k,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let h=await Nd({agentId:c,cwd:p,plan:l,history:o,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=jm(h.synopsis,o);m&&qm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${Wm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function jm(t,e){let n=Dm(e),s=Nm(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 qm(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 Wm(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(",")}]`}we();import*as Ge from"fs/promises";function Km(t){return t==="summary"?"summary":"inline"}var Lu=256;function Jm(t,e){return e!=="summary"?t:t.map(kI)}function kI(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(Ym));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Bu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function II(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Ym(t){if(II(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=Bu(e.text)),typeof e.content=="string"?n.content=Bu(e.content):e.content&&typeof e.content=="object"&&(n.content=Ym(e.content)),n}function Bu(t){if(typeof t=="string"&&t.length>Lu){let e=t.length-Lu;return`${t.slice(0,Lu)}\u2026[+${e} chars omitted from summary export]`}return t}var xI=2048;function Vm(t){let e=new Set,n=s=>{if(Qm(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 Qm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function AI(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 Hu(t,e){if(!AI(t))return t;let n=t.params,s=n.update,r=await Nu(s,e);return{...t,params:{...n,update:r}}}async function Nu(t,e){if(typeof t=="string"){if(t.length<=xI)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 Nu(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Nu(r,e);return n}return t}async function Gm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await Du(n,e);return s===n?t:{...t,params:s}}async function Du(t,e){if(Qm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await Du(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 Du(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var CI=/^history\.jsonl\.(\d+)$/,Wr=/^[A-Za-z0-9_-]+$/,RI=1e3,TI=1e7,EI=10,Hd=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;constructor(e={}){this.maxEntries=e.maxEntries??RI,this.archiveMaxBytes=e.archiveMaxBytes??TI,this.archiveTiers=e.archiveTiers??EI}async append(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{await Ge.mkdir(O.sessionDir(e),{recursive:!0});let s=await Hu(n,i=>Xl(e,i)),r=JSON.stringify(s)+`
295
- `;await Ge.appendFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{await Ge.mkdir(O.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Hu(i,o=>Xl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
294
+ ${Cu}`;return Fm(t,s,Pm)}function vI(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 SI(t){let e=new Set;$m(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&$m(e,n.availableModels),e}function $m(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)}}}Lu();we();var kI=2,Dd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??kI}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,n){if(this.stopped)return;let s=n?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>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={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){let s=n.kind,r=n.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await bn(d,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,u=s==="compaction"?this.opts.compactionModel??(f?i.currentModel:void 0):this.opts.synopsisModel,p=O.sessionDir(e);if(await zm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(u??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,w,b=0,S,k=Date.now(),A={targetAgentId:r},E=B=>this.opts.onCompactionStateChange?.(e,B,A)??Promise.resolve(),P=B=>{this.opts.broadcastHydraCompaction?.(e,B,A)};await E({status:"requested",requestedAt:k}),P({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let B=await this.opts.histories.load(e,{maxEntries:1/0});if(B.length===y)break;let _=await Om({agentId:c,cwd:p,plan:l,history:B,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(N,L)=>{E({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:N,pid:L??0}})},onFailure:N=>{S=N}});if(_){let N=jm(_.synopsis,B);N&&qm(N)&&(await this.opts.persistSynopsis(e,N,B.length),w=N,b=B.length,S=void 0,await E({status:"running",requestedAt:k,iter:m}),P({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:B.length}),await this.opts.onSynthesisArtifact?.(e,N,b,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Wm(N)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=B.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(w)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${b} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let B=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:k,iter:m,lastError:B}),P({sessionUpdate:"hydra_compaction",phase:"failed",error:B})}}catch(B){let _=B instanceof Error?B.message:String(B);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await E({status:"failed",requestedAt:k,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let h=await Nd({agentId:c,cwd:p,plan:l,history:o,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=jm(h.synopsis,o);m&&qm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${Wm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function jm(t,e){let n=Dm(e),s=Nm(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 qm(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 Wm(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(",")}]`}we();import*as Fe from"fs/promises";import{gzip as RI,gunzip as TI}from"zlib";import{promisify as Xm}from"util";function Km(t){return t==="summary"?"summary":"inline"}var Bu=256;function Jm(t,e){return e!=="summary"?t:t.map(II)}function II(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(Ym));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Nu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function xI(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Ym(t){if(xI(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=Nu(e.text)),typeof e.content=="string"?n.content=Nu(e.content):e.content&&typeof e.content=="object"&&(n.content=Ym(e.content)),n}function Nu(t){if(typeof t=="string"&&t.length>Bu){let e=t.length-Bu;return`${t.slice(0,Bu)}\u2026[+${e} chars omitted from summary export]`}return t}var AI=2048;function Vm(t){let e=new Set,n=s=>{if(Qm(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 Qm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function CI(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 Uu(t,e){if(!CI(t))return t;let n=t.params,s=n.update,r=await Du(s,e);return{...t,params:{...n,update:r}}}async function Du(t,e){if(typeof t=="string"){if(t.length<=AI)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 Du(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Du(r,e);return n}return t}async function Gm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await Hu(n,e);return s===n?t:{...t,params:s}}async function Hu(t,e){if(Qm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await Hu(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 Hu(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var EI=Xm(RI),PI=Xm(TI),MI=/^history\.jsonl\.(\d+)(\.gz)?$/,Wr=/^[A-Za-z0-9_-]+$/,_I=1e3,$I=1e7,FI=10,Hd=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;constructor(e={}){this.maxEntries=e.maxEntries??_I,this.archiveMaxBytes=e.archiveMaxBytes??$I,this.archiveTiers=e.archiveTiers??FI}async append(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{await Fe.mkdir(O.sessionDir(e),{recursive:!0});let s=await Uu(n,i=>Zl(e,i)),r=JSON.stringify(s)+`
295
+ `;await Fe.appendFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{await Fe.mkdir(O.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Uu(i,o=>Zl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
296
296
  `)+`
297
- `;await Ge.writeFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{let s;try{s=await Ge.readFile(O.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=s.split(`
298
- `).filter(a=>a.length>0);if(r.length<=n)return;let i=r.slice(0,r.length-n),o=r.slice(-n);this.archiveMaxBytes>0&&i.length>0&&await this.spillToArchive(e,i),await Ge.writeFile(O.historyFile(e),o.join(`
297
+ `;await Fe.writeFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Wr.test(e))return this.enqueue(e,async()=>{let s;try{s=await Fe.readFile(O.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=s.split(`
298
+ `).filter(a=>a.length>0);if(r.length<=n)return;let i=r.slice(0,r.length-n),o=r.slice(-n);this.archiveMaxBytes>0&&i.length>0&&await this.spillToArchive(e,i),await Fe.writeFile(O.historyFile(e),o.join(`
299
299
  `)+`
300
300
  `,{encoding:"utf8",mode:384})})}async spillToArchive(e,n){let s=n.join(`
301
301
  `)+`
302
- `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=O.historyArchiveFile(e,r);await Ge.mkdir(O.sessionDir(e),{recursive:!0}),await Ge.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await Ge.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?this.nextArchiveIndex.set(e,r+1):this.nextArchiveIndex.set(e,r)}async resolveNextArchiveIndex(e){let n=this.nextArchiveIndex.get(e);if(n!==void 0)return n;let s=await this.listArchiveIndices(e),r=s.length===0?0:s[s.length-1],i=r===0?1:r;if(r>0)try{(await Ge.stat(O.historyArchiveFile(e,r))).size>=this.archiveMaxBytes&&(i=r+1)}catch{i=r}return this.nextArchiveIndex.set(e,i),i}async enforceArchiveTierCap(e,n){if(this.archiveTiers<=0)return;let s=await this.listArchiveIndices(e),i=(s.includes(n)?s.length:s.length+1)-this.archiveTiers,o=0;for(;i>0&&o<s.length;){let a=s[o];if(a!==n){try{await Ge.unlink(O.historyArchiveFile(e,a))}catch(c){if(c.code!=="ENOENT")throw c}i-=1}o+=1}}async listArchiveIndices(e){let n;try{n=await Ge.readdir(O.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i=CI.exec(r);if(!i)continue;let o=Number.parseInt(i[1],10);Number.isFinite(o)&&o>0&&s.push(o)}return s.sort((r,i)=>r-i),s}async listArchives(e){return Wr.test(e)?(await this.listArchiveIndices(e)).map(s=>({index:s,path:O.historyArchiveFile(e,s)})):[]}async loadArchives(e){if(!Wr.test(e))return[];let n=this.writeQueues.get(e);n&&await n;let s=await this.listArchives(e),r=[];for(let{path:i}of s){let o;try{o=await Ge.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
303
- `)){if(a.length===0)continue;let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object"||Array.isArray(c))continue;let d=c;typeof d.method=="string"&&typeof d.recordedAt=="number"&&r.push({method:d.method,params:d.params,recordedAt:d.recordedAt})}}return r}async load(e,n={}){if(!Wr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Ge.readFile(O.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
304
- `)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async u=>{let p=d.get(u);if(p!==void 0)return p;let h=await vd(e,u);return d.set(u,h),h},f=[];for(let u of c)f.push(await Gm(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Wr.test(e))return this.enqueue(e,async()=>{try{await Ge.unlink(O.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let n=await this.listArchiveIndices(e);for(let s of n)try{await Ge.unlink(O.historyArchiveFile(e,s))}catch(r){if(r.code!=="ENOENT")throw r}this.nextArchiveIndex.delete(e),await Ph(e);try{await Ge.rmdir(O.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}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}};we();Qe();jd();Kr();Md();Ot();Ot();an();bu();var eg=900*1e3,OI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qd=FI(OI,16),Wd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>nr.spawn(a)),this.store=s??new Od,this.tombstones=r.tombstones??new Ld,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Hd({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new Dd({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,n,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,n,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let n=this.get(e);if(!n)return;let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(n,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,n,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:n,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await qi(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.registry.getAgent(e.agentId);n&&n.id!==e.agentId&&(e={...e,agentId:n.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${qd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Zi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}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=j.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 m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=j.AgentNotInstalled,m}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,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}});o=m.agentCapabilities,i.authMethods=pa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),rr(m,i)}let a;try{let m=tg(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===j.AuthRequired)throw await i.kill().catch(()=>{}),rr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
305
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Ju(a??{}),d=e.agentModes??Wu(Ku(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await zi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=qu(a??{}),u=Wu(zu(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(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ki({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Zi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:u,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}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,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await zi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ki({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Zi({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:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},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,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Jr.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:tt(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=j.AgentNotInstalled,p}let s=await bn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:zd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}})}catch(p){throw await r.kill().catch(()=>{}),rr(p,r)}if(r.authMethods=pa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=O.sessionsDir(),f=[],u=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){u+=1;continue}if(LI(p.cwd,l)){u+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!_m(m,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 ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${jt}${qd()}`,w=new Date().toISOString(),b=p.updatedAt??w,S={sessionId:y,lineageId:aa(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(S.title=p.title);let k=Mu(S);await this.store.write(k),f.push({version:1,...k})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.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=j.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,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}}),o=i.agentCapabilities;r.authMethods=pa(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=qu(a),l=zu(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==d){let h=Vi(f,l),m=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,f,m)&&(d=f);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(w=>w.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=Ku(a),p=Ju(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),rr(sg(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=j.AgentNotInstalled,o}let r=await bn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}}),a=o.agentCapabilities;i.authMethods=pa(o.authMethods);let c=tg(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=qu(d),f=Wu(zu(d)),u=Ku(d),p=Ju(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),rr(sg(o,i,n.agentId,{command:r.command,args:r.args,cwd:n.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=j.AgentNotInstalled,c}let i=await bn(r,[],{npmRegistry:this.npmRegistry}),o=n??tt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}});a.authMethods=pa(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),rr(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=j.AgentNotInstalled,s}return bn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let r=so({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=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",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),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:ig(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(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=BI(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 vd(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:NI(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,forkSynthesisState:n.forkSynthesisState,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState,attentionFlags:n.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}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=Gi(r.update.prompt),o=Iu(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(jt))return;let n=jt+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=j.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,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await ha(n.sessionId),c=so({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"warm",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await ha(s.sessionId),i=so(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}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=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>ha(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=so({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let h=u.mtime??new Date(f.updatedAt).toISOString();n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>ha(l.sessionId)));for(let l=0;l<c.length;l+=1){let f=c[l],u=d[l],p=so(f,u.hasContent);if(!r(p))continue;let h=u.mtime??f.updatedAt;n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return n.sort((l,f)=>l.updatedAt<f.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 d=aa(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await rg(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Vm(o)){let l=await Th(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}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=j.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=`${jt}${qd()}`;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 S=new Error(`source session not found: ${e}`);throw S.code=j.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=j.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,f,u,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=ku(o,n.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw k.code=j.InvalidParams,k}c=n.forkAt,a=o.slice(0,S+1)}else{let S=HI(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{n.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${n.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=j.AgentNotInstalled,k}u=S,f=s.currentModel,l="running"}let h=await rg(e),m=d==="synthesis",y={...s,lineageId:aa(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...n.model!==void 0?{currentModel:n.model}:{}},w=fa({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:be,machine:zd.hostname()}),b=`${jt}${qd()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await bn(u,[],{npmRegistry:this.npmRegistry}),k=await Nd({agentId:r,cwd:n.cwd??O.sessionDir(e),plan:S,history:o,modelId:f,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(b,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(b,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:b,forkedFromSessionId:e,forkedAt:c}}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 Eh(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Jr.utimes(O.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await zr(O.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,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await ha(e),i=so(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:n,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let n=this.pendingDeletions.get(e);n&&await n}async isTombstoned(e,n){return(await this.tombstones.read(e,n).catch(()=>{}))?.reason==="user"}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){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),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.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,n){return(await this.store.read(e))?.extensionState?.[n]??{}}async getExtensionStateKey(e,n,s){return(await this.getExtensionState(e,n))[s]}async setExtensionStateKey(e,n,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[n]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>t.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${n} would be ${c} bytes; cap is ${t.EXTENSION_STATE_CAP_BYTES}`);o[n]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[n])return;let i={...r.extensionState},o={...i[n]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[n]:i[n]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(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)}scheduleCompaction(e,n){if(n?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:n.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=n.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,n);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,n);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,n)}})();return}this.synopsisCoordinator.scheduleCompaction(e,n)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,n,s){let r=this.get(e);if(r){if(n){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:n);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),n=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;n+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}n>0&&this.logger?.info(`cleared ${n} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=n.pendingAgentSwap;if(s)try{let r=await this.histories.load(n.sessionId).catch(()=>[]);n.synopsis!==void 0&&n.summarizedThroughEntry!==void 0&&n.summarizedThroughEntry>=r.length&&n.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(n.sessionId,n.synopsis,n.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${n.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(n.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${n.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await gm(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<eg),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${eg/1e3}s)`),await ra(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 ra(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function LI(t,e){if(typeof t!="string"||t.length===0)return!1;let n=ma.resolve(t),s=ma.resolve(e);return n===s||n.startsWith(s+ma.sep)}function BI(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(),d=(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 Mu({sessionId:t.sessionId,lineageId:e?.lineageId??aa(),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:ig(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,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,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function ig(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 NI(t){return t?{...t}:void 0}function tg(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Kd(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=DI(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function qu(t){return Kd(t,{nestedKey:"models",configId:"model",fromObject:e=>ns(e.currentModelId)??ns(e.currentModel)??ns(e.modelId)??ns(e.model),fromConfig:e=>ns(e.currentValue)})}function rr(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==j.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=j.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function ng(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function sg(t,e,n,s){if(t&&typeof t=="object"&&t.code===j.AuthRequired)return t;let r=t instanceof Error?t.message:String(t),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${ng(s.cwd)} && ${[s.command,...s.args].map(ng).join(" ")})`:"";if(!o&&!a)return t;let c=[i?r:`agent ${n} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
306
- `));if(t&&typeof t=="object"){let l=t;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function pa(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.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function ns(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function DI(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 Wu(t){return t.length>0?t:void 0}function zu(t){return Kd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Xi(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Xi(e.options);return n.length>0?n:void 0}})??[]}function Ku(t){return Kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=ia(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=ia(e.options);return n.length>0?n:void 0}})??[]}function Ju(t){return Kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>ns(e.currentModeId)??ns(e.currentMode)??ns(e.modeId)??ns(e.mode),fromConfig:e=>ns(e.currentValue)})}function HI(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 rg(t){try{let e=await Jr.readFile(O.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
307
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function ha(t){try{let e=await Jr.stat(O.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function so(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===qr?!1:e?!0:void 0}import{spawn as UI}from"child_process";import*as Yd from"fs";import*as Ts from"fs/promises";import*as Vd from"path";import jI from"pino-roll";var Jd=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_}};Qe();var qI=1e3,WI=6e4,Yu=3e3,ro=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??qI,this.restartCapMs=r.restartCapMs??WI;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 Ts.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let n of this.entries.values())n.config.enabled&&e.push(this.spawn(n,0));await Promise.all(e)}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()},Yu);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 ga(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw ga(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,await this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw ga(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 ga(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).catch(s=>{n.failureReason=`spawn: ${s.message}`}),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw ga(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{}},Yu);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 Jd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ts.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.isDirectory())continue;let s=this.adapter.paths.pidFile(n.name),r;try{let i=await Ts.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Vu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Yu;for(;Date.now()<i&&Vu(r);)await new Promise(o=>setTimeout(o,50));if(Vu(r))try{process.kill(r,"SIGKILL")}catch{}}await Ts.unlink(s).catch(()=>{})}}async 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=Vd.dirname(this.adapter.paths.logFile(r.name)),a;try{await Ts.mkdir(o,{recursive:!0}),a=await jI({file:Vd.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,n+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
302
+ `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=O.historyArchiveFile(e,r);await Fe.mkdir(O.sessionDir(e),{recursive:!0}),await Fe.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await Fe.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?(await this.sealArchive(e,r),this.nextArchiveIndex.set(e,r+1)):this.nextArchiveIndex.set(e,r)}async sealArchive(e,n){let s=O.historyArchiveFile(e,n),r;try{r=await Fe.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await EI(r);await Fe.writeFile(s+".gz",i,{mode:384});try{await Fe.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}async resolveNextArchiveIndex(e){let n=this.nextArchiveIndex.get(e);if(n!==void 0)return n;let s=await this.listArchiveIndices(e),r=s.length===0?0:s[s.length-1],i=r===0?1:r;if(r>0){let o=O.historyArchiveFile(e,r),a=o+".gz",c=!1;try{await Fe.access(a),c=!0}catch{c=!1}if(c)i=r+1;else try{(await Fe.stat(o)).size>=this.archiveMaxBytes&&(i=r+1)}catch{i=r}}return this.nextArchiveIndex.set(e,i),i}async enforceArchiveTierCap(e,n){if(this.archiveTiers<=0)return;let s=await this.listArchiveIndices(e),i=(s.includes(n)?s.length:s.length+1)-this.archiveTiers,o=0;for(;i>0&&o<s.length;){let a=s[o];a!==n&&(await this.unlinkArchive(e,a),i-=1),o+=1}}async unlinkArchive(e,n){let s=O.historyArchiveFile(e,n);for(let r of[s,s+".gz"])try{await Fe.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}}async listArchiveIndices(e){let n;try{n=await Fe.readdir(O.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=new Set;for(let r of n){let i=MI.exec(r);if(!i)continue;let o=Number.parseInt(i[1],10);Number.isFinite(o)&&o>0&&s.add(o)}return[...s].sort((r,i)=>r-i)}async listArchives(e){if(!Wr.test(e))return[];let n=await this.listArchiveIndices(e),s=[];for(let r of n){let i=O.historyArchiveFile(e,r),o=i+".gz",a=i;try{await Fe.access(o),a=o}catch{a=i}s.push({index:r,path:a})}return s}async loadArchives(e){if(!Wr.test(e))return[];let n=this.writeQueues.get(e);n&&await n;let s=await this.listArchives(e),r=[];for(let{path:i}of s){let o;try{if(i.endsWith(".gz")){let a=await Fe.readFile(i);o=(await PI(a)).toString("utf8")}else o=await Fe.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
303
+ `)){if(a.length===0)continue;let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object"||Array.isArray(c))continue;let d=c;typeof d.method=="string"&&typeof d.recordedAt=="number"&&r.push({method:d.method,params:d.params,recordedAt:d.recordedAt})}}return r}async load(e,n={}){if(!Wr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Fe.readFile(O.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
304
+ `)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async u=>{let p=d.get(u);if(p!==void 0)return p;let h=await vd(e,u);return d.set(u,h),h},f=[];for(let u of c)f.push(await Gm(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Wr.test(e))return this.enqueue(e,async()=>{try{await Fe.unlink(O.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let n=await this.listArchiveIndices(e);for(let s of n)await this.unlinkArchive(e,s);this.nextArchiveIndex.delete(e),await Ph(e);try{await Fe.rmdir(O.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}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}};we();Ge();jd();Kr();Md();Ot();Ot();an();vu();var tg=900*1e3,HI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qd=DI(HI,16),Wd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>sr.spawn(a)),this.store=s??new Od,this.tombstones=r.tombstones??new Ld,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Hd({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new Dd({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,n,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,n,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let n=this.get(e);if(!n)return;let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(n,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,n,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:n,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await qi(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.registry.getAgent(e.agentId);n&&n.id!==e.agentId&&(e={...e,agentId:n.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${qd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Zi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}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=j.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 m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=j.AgentNotInstalled,m}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,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}});o=m.agentCapabilities,i.authMethods=pa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),ir(m,i)}let a;try{let m=ng(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===j.AuthRequired)throw await i.kill().catch(()=>{}),ir(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
305
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Yu(a??{}),d=e.agentModes??zu(Ju(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await zi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=Wu(a??{}),u=zu(Ku(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(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ki({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Zi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:u,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}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,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await zi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ki({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Zi({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:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},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,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Jr.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:tt(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=j.AgentNotInstalled,p}let s=await bn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:zd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}})}catch(p){throw await r.kill().catch(()=>{}),ir(p,r)}if(r.authMethods=pa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=O.sessionsDir(),f=[],u=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){u+=1;continue}if(UI(p.cwd,l)){u+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!_m(m,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 ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${jt}${qd()}`,w=new Date().toISOString(),b=p.updatedAt??w,S={sessionId:y,lineageId:aa(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(S.title=p.title);let k=_u(S);await this.store.write(k),f.push({version:1,...k})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.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=j.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,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}}),o=i.agentCapabilities;r.authMethods=pa(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=Wu(a),l=Ku(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==d){let h=Vi(f,l),m=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,f,m)&&(d=f);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(w=>w.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=Ju(a),p=Yu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ir(rg(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=j.AgentNotInstalled,o}let r=await bn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}}),a=o.agentCapabilities;i.authMethods=pa(o.authMethods);let c=ng(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=Wu(d),f=zu(Ku(d)),u=Ju(d),p=Yu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),ir(rg(o,i,n.agentId,{command:r.command,args:r.args,cwd:n.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=j.AgentNotInstalled,c}let i=await bn(r,[],{npmRegistry:this.npmRegistry}),o=n??tt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Wi,clientInfo:{name:"hydra",version:be}});a.authMethods=pa(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),ir(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=j.AgentNotInstalled,s}return bn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let r=so({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=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",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),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:og(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(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=jI(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 vd(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:qI(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,forkSynthesisState:n.forkSynthesisState,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState,attentionFlags:n.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}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=Gi(r.update.prompt),o=xu(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(jt))return;let n=jt+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=j.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,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await ha(n.sessionId),c=so({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"warm",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await ha(s.sessionId),i=so(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}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=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>ha(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=so({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let h=u.mtime??new Date(f.updatedAt).toISOString();n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>ha(l.sessionId)));for(let l=0;l<c.length;l+=1){let f=c[l],u=d[l],p=so(f,u.hasContent);if(!r(p))continue;let h=u.mtime??f.updatedAt;n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return n.sort((l,f)=>l.updatedAt<f.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 d=aa(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await ig(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Vm(o)){let l=await Th(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}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=j.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=`${jt}${qd()}`;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 S=new Error(`source session not found: ${e}`);throw S.code=j.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=j.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,f,u,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=Iu(o,n.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw k.code=j.InvalidParams,k}c=n.forkAt,a=o.slice(0,S+1)}else{let S=zI(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{n.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${n.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=j.AgentNotInstalled,k}u=S,f=s.currentModel,l="running"}let h=await ig(e),m=d==="synthesis",y={...s,lineageId:aa(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...n.model!==void 0?{currentModel:n.model}:{}},w=fa({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:be,machine:zd.hostname()}),b=`${jt}${qd()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await bn(u,[],{npmRegistry:this.npmRegistry}),k=await Nd({agentId:r,cwd:n.cwd??O.sessionDir(e),plan:S,history:o,modelId:f,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(b,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(b,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:b,forkedFromSessionId:e,forkedAt:c}}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 Eh(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Jr.utimes(O.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await zr(O.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,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await ha(e),i=so(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:n,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let n=this.pendingDeletions.get(e);n&&await n}async isTombstoned(e,n){return(await this.tombstones.read(e,n).catch(()=>{}))?.reason==="user"}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){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),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.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,n){return(await this.store.read(e))?.extensionState?.[n]??{}}async getExtensionStateKey(e,n,s){return(await this.getExtensionState(e,n))[s]}async setExtensionStateKey(e,n,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[n]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>t.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${n} would be ${c} bytes; cap is ${t.EXTENSION_STATE_CAP_BYTES}`);o[n]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[n])return;let i={...r.extensionState},o={...i[n]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[n]:i[n]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(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)}scheduleCompaction(e,n){if(n?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:n.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=n.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,n);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,n);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,n)}})();return}this.synopsisCoordinator.scheduleCompaction(e,n)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,n,s){let r=this.get(e);if(r){if(n){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:n);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),n=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;n+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}n>0&&this.logger?.info(`cleared ${n} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=n.pendingAgentSwap;if(s)try{let r=await this.histories.load(n.sessionId).catch(()=>[]);n.synopsis!==void 0&&n.summarizedThroughEntry!==void 0&&n.summarizedThroughEntry>=r.length&&n.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(n.sessionId,n.synopsis,n.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${n.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(n.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${n.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await gm(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<tg),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${tg/1e3}s)`),await ra(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 ra(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function UI(t,e){if(typeof t!="string"||t.length===0)return!1;let n=ma.resolve(t),s=ma.resolve(e);return n===s||n.startsWith(s+ma.sep)}function jI(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(),d=(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 _u({sessionId:t.sessionId,lineageId:e?.lineageId??aa(),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:og(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,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,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function og(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 qI(t){return t?{...t}:void 0}function ng(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Kd(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=WI(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Wu(t){return Kd(t,{nestedKey:"models",configId:"model",fromObject:e=>ns(e.currentModelId)??ns(e.currentModel)??ns(e.modelId)??ns(e.model),fromConfig:e=>ns(e.currentValue)})}function ir(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==j.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=j.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function sg(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function rg(t,e,n,s){if(t&&typeof t=="object"&&t.code===j.AuthRequired)return t;let r=t instanceof Error?t.message:String(t),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${sg(s.cwd)} && ${[s.command,...s.args].map(sg).join(" ")})`:"";if(!o&&!a)return t;let c=[i?r:`agent ${n} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
306
+ `));if(t&&typeof t=="object"){let l=t;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function pa(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.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function ns(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function WI(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 Ku(t){return Kd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Xi(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Xi(e.options);return n.length>0?n:void 0}})??[]}function Ju(t){return Kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=ia(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=ia(e.options);return n.length>0?n:void 0}})??[]}function Yu(t){return Kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>ns(e.currentModeId)??ns(e.currentMode)??ns(e.modeId)??ns(e.mode),fromConfig:e=>ns(e.currentValue)})}function zI(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 ig(t){try{let e=await Jr.readFile(O.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
307
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function ha(t){try{let e=await Jr.stat(O.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function so(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===qr?!1:e?!0:void 0}import{spawn as KI}from"child_process";import*as Yd from"fs";import*as Ts from"fs/promises";import*as Vd from"path";import JI from"pino-roll";var Jd=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_}};Ge();var YI=1e3,VI=6e4,Vu=3e3,ro=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??YI,this.restartCapMs=r.restartCapMs??VI;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 Ts.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let n of this.entries.values())n.config.enabled&&e.push(this.spawn(n,0));await Promise.all(e)}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()},Vu);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 ga(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw ga(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,await this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw ga(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 ga(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).catch(s=>{n.failureReason=`spawn: ${s.message}`}),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw ga(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{}},Vu);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 Jd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ts.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.isDirectory())continue;let s=this.adapter.paths.pidFile(n.name),r;try{let i=await Ts.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Qu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Vu;for(;Date.now()<i&&Qu(r);)await new Promise(o=>setTimeout(o,50));if(Qu(r))try{process.kill(r,"SIGKILL")}catch{}}await Ts.unlink(s).catch(()=>{})}}async 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=Vd.dirname(this.adapter.paths.logFile(r.name)),a;try{await Ts.mkdir(o,{recursive:!0}),a=await JI({file:Vd.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,n+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
308
308
  `);let c=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=c,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:c,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[l,...f]=i;if(l===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
309
- `),a.end();return}let u=tt(l),p=[...f,...r.args].map(tt),h;try{h=UI(u,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
309
+ `),a.end();return}let u=tt(l),p=[...f,...r.args].map(tt),h;try{h=KI(u,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
310
310
  `),a.end(),this.scheduleRestart(e,n);return}let m=y=>{try{a.write(typeof y=="string"?y:y.toString())}catch{}};if(h.stdout?.on("data",m),h.stderr?.on("data",m),typeof h.pid=="number")try{Yd.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
311
311
  `,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${y.message}
312
312
  `)}e.child=h,e.logStream=a,e.pid=typeof h.pid=="number"?h.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,h.on("error",y=>{a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${y.message}
313
313
  `)}),h.on("exit",(y,w)=>{try{Yd.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${w??"null"}
314
314
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof y=="number"?y:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let b=e.exitWaiters.splice(0);for(let k of b)k();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let S=e.breaker.recordExit(y,r.name,this.adapter.kind);if(typeof S=="object"){e.failureReason=S.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${S.tripped}
315
- `);try{a.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).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Vu(t){try{return process.kill(t,0),!0}catch{return!1}}function ga(t,e){return t.code=e,t}we();var zI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:O.extensionsDir,logFile:O.extensionLogFile,pidFile:O.extensionPidFile}},Qd=class extends ro{constructor(e,n,s={}){super(e,zI,n,s)}};we();var KI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:O.transformersDir,logFile:O.transformerLogFile,pidFile:O.transformerPidFile}},Gd=class extends ro{connected=new Map;constructor(e,n,s={}){super(e,KI,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}interestedIn(e){let n=[];for(let s of this.connected.values())s.intercepts.has(e)&&n.push(s);return n}};var Xd=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{}}};we();Ni();Ui();we();Ui();import*as wa from"fs/promises";import*as Zd from"path";var ya=t=>{process.stderr.write(t+`
316
- `)};function Qu(t){ya=t??(e=>process.stderr.write(e+`
317
- `))}async function og(t,e){let n=wn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Zd.join(O.agentsDir(),n),a;try{a=await wa.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ya(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let f=i.get(d)??new Set,u=Zd.join(o,d),p;try{p=await wa.readdir(u,{withFileTypes:!0})}catch(h){ya(`hydra-acp: prune: failed to read ${u}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||f.has(m)||m.includes(".partial-"))continue;let y=Zd.join(u,m);try{await wa.rm(y,{recursive:!0,force:!0}),ya(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(w){ya(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function ag(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await au(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 c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Gu(t){let e=t.maxDeletions??200,n=(p,h)=>{t.logger&&t.logger[p](`session-gc: ${h}`)},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 m=Date.parse(p.updatedAt);Number.isFinite(m)&&(t.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,n("warn",`delete ${p} failed: ${h.message}`)}let f=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${JI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:d,failed:l,deferred:f};return c!==void 0&&(u.oldestLastUsedMs=c),u}function dg(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Gu({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 JI(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`}an();ba();we();Or();import*as ug from"path";import{createHash as VI,randomBytes as QI,timingSafeEqual as GI}from"crypto";var fg="hydra_session_",XI=3600*24*30,cg=12,ZI=32,ex=50;function tx(){return ug.join(O.home(),"session-tokens.json")}function lg(t){return VI("sha256").update(t).digest("hex")}function pg(t){return QI(t).toString("hex")}function nx(){return pg(cg).slice(0,cg*2)}function sx(){return`${fg}${pg(ZI)}`}var ec=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=tx(),s=await yn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(rx));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=sx(),s=lg(n),r=nx(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:XI,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(fg))return;let n=lg(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||!GI(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(()=>{})},ex))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>nn(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 rx(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")}xs();var hg="Bearer ",tc=class{constructor(e){this.token=e}token;async validate(e){return ix(e,this.token)?"service":void 0}},nc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},sc=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 mg(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(hg)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(hg.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function gg(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 rc=class{tokens=new Map;mint(e,n){let s=$i();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 ix(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 ic=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)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};we();Qe();ef();Kr();dc();import*as rf from"fs";import*as ka from"os";import*as Lg from"path";import*as of from"readline";or();es();function cc(t,e={}){let n=$x(t),s=Fx(n),r=[];Ox(r,t),Lx(r,n,s,e.includeTools??!1);let i=r.join(`
315
+ `);try{a.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).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Qu(t){try{return process.kill(t,0),!0}catch{return!1}}function ga(t,e){return t.code=e,t}we();var QI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:O.extensionsDir,logFile:O.extensionLogFile,pidFile:O.extensionPidFile}},Qd=class extends ro{constructor(e,n,s={}){super(e,QI,n,s)}};we();var GI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:O.transformersDir,logFile:O.transformerLogFile,pidFile:O.transformerPidFile}},Gd=class extends ro{connected=new Map;constructor(e,n,s={}){super(e,GI,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}interestedIn(e){let n=[];for(let s of this.connected.values())s.intercepts.has(e)&&n.push(s);return n}};var Xd=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{}}};we();Ni();Ui();we();Ui();import*as wa from"fs/promises";import*as Zd from"path";var ya=t=>{process.stderr.write(t+`
316
+ `)};function Gu(t){ya=t??(e=>process.stderr.write(e+`
317
+ `))}async function ag(t,e){let n=wn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Zd.join(O.agentsDir(),n),a;try{a=await wa.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ya(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let f=i.get(d)??new Set,u=Zd.join(o,d),p;try{p=await wa.readdir(u,{withFileTypes:!0})}catch(h){ya(`hydra-acp: prune: failed to read ${u}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||f.has(m)||m.includes(".partial-"))continue;let y=Zd.join(u,m);try{await wa.rm(y,{recursive:!0,force:!0}),ya(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(w){ya(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function dg(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await du(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 c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Xu(t){let e=t.maxDeletions??200,n=(p,h)=>{t.logger&&t.logger[p](`session-gc: ${h}`)},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 m=Date.parse(p.updatedAt);Number.isFinite(m)&&(t.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,n("warn",`delete ${p} failed: ${h.message}`)}let f=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${XI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:d,failed:l,deferred:f};return c!==void 0&&(u.oldestLastUsedMs=c),u}function cg(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Xu({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 XI(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`}an();ba();we();Or();import*as fg from"path";import{createHash as ex,randomBytes as tx,timingSafeEqual as nx}from"crypto";var pg="hydra_session_",sx=3600*24*30,lg=12,rx=32,ix=50;function ox(){return fg.join(O.home(),"session-tokens.json")}function ug(t){return ex("sha256").update(t).digest("hex")}function hg(t){return tx(t).toString("hex")}function ax(){return hg(lg).slice(0,lg*2)}function dx(){return`${pg}${hg(rx)}`}var ec=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=ox(),s=await yn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(cx));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=dx(),s=ug(n),r=ax(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:sx,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(pg))return;let n=ug(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||!nx(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(()=>{})},ix))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>nn(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 cx(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")}xs();var mg="Bearer ",tc=class{constructor(e){this.token=e}token;async validate(e){return lx(e,this.token)?"service":void 0}},nc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},sc=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 gg(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(mg)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(mg.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function yg(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 rc=class{tokens=new Map;mint(e,n){let s=$i();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 lx(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 ic=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)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};we();Ge();tf();Kr();dc();import*as of from"fs";import*as ka from"os";import*as Bg from"path";import*as af from"readline";ar();es();function cc(t,e={}){let n=Nx(t),s=Dx(n),r=[];Hx(r,t),Ux(r,n,s,e.includeTools??!1);let i=r.join(`
318
318
  `);return i.endsWith(`
319
319
  `)||(i+=`
320
- `),i}function $x(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=ss(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Fx(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 Ox(t,e){let n=e.session,s=pt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${ao(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 c=[];if(a.used!==void 0){let d=a.size!==void 0?`${nf(a.size)}`:void 0;c.push(d?`${nf(a.used)} / ${d} tokens`:`${nf(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
321
- `)),t.push("")}function Lx(t,e,n,s){if(!e.some(p=>Bx(p.event))){t.push("_No conversation history recorded._"),t.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)t.push(p);t.push(""),a=[]}},f=()=>{l(),o.length>0&&(Rg(t,o.trimEnd(),"*"),t.push(""),o=""),i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},u=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{f(),t.push("---"),t.push(""),r+=1,Rg(t,p.text,"**"),t.push(""),d=!0;break}case"agent-text":u(),i+=p.text;break;case"agent-thought":{u(),i.length>0&&(t.push(i.trimEnd()),t.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(u(),(i.length>0||o.length>0)&&f(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=n.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${Dx(h.status)} ${Nx(h)}`);break}case"tool-call-update":break;case"plan":{u(),f(),t.push("**Plan:**"),t.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";t.push(`- ${m} ${ao(h.content)}`)}t.push("");break}case"mode-changed":u(),f(),t.push(`_mode: ${ao(p.mode)}_`),t.push("");break;case"model-changed":u(),f(),t.push(`_model: ${ao(p.model)}_`),t.push("");break;case"turn-complete":f();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}f()}function Bx(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Nx(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${ao(t.title)}${n}`}function Dx(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 Rg(t,e,n){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
322
- `);for(let a=0;a<o.length;a++){let c=o[a],d=ao(c);t.push(a===0&&a===o.length-1?`${n}${d}${n}`:a===0?`${n}${d}`:a===o.length-1?`${d}${n}`:d)}r<s.length-1&&t.push("")}}function ao(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function nf(t){return t.toLocaleString("en-US")}Ot();an();Go();or();function Hx(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,c=[];for(let l of s){let f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>Ux(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function Ux(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Tg(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:Tg(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Tg(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function jx(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var qx=5,Wx=200,Eg=30;async function _g(t,e,n={}){let s=Hx(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??qx,i=n.maxSessions??Wx,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(f=>o.has(f.sessionId)):a,d=[],l=!1;for(let f of c){if(d.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=zx(u,s,r);if(p.snippets.length===0)continue;let h={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(h.title=f.title),d.push(h)}return{query:e,truncated:l,results:d}}function zx(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=Kx(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 Kx(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=Jx(a).filter(d=>jx(n,d.kind));for(let d of c){let l=d.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),h={kind:d.kind,text:Xx(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Jx(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=lc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?wt(s.text):lc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Qx(s))return[];let i=lc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Gx(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Yx(s);default:return[]}}function Yx(t){let e=Pg(t,"name"),n=Pg(t,"title"),s=[];if(n!==void 0){let a=Pe(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=Pe(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Mg(r);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Mg(i);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Vx(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Vx(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=Pe(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=Pe(s);if(r.length>0)return r}}return null}function Qx(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 lc(t){if(typeof t=="string")return wt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?wt(e.text):""}function Gx(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=lc(n);s.length>0&&e.push(s)}return e.join("")}function Pg(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Mg(t){try{return JSON.stringify(t)}catch{return""}}function Xx(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-Eg),c=Math.min(s.length,o+i.length+Eg),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Fg}from"crypto";function $g(t){let e=Fg(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function sf(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push($g({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push($g({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=co(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function co(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=Fg(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 uc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Og(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!Lr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Bg(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,f=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:f})}}),t.get("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.getOne(u);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let f=d.body??{},u=typeof f.q=="string"?f.q:"";if(u.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await _g(e,u,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let f=d.body??{},u=tt(f.cwd??n.cwd),p=f.agentId??n.agentId,h=co(s),m=h!==void 0?[...f.mcpServers??[],...h.descriptors]:f.mcpServers;try{let y=await e.create({cwd:u,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),t.post("/v1/sessions/collect",async(d,l)=>{let f=d.body??{},u=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,p=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,h=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await Gu({manager:e,maxAgeMs:u,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>Lg.join(ka.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(w){return l.code(409).send({error:w.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(u,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(u)!==void 0||await e.hasRecord(u))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(u),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(u,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(u),await e.hasRecord(u)&&await e.deleteRecord(u),l.code(204).send();return}if(!await e.deleteRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.query?.tools,h=p==="references"?"references":Km(p),m=await e.exportBundle(u,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=fa({record:m.record,history:h==="summary"?Jm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:be,machine:ka.hostname(),hydraHost:Og(n)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${u}-${w}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,w=io(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:oo(b.hunks)}))),l.code(200).send(w)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let f=d.params,u=await e.resolveCanonicalId(f.id)??f.id,p=await e.loadToolBlob(u,f.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=fa({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:be,machine:ka.hostname(),hydraHost:Og(n)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(cc(h,{includeTools:y}))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=tt(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(u,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===j.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===j.InvalidParams||y.code===j.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),t.post("/v1/sessions/import",async(d,l)=>{let f=d.body??{};if(f.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let u;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}u=f.cwd}let p;try{p=On(f.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:f.replace===!0,...u!==void 0?{cwd:u}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===j.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(u),h===void 0&&!await e.hasRecord(u))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(u),y=await e.getRollbackBreadcrumb(u),w=!1,b,k=await e.getHistory(u).catch(()=>[])??[];if(k.length>0&&n.compaction){let A=h??0,E=k.length,B=k.slice(A).reduce((L,K)=>L+JSON.stringify(K.params).length,0);b=Zu(B);let _=p?.currentModel,D=k.at(-1).recordedAt,N=p?.currentUsage;w=yg({summarizedThroughEntry:A,totalEntries:E,unsummarizedChars:B,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:D,nowMs:Date.now(),config:n.compaction,...typeof N?.used=="number"?{agentReportedUsed:N.used}:{},...typeof N?.size=="number"?{agentReportedSize:N.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f;if(e.get(u)){e.scheduleCompaction(u),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(u),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(u),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let f=d.params.id,u=d.query,p=u?.follow==="1"||u?.follow==="true",h=await e.resolveCanonicalId(f)??f,m=e.get(h),y,w,b=!1,S=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
320
+ `),i}function Nx(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=ss(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Dx(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 Hx(t,e){let n=e.session,s=pt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${ao(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 c=[];if(a.used!==void 0){let d=a.size!==void 0?`${sf(a.size)}`:void 0;c.push(d?`${sf(a.used)} / ${d} tokens`:`${sf(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
321
+ `)),t.push("")}function Ux(t,e,n,s){if(!e.some(p=>jx(p.event))){t.push("_No conversation history recorded._"),t.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)t.push(p);t.push(""),a=[]}},f=()=>{l(),o.length>0&&(Tg(t,o.trimEnd(),"*"),t.push(""),o=""),i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},u=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{f(),t.push("---"),t.push(""),r+=1,Tg(t,p.text,"**"),t.push(""),d=!0;break}case"agent-text":u(),i+=p.text;break;case"agent-thought":{u(),i.length>0&&(t.push(i.trimEnd()),t.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(u(),(i.length>0||o.length>0)&&f(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=n.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${Wx(h.status)} ${qx(h)}`);break}case"tool-call-update":break;case"plan":{u(),f(),t.push("**Plan:**"),t.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";t.push(`- ${m} ${ao(h.content)}`)}t.push("");break}case"mode-changed":u(),f(),t.push(`_mode: ${ao(p.mode)}_`),t.push("");break;case"model-changed":u(),f(),t.push(`_model: ${ao(p.model)}_`),t.push("");break;case"turn-complete":f();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}f()}function jx(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function qx(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${ao(t.title)}${n}`}function Wx(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 Tg(t,e,n){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
322
+ `);for(let a=0;a<o.length;a++){let c=o[a],d=ao(c);t.push(a===0&&a===o.length-1?`${n}${d}${n}`:a===0?`${n}${d}`:a===o.length-1?`${d}${n}`:d)}r<s.length-1&&t.push("")}}function ao(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function sf(t){return t.toLocaleString("en-US")}Ot();an();Go();ar();function zx(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,c=[];for(let l of s){let f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>Kx(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function Kx(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Eg(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:Eg(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Eg(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Jx(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Yx=5,Vx=200,Pg=30;async function $g(t,e,n={}){let s=zx(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Yx,i=n.maxSessions??Vx,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(f=>o.has(f.sessionId)):a,d=[],l=!1;for(let f of c){if(d.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Qx(u,s,r);if(p.snippets.length===0)continue;let h={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(h.title=f.title),d.push(h)}return{query:e,truncated:l,results:d}}function Qx(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=Gx(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 Gx(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=Xx(a).filter(d=>Jx(n,d.kind));for(let d of c){let l=d.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),h={kind:d.kind,text:sA(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Xx(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=lc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?wt(s.text):lc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(tA(s))return[];let i=lc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=nA(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Zx(s);default:return[]}}function Zx(t){let e=Mg(t,"name"),n=Mg(t,"title"),s=[];if(n!==void 0){let a=Pe(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=Pe(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=_g(r);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=_g(i);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=eA(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function eA(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=Pe(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=Pe(s);if(r.length>0)return r}}return null}function tA(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 lc(t){if(typeof t=="string")return wt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?wt(e.text):""}function nA(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=lc(n);s.length>0&&e.push(s)}return e.join("")}function Mg(t,e){let n=t[e];return typeof n=="string"?n:void 0}function _g(t){try{return JSON.stringify(t)}catch{return""}}function sA(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-Pg),c=Math.min(s.length,o+i.length+Pg),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Og}from"crypto";function Fg(t){let e=Og(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function rf(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push(Fg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Fg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=co(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function co(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=Og(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 uc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Lg(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!Lr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Ng(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,f=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:f})}}),t.get("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.getOne(u);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let f=d.body??{},u=typeof f.q=="string"?f.q:"";if(u.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await $g(e,u,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let f=d.body??{},u=tt(f.cwd??n.cwd),p=f.agentId??n.agentId,h=co(s),m=h!==void 0?[...f.mcpServers??[],...h.descriptors]:f.mcpServers;try{let y=await e.create({cwd:u,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),t.post("/v1/sessions/collect",async(d,l)=>{let f=d.body??{},u=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,p=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,h=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await Xu({manager:e,maxAgeMs:u,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>Bg.join(ka.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(w){return l.code(409).send({error:w.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(u,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(u)!==void 0||await e.hasRecord(u))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(u),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(u,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(u),await e.hasRecord(u)&&await e.deleteRecord(u),l.code(204).send();return}if(!await e.deleteRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.query?.tools,h=p==="references"?"references":Km(p),m=await e.exportBundle(u,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=fa({record:m.record,history:h==="summary"?Jm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:be,machine:ka.hostname(),hydraHost:Lg(n)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${u}-${w}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,w=io(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:oo(b.hunks)}))),l.code(200).send(w)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let f=d.params,u=await e.resolveCanonicalId(f.id)??f.id,p=await e.loadToolBlob(u,f.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=fa({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:be,machine:ka.hostname(),hydraHost:Lg(n)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(cc(h,{includeTools:y}))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=tt(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(u,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===j.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===j.InvalidParams||y.code===j.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),t.post("/v1/sessions/import",async(d,l)=>{let f=d.body??{};if(f.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let u;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}u=f.cwd}let p;try{p=On(f.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:f.replace===!0,...u!==void 0?{cwd:u}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===j.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(u),h===void 0&&!await e.hasRecord(u))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(u),y=await e.getRollbackBreadcrumb(u),w=!1,b,k=await e.getHistory(u).catch(()=>[])??[];if(k.length>0&&n.compaction){let A=h??0,E=k.length,B=k.slice(A).reduce((L,K)=>L+JSON.stringify(K.params).length,0);b=ef(B);let _=p?.currentModel,D=k.at(-1).recordedAt,N=p?.currentUsage;w=wg({summarizedThroughEntry:A,totalEntries:E,unsummarizedChars:B,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:D,nowMs:Date.now(),config:n.compaction,...typeof N?.used=="number"?{agentReportedUsed:N.used}:{},...typeof N?.size=="number"?{agentReportedSize:N.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f;if(e.get(u)){e.scheduleCompaction(u),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(u),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(u),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let f=d.params.id,u=d.query,p=u?.follow==="1"||u?.follow==="true",h=await e.resolveCanonicalId(f)??f,m=e.get(h),y,w,b=!1,S=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
323
323
  `):(k.push(E),k.length>S&&k.shift()))})),d.raw.on("close",()=>{w?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(E){throw w?.(),E}}else{let E=await e.getHistory(h);if(E===void 0)return l.code(404).send({error:"session not found"}),l;y=E}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let A=new Set;for(let E of y??[]){l.raw.write(JSON.stringify(E)+`
324
324
  `);let P=E;typeof P.recordedAt=="number"&&A.add(String(P.recordedAt))}for(;k.length>0;){let E=k.splice(0,k.length);for(let P of E){let B=P,_=typeof B.recordedAt=="number"?String(B.recordedAt):"";_&&A.has(_)||l.raw.write(JSON.stringify(P)+`
325
- `)}}return b=!0,w||l.raw.end(),l});function r(d,l,f){let u=typeof d=="string"?d.trim():"";if(u.length===0)return null;let p;try{p=JSON.parse(u)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||f!==void 0&&h.recordedAt<f||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!l.has(w)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,f){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:f,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,f,u){for await(let p of l){let h=r(p,f,u);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,f,u){let p=of.createInterface({input:rf.createReadStream(l),crlfDelay:1/0}),h=o(d,p,f,u),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}t.get("/v1/sessions/events",async(d,l)=>{let f=d.query,u=f.kinds;if(!u||u.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=u.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!uc.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...uc].join(", ")}`}),l;let h=new Set(p),m;if(f.since!==void 0&&f.since.trim().length>0){let S=new Date(f.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),w=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let b=[];for(let S of w)try{let k=O.historyFile(S.sessionId),A=await a(S.sessionId,k,h,m);A.exhausted||b.push(A)}catch(k){if(k.code==="ENOENT")continue;throw k}d.raw.on("close",()=>{for(let S of b)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;b.length>0;){let S=-1,k=1/0;for(let E=0;E<b.length;E++){let P=b[E];P.current!==null&&P.current.ts<k&&(k=P.current.ts,S=E)}if(S===-1)break;let A=b[S];if(l.raw.write(JSON.stringify(A.current.row)+`
326
- `),await c(A),A.exhausted){try{A.rl.close()}catch{}b.splice(S,1)}}}catch(S){for(let k of b)try{k.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let f=d.params.id,u=d.query,p=await e.resolveCanonicalId(f)??f;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=u.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(E=>E.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let E of y)if(!uc.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...uc].join(", ")}`}),l;let w=new Set(y),b;if(u.since!==void 0&&u.since.trim().length>0){let E=new Date(u.since);if(isNaN(E.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;b=E.getTime()}let S=O.historyFile(p),k=rf.createReadStream(S),A=of.createInterface({input:k,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let E of A){let P=typeof E=="string"?E.trim():"";if(P.length===0)continue;let B;try{B=JSON.parse(P)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!B||typeof B!="object"||Array.isArray(B)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let _=B;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let D=_.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let N=D.update,L=N.sessionUpdate;if(typeof L!="string"||!w.has(L)||b!==void 0&&_.recordedAt<b)continue;let K={ts:new Date(_.recordedAt).toISOString(),kind:L,update:N};N.messageId!==void 0&&N.messageId!==null&&(K.messageId=N.messageId),l.raw.write(JSON.stringify(K)+`
327
- `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);return!p&&!await e.hasRecord(u)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(u))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let f=d.query;if(!f.source||f.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let u=await e.list({includeNonInteractive:!0}),p=[];for(let h of u){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let w of y)w.source===f.source&&p.push({...w,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let w=e.get(u);if(w){if(m.length>0&&y.length>0)w.clearAttentionFlag(m,y);else{let E=Array.from(w.listAttentionFlags()).map(P=>`${P.source}::${P.reason}`);for(let P of E)w.clearAttentionFlag(P.split("::")[0],P.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}let b=e.store,S=await b.read(u);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],A;if(m.length>0&&y.length>0){let E=`${m}::${y}`;A=k.filter(P=>`${P.source}::${P.reason}`!==E)}else A=[];if(A.length===k.length&&A.every((E,P)=>E.source===k[P].source&&E.reason===k[P].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:A}),l.code(204).send()})}Ot();function Ng(t,e,n,s={}){t.get("/v1/agents",async()=>qi(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 c=await bn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===j.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function Dg(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var Zx=/^[A-Za-z0-9._-]+$/;function fc(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=eA(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){Ia(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){Ia(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}})}function Ia(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 eA(t){let e=t.name;if(typeof e!="string"||!Zx.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 Hg(t,e){fc(t,"extension",e)}function Ug(t,e){fc(t,"transformer",e)}function jg(t,e){t.get("/v1/config",async()=>e)}import{z as lo}from"zod";we();import*as ar from"fs/promises";import*as Kg from"path";import{randomBytes as tA,scrypt as nA,timingSafeEqual as sA}from"crypto";import{promisify as rA}from"util";var Jg=rA(nA);function af(){return Kg.join(O.home(),"password-hash")}var qg=32768,Wg=8,zg=1,iA=64,oA=16,Yg=128*1024*1024;async function Vg(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=tA(oA),n=await Jg(t,e,iA,{N:qg,r:Wg,p:zg,maxmem:Yg}),s=`scrypt$${qg}$${Wg}$${zg}$${e.toString("hex")}$${n.toString("hex")}
328
- `;await ar.mkdir(O.home(),{recursive:!0}),await ar.writeFile(af(),s,{encoding:"utf8",mode:384})}async function pc(){try{return(await ar.readFile(af(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hc(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await ar.readFile(af(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}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 c=await Jg(t,o,a.length,{N:s,r,p:i,maxmem:Yg});return c.length!==a.length?!1:sA(c,a)}var aA=lo.object({password:lo.string().min(1),label:lo.string().min(1).max(256).optional(),ttlSec:lo.number().int().positive().optional()}),dA=lo.object({id:lo.string().optional()}).optional();function Qg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=cA(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=aA.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await pc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await hc(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=dA.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 cA(t){return t.ip||"unknown"}jr();uo();import{nanoid as df}from"nanoid";Md();Ot();an();import{randomBytes as Xg}from"crypto";import*as Zg from"os";import*as ey from"path";function se(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function hA(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function dn(t,e,n){let s=t.get(e);if(!s)throw se(j.SessionNotFound,n??`session ${e} not found`);return s}async function mc(t,e){let n=co(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Xg(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=sf({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,f=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{f.unbind(l)})}return IA(d,t),ny(d.sessionId,t),d}function ty(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=gg({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=rs(n),a=new Kt(o),c={clientId:`hydra_client_${df(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let d=(f,u)=>{if(c.attached.get(f)?.readonly)throw se(j.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=jh.parse(f??{});u.clientInfo?.name&&(c.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)),kA()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return f.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let S={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(S.outputSchema=b.outputSchema),S}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,y),{ok:!0,registered:y.length}});let u=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw se(j.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=u(p);if(!e.manager)throw se(j.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(m.value===void 0)throw se(j.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(j.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(j.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(j.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{f.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async u=>{let p=u??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw se(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw se(-32602,"emit_message requires method");let b=dn(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return b.dischargeClaim(S,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return dn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async u=>wA(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let p=u??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,S=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let P=e.manager.get(y);P&&(m=P.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:S,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,b=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let f=async(u,p)=>{let h=u??{};if(typeof h.sessionId!="string")throw se(j.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async u=>(await f(u,"session/delete"),{})),a.onRequest("session/close",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(j.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async u=>{let{id:p,existed:h}=await f(u,"hydra-acp/session/delete");if(!h)throw se(j.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw se(-32602,"await_child requires childSessionId");let w=dn(e.manager,h,`child session ${h} not found`);return new Promise(b=>{let A=[],E=[],P=0,B=!1,_,D,N=!1,L=()=>{N||(N=!0,clearTimeout(K),_?.(),D?.(),b(B?{entries:A,truncated:!0}:{entries:A}))};_=w.onBroadcast(X=>{let Z=hA(X);for(A.push(X),E.push(Z),P+=Z;A.length>0&&(A.length>1e3||P>1048576);)A.shift(),P-=E.shift()??0,B=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&L()});let K=setTimeout(L,y);typeof K.unref=="function"&&K.unref(),D=w.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>bA(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>vA(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let p=u??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw se(j.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,h=await e.manager.loadToolBlob(p,u.hash);if(h===null)throw se(j.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async f=>mA(f,e)),a.onRequest("logout",async f=>gA(f,e)),a.onRequest("session/new",async f=>{let u=qh.parse(f),p=rn(f?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(L=>typeof L=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,w,b=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Xg(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let K={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...u.mcpServers??[],K]}let S,k,A=co(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=sf({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Gg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(L){throw w!==void 0&&w.abandon(L instanceof Error?L:void 0),k!==void 0&&k.abandon(L instanceof Error?L:void 0),A!==void 0&&A.abandon(L instanceof Error?L:void 0),L}if(y!==void 0&&w!==void 0&&e.mcpTokenRegistry!==void 0){let L=y,K=e.mcpTokenRegistry;w.complete(P),P.onClose(()=>{K.unbind(L)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let L=S,K=e.mcpTokenRegistry;k.complete(P),P.onClose(()=>{K.unbind(L)})}A!==void 0&&A.bindToSession(P),ny(P.sessionId,e);let B,_;try{bc(c,P,P.sessionId),B=xa(a,P,c),{entries:_}=await P.attach(B,"full")}catch(L){throw await P.close({deleteRecord:!1}).catch(()=>{}),L}c.attached.set(P.sessionId,{sessionId:P.sessionId,clientId:B.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let L of _){if(a.isClosed())break;await a.notify(L.method,L.params).catch(()=>{})}})()});let D=gc(P),N=yc(P);return{sessionId:P.sessionId,...D?{modes:D}:{},...N?{models:N}:{},configOptions:P.buildConfigOptions(),_meta:wc(e.manager,P,{clientId:B.clientId})}}),a.onRequest("session/attach",async f=>{let u=zh.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=rn(u._meta),m=h.resume,y=h.readonly===!0,w=h.env;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,S=e.manager.get(b);if(!S&&y){let N=await e.manager.loadFromDisk(b);if(!N)throw se(j.SessionNotFound,`session ${u.sessionId} not found`);let L=await e.manager.loadHistory(b),K=u.clientId??`cli_${df(8)}`;c.attached.set(N.hydraSessionId,{sessionId:N.hydraSessionId,clientId:K,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${N.hydraSessionId} clientId=${K} attachedCount=${c.attached.size} replayed=${L.length}`);for(let X of L)await a.notify(X.method,X.params).catch(()=>{});return{sessionId:N.hydraSessionId,clientId:K,connectedClients:[K],historyPolicy:"full",replayed:L.length,_meta:SA(N)}}let k=!S;if(!S){let N=await e.manager.loadFromDisk(b),L=N;if(m&&(L={...N,hydraSessionId:u.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!L)throw se(j.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(L.agentId,L.upstreamSessionId))throw se(j.SessionNotFound,`session ${u.sessionId} was deleted`);let K=L.originatingClient?L:{...L,originatingClient:c.clientInfo},X=w!==void 0?{...K,forwardedEnv:w}:K;S=await mc(e,{...X,onInstallProgress:Gg(a)})}bc(c,S,S.sessionId);let A=xa(a,S,c,u.clientInfo,u.clientId),E=h.replayMode==="drip",{entries:P,appliedPolicy:B}=await S.attach(A,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(S.sessionId,w).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${B} replayed=${P.length} readonly=${y}${E?" replayMode=drip":""}`),E){let N=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,L=750;(async()=>{let K=null;for(let X of P){let Z=typeof X.recordedAt=="number"?X.recordedAt:null;if(K!==null&&Z!==null){let Q=Math.min(L,Math.max(0,(Z-K)/N));Q>0&&await new Promise(fe=>setTimeout(fe,Q))}Z!==null&&(K=Z);try{await a.notify(X.method,X.params)}catch{return}}})()}else for(let N=0;N<P.length&&!a.isClosed();N++){let L=P[N],K=a.notify(L.method,L.params).catch(()=>{});(N+1)%200===0&&await K}S.replayPendingPermissions(A);let _=gc(S),D=yc(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:B,replayed:P.length,..._?{modes:_}:{},...D?{models:D}:{},configOptions:S.buildConfigOptions(),_meta:wc(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async f=>{let u=Kh.parse(f),p=c.attached.get(u.sessionId);if(!p)throw se(j.SessionNotFound,"client not attached to that session");let h=e.manager.get(u.sessionId);return h?.detach(p.clientId),c.attached.delete(u.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[Ft]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=Jh.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==qr).map(Yh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(j.InternalError,"agent registry unavailable");return qi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let u=f??{};if(typeof u.agentId!="string"||u.agentId.length===0)throw se(j.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(u.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let u=Vh.parse(f);d(u.sessionId,"session/prompt");let p=c.attached.get(u.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),se(j.SessionNotFound,"not attached to session");let h=e.manager.get(u.sessionId);if(!h){let m=await e.manager.loadFromDisk(u.sessionId);if(!m)throw se(j.SessionNotFound,`session ${u.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),h=await mc(e,m);let y=xa(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,u)});let l=f=>{let u;try{u=Cd.parse(f)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let h=e.manager.get(u.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${u.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Cd.parse(f);return d(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=Gh.parse(f);return d(u.sessionId,"hydra-acp/prompt/cancel"),dn(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Cd.parse(f);return d(u.sessionId,"hydra-acp/session/force_cancel"),dn(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=Xh.parse(f);return d(u.sessionId,"hydra-acp/prompt/update"),dn(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=Zh.parse(f);d(u.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(u.sessionId);if(!p)throw se(j.SessionNotFound,"not attached to session");return dn(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/resume",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let S=await e.manager.loadFromDisk(h);if(!S)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await mc(e,S)}bc(c,m,m.sessionId);let y=xa(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=gc(m),b=yc(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:wc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await mc(e,k)}bc(c,m,m.sessionId);let y=xa(a,m,c),{entries:w}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of w){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let b=gc(m),S=yc(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:wc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&d(u,"session/set_model");let p=yA(f,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),se(p.code,p.message);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:h}=p,m=await p.session.forwardRequest("session/set_model",{...f,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw se(j.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw se(j.InvalidParams,"session/set_mode requires string modeId");let h=dn(e.manager,u.sessionId),m=await h.forwardRequest("session/set_mode",f);return h.applyModeChange(u.modeId),m}),a.onRequest("session/set_config_option",async f=>{let u=f,p=w=>se(j.InvalidParams,w),h=u?.sessionId;if(typeof h=="string"&&d(h,"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 m=dn(e.manager,u.sessionId),y=m.buildConfigOptions().find(w=>w.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(w=>w.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!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),m.applyModelChange(u.value);break}case"mode":{u.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),m.applyModeChange(u.value);break}case"agent":{u.value!==m.agentId&&await m.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=u.startsWith("session/"),m=u.startsWith("hydra-acp/");if(!h&&!m||f===null||typeof f!="object"||p.has(u))throw se(j.MethodNotFound,`Method not found: ${u}`);let y=f.sessionId;if(typeof y!="string")throw se(j.MethodNotFound,`Method not found: ${u}`);return d(y,u),dn(e.manager,y).forwardRequest(u,f)})})}async function mA(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw se(j.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw se(j.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,f=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:f!==void 0?"terminal":"agent"))==="terminal"){let p=(S,k)=>{if(!Array.isArray(S))throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let A of S)if(typeof A!="string")throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(f?.args!==void 0){let S=typeof f.command=="string"?f.command:void 0;m=S!==void 0&&ey.isAbsolute(S)?S:h.command,y=p(f.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(w[S]=k);Object.assign(w,h.env);let b=Zg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw rr(p,a)}}async function gA(t,e){let s=(t??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function Gg(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(Rd,n).catch(()=>{})}}function gc(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 yc(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 yA(t,e){if(!t||typeof t!="object")return{kind:"error",code:j.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:j.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:j.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:j.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Vi(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(c=>c.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:j.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 wA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(j.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw se(j.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw se(j.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return dn(n.manager,r).addTransformer(i),{ok:!0}}async function bA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/set requires string reason");return dn(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function vA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string reason");return dn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function SA(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,forkSynthesisState:t.forkSynthesisState,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{[Ft]:xd(e,n)}}function wc(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(),...n.resurrected===!0?{resurrected:!0}:{}};return na(e.agentMeta,xd(s,r))}function kA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:be},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:na(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function IA(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 ny(t,e){if(!e.transformers)return;let n=e.transformers.interestedIn("lifecycle:session.starting");for(let s of n)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:t}).catch(()=>{})}function xa(t,e,n,s,r){return{clientId:r??`cli_${df(8)}`,connection:t,clientInfo:s}}function bc(t,e,n){let s=t.attached.get(n);s&&(e.detach(s.clientId),t.attached.delete(n))}var vc=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 xA}from"crypto";import{McpServer as AA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as CA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Lt}from"zod";function*cf(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function cn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var sy="Bearer ";function fo(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(sy))return;let n=e.slice(sy.length).trim();return n.length>0?n:void 0}function RA(t){let e=new AA({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:Lt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return cn(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:Lt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return cn(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:Lt.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:Lt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Lt.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 cn(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:Lt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Lt.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();return cn({outcome:r,writeCursor:i.writeCursor,closed:i.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:Lt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Lt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Lt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Lt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Lt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Lt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Lt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Lt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Lt.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);return cn(r)}),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 cn(n)}),e}var TA=1e4;function ry(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=RA(a),l=new CA({sessionIdGenerator:()=>xA()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=fo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),TA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let f=await s(c,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)})}_d();import{randomUUID as EA}from"crypto";import{McpServer as PA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as MA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as dr}from"zod";function _A(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function $A(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function FA(t){let e=new PA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:dr.string().min(1).describe("Case-insensitive substring to search for."),limit:dr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:dr.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:f}of cf(o)){if(f==="tool_call"&&!r)continue;let u=Qi([l]),p=u.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=_A(f),m=$A(u,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return cn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:dr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:dr.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return cn({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),f=Qi(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:dr.string().optional(),file_path:dr.string().optional(),limit:dr.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of cf(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let w=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,b=l.get(w);b||(b={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(w,b),d.push(w)),typeof y.name=="string"&&y.name.length>0?b.toolName=y.name:(b.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(b.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[k,A]of Object.entries(S))b.rawInput[k]=A;if(Array.isArray(y.locations))for(let k of y.locations){let A=k?.path;typeof A=="string"&&A.length>0&&!b.locations.includes(A)&&b.locations.push(A)}typeof y.status=="string"&&(b.status=y.status),h.recordedAt!==void 0&&b.timestamp===void 0&&(b.timestamp=String(h.recordedAt))}let f=[];for(let p of d){let h=l.get(p);if(n!==void 0&&h.toolName.toLowerCase()!==n.toLowerCase())continue;if(a){let y=s.toLowerCase(),w=["file_path","filePath","path"],b=!1;for(let S of w){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let S of h.locations)if(S.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),f.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),f.length>=r)break}let u=f.length>=r;return cn({calls:f,truncated:u})}),e}var OA=1e4;function iy(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=FA(a),l=new MA({sessionIdGenerator:()=>EA()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=fo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),OA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var Sc=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 qA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as WA}from"crypto";import{Server as LA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as BA,ListToolsRequestSchema as NA}from"@modelcontextprotocol/sdk/types.js";function oy(t,e,n,s){let r=typeof n=="function"?async()=>n():async()=>n,i=new LA({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(NA,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(BA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,f=HA(l,c.sendNotification);try{let u=await r(),p=await UA(e.connection,t,d,a.params.arguments??{},u);return jA(p,d)}catch(u){return lf(u instanceof Error?u.message:String(u))}finally{f()}}),i}var DA=15e3;function HA(t,e,n=DA){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function UA(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function jA(t,e){if(t===null||typeof t!="object")return lf(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:lf(`extension ${e} omitted content array`)}function lf(t){return{content:[{type:"text",text:t}],isError:!0}}var zA=1e4;function ay(t,e,n){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let f of s.values()){let u=f.get(l);u!==void 0&&(f.delete(l),r(u))}}async function o(l,f){for(let[u,p]of s){if(e.lookup(u)?.session?.sessionId!==l)continue;let m=p.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}n.onChange(l=>{i(l)});async function a(l,f){let u=s.get(l);u===void 0&&(u=new Map,s.set(l,u),e.addDisposer(l,async()=>{let k=s.get(l);if(k!==void 0){s.delete(l);for(let A of k.values())await r(A)}}));let p=u.get(f);if(p!==void 0)return p.transport;let h=n.lookup(f);if(h===void 0)return;let b=oy(f,h,async()=>{let k=e.lookup(l);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let A,E=new Promise(B=>{A=setTimeout(()=>B(void 0),zA)}),P=await Promise.race([k.sessionReady.catch(()=>{}),E]);if(A!==void 0&&clearTimeout(A),P===void 0)throw new Error("session not ready");return P.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async k=>{let A=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:k});if(!A||typeof A!="object")return;let E=A.tools;if(!Array.isArray(E))return;let P=[];for(let B of E){if(!B||typeof B!="object")continue;let _=B;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let D={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(D.outputSchema=_.outputSchema),P.push(D)}return P}}),S=new qA({sessionIdGenerator:()=>WA()});return await b.connect(S),u.set(f,{server:b,transport:S}),S}async function c(l,f){let u=fo(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 h=l.params.name,m=await a(u,h);if(m===void 0){f.code(404).send({error:`unknown mcp server: ${h}`});return}f.hijack(),await m.handleRequest(l.raw,f.raw,l.body)}let d={config:{skipAuth:!0}};return t.post("/mcp/:name",d,async(l,f)=>{await c(l,f)}),t.get("/mcp/:name",d,async(l,f)=>{await c(l,f)}),t.delete("/mcp/:name",d,async(l,f)=>{await c(l,f)}),{notifyToolListChanged:o}}async function py(t,e){XA(t);let n=t.daemon.tls?await is.readFile(tt(t.daemon.tls.key)):void 0,s=t.daemon.tls?await is.readFile(tt(t.daemon.tls.cert)):void 0;await is.mkdir(O.home(),{recursive:!0});let{stream:r,fileStream:i}=await QA(t.daemon.logLevel),o=KA({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(JA,{options:{handleProtocols:Ih}}),nu(G=>{o.log.info(G)}),iu(G=>{o.log.info(G)});let a=await ec.load(),c=new ic,d=new rc,l=new sc([new tc(e),new nc(a),d]),f=mg({validator:l});o.addHook("onRequest",async(G,xe)=>{G.routeOptions.config?.skipAuth||G.url==="/acp"||G.url?.startsWith("/acp?")||await f(G,xe)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Sd(t,{onFetched:()=>{og(h,b)}});Qu(G=>o.log.info(G));let m={info:G=>o.log.info(G),warn:G=>o.log.warn(G)},y=G=>nr.spawn({...G,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Rh(t.compressToolContent);let w=new Xd,b=new Wd(h,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:t.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:t.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:t.npmRegistry,extensionCommands:w,defaultCwd:t.defaultCwd}),S=new Qd(Vp(t),void 0,{tokenRegistry:d}),k=new Gd(Qp(t),void 0,{tokenRegistry:d});Dg(o,be,ir(t));let A=new vc,E=new Sc,P,B=()=>{if(P!==void 0)return P;let G=o.server.address();return P=`http://127.0.0.1:${G&&typeof G=="object"?G.port:t.daemon.port}`,P};Bg(o,b,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:E,mcpTokenRegistry:A,getDaemonOrigin:B}),Ng(o,h,b,{npmRegistry:t.npmRegistry}),Hg(o,S),Ug(o,k),jg(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),Qg(o,{store:a,rateLimiter:c}),ry(o,A),iy(o,A);let _=ay(o,A,E);ty(o,{validator:l,manager:b,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(G,xe)=>S.reportVersion(G,xe),onTransformerVersion:(G,xe)=>k.reportVersion(G,xe),transformers:k,extensionCommands:w,mcpTokenRegistry:A,extensionMcp:E,extensionMcpControls:_,getDaemonOrigin:B,registry:h});let D=!!t.daemon.tls;await o.listen({host:D?"127.0.0.1":t.daemon.host,port:D?0:t.daemon.port});let N=o.server.address(),L=N&&typeof N=="object"?N.port:t.daemon.port,K,X=t.daemon.host,Z=L;if(D&&n&&s){K=GA({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let G=K.address();G&&typeof G=="object"&&(Z=G.port)}await is.mkdir(O.home(),{recursive:!0}),await rh({pid:process.pid,host:X,port:Z,loopbackPort:L,startedAt:new Date().toISOString()});let Q={daemonUrl:`http://127.0.0.1:${L}`,daemonHost:"127.0.0.1",daemonPort:L,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${L}/acp`,hydraHome:O.home()};S.setContext(Q),k.setContext(Q),await S.start(),await k.start();try{await b.reconcilePermissionFlags()}catch(G){o.log.warn(`permission flag reconcile failed: ${G.message}`)}b.resurrectPendingQueues().catch(G=>{o.log.warn(`queue replay scan failed: ${G.message}`)}),b.resumePendingCompactions().catch(G=>{o.log.warn(`compaction resume scan failed: ${G.message}`)}),b.resumePendingAgentSwaps().catch(G=>{o.log.warn(`agent-swap resume scan failed: ${G.message}`)});let fe=t.daemon.agentSyncIntervalMinutes*60*1e3,Me=fe>0?ag({registry:h,manager:b,intervalMs:fe,logger:m}):void 0,In=t.daemon.sessionGcIntervalMinutes*60*1e3,De=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,us=In>0?dg({manager:b,intervalMs:In,maxAgeMs:De,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:d,shutdown:async()=>{us&&us(),Me&&Me(),clearInterval(u),clearInterval(p);let G=async(xe,je)=>{try{await je()}catch(Yt){o.log.warn(`shutdown step ${xe} failed: ${Yt instanceof Error?Yt.message:String(Yt)}`)}};await G("sessionTokenStore.flush",()=>a.flush()),await G("extensions.stop",()=>S.stop()),await G("transformers.stop",()=>k.stop()),await G("manager.closeAll",()=>b.closeAll()),await G("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await G("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await G("manager.flushMetaWrites",()=>b.flushMetaWrites()),await G("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),nu(null),iu(null),Qu(null),K&&await G("tlsTerminator.close",()=>new Promise(xe=>K.close(()=>xe()))),await G("app.close",()=>o.close());try{ly.unlinkSync(O.pidFile())}catch{}await G("fileStream.flushSync",()=>i.flushSync())}}}var cy=20;async function VA(t,e){let n=po.dirname(t),s=po.basename(t,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await is.readdir(n)}catch{return}let o=[];for(let c of i){let d=c.match(r);d&&o.push({name:c,n:Number(d[1])})}if(o.length<=e)return;o.sort((c,d)=>c.n-d.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(c=>is.unlink(po.join(n,c.name))))}async function QA(t){await VA(O.logFile(),cy);let e=await YA({file:O.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:cy,removeOtherLogFiles:!0}}),n=dy.destination(2);return{stream:dy.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function GA(t){let e=fy.createServer(t.tlsOptions,n=>{let s=uy.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function XA(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.`)}Vr();an();ba();Aa();async function yy(t={}){let e=await Ae(),n=await Vo();if(await kc(e)){let r=await go();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
329
- `);return}if(Mi(t,"foreground")){process.title="hydra-daemon";let r=await py(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
325
+ `)}}return b=!0,w||l.raw.end(),l});function r(d,l,f){let u=typeof d=="string"?d.trim():"";if(u.length===0)return null;let p;try{p=JSON.parse(u)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||f!==void 0&&h.recordedAt<f||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!l.has(w)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,f){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:f,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,f,u){for await(let p of l){let h=r(p,f,u);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,f,u){let p=af.createInterface({input:of.createReadStream(l),crlfDelay:1/0}),h=o(d,p,f,u),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}t.get("/v1/sessions/events",async(d,l)=>{let f=d.query,u=f.kinds;if(!u||u.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=u.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!uc.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...uc].join(", ")}`}),l;let h=new Set(p),m;if(f.since!==void 0&&f.since.trim().length>0){let S=new Date(f.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),w=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let b=[];for(let S of w)try{let k=O.historyFile(S.sessionId),A=await a(S.sessionId,k,h,m);A.exhausted||b.push(A)}catch(k){if(k.code==="ENOENT")continue;throw k}d.raw.on("close",()=>{for(let S of b)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;b.length>0;){let S=-1,k=1/0;for(let E=0;E<b.length;E++){let P=b[E];P.current!==null&&P.current.ts<k&&(k=P.current.ts,S=E)}if(S===-1)break;let A=b[S];if(l.raw.write(JSON.stringify(A.current.row)+`
326
+ `),await c(A),A.exhausted){try{A.rl.close()}catch{}b.splice(S,1)}}}catch(S){for(let k of b)try{k.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let f=d.params.id,u=d.query,p=await e.resolveCanonicalId(f)??f;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=u.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(E=>E.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let E of y)if(!uc.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...uc].join(", ")}`}),l;let w=new Set(y),b;if(u.since!==void 0&&u.since.trim().length>0){let E=new Date(u.since);if(isNaN(E.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;b=E.getTime()}let S=O.historyFile(p),k=of.createReadStream(S),A=af.createInterface({input:k,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let E of A){let P=typeof E=="string"?E.trim():"";if(P.length===0)continue;let B;try{B=JSON.parse(P)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!B||typeof B!="object"||Array.isArray(B)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let _=B;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let D=_.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let N=D.update,L=N.sessionUpdate;if(typeof L!="string"||!w.has(L)||b!==void 0&&_.recordedAt<b)continue;let K={ts:new Date(_.recordedAt).toISOString(),kind:L,update:N};N.messageId!==void 0&&N.messageId!==null&&(K.messageId=N.messageId),l.raw.write(JSON.stringify(K)+`
327
+ `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);return!p&&!await e.hasRecord(u)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(u))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let f=d.query;if(!f.source||f.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let u=await e.list({includeNonInteractive:!0}),p=[];for(let h of u){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let w of y)w.source===f.source&&p.push({...w,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let f=d.params.id,u=await e.resolveCanonicalId(f)??f,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let w=e.get(u);if(w){if(m.length>0&&y.length>0)w.clearAttentionFlag(m,y);else{let E=Array.from(w.listAttentionFlags()).map(P=>`${P.source}::${P.reason}`);for(let P of E)w.clearAttentionFlag(P.split("::")[0],P.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}let b=e.store,S=await b.read(u);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],A;if(m.length>0&&y.length>0){let E=`${m}::${y}`;A=k.filter(P=>`${P.source}::${P.reason}`!==E)}else A=[];if(A.length===k.length&&A.every((E,P)=>E.source===k[P].source&&E.reason===k[P].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:A}),l.code(204).send()})}Ot();function Dg(t,e,n,s={}){t.get("/v1/agents",async()=>qi(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 c=await bn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===j.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function Hg(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var rA=/^[A-Za-z0-9._-]+$/;function fc(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=iA(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){Ia(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){Ia(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){Ia(o,c)}})}function Ia(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 iA(t){let e=t.name;if(typeof e!="string"||!rA.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 Ug(t,e){fc(t,"extension",e)}function jg(t,e){fc(t,"transformer",e)}function qg(t,e){t.get("/v1/config",async()=>e)}import{z as lo}from"zod";we();import*as dr from"fs/promises";import*as Jg from"path";import{randomBytes as oA,scrypt as aA,timingSafeEqual as dA}from"crypto";import{promisify as cA}from"util";var Yg=cA(aA);function df(){return Jg.join(O.home(),"password-hash")}var Wg=32768,zg=8,Kg=1,lA=64,uA=16,Vg=128*1024*1024;async function Qg(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=oA(uA),n=await Yg(t,e,lA,{N:Wg,r:zg,p:Kg,maxmem:Vg}),s=`scrypt$${Wg}$${zg}$${Kg}$${e.toString("hex")}$${n.toString("hex")}
328
+ `;await dr.mkdir(O.home(),{recursive:!0}),await dr.writeFile(df(),s,{encoding:"utf8",mode:384})}async function pc(){try{return(await dr.readFile(df(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hc(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await dr.readFile(df(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}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 c=await Yg(t,o,a.length,{N:s,r,p:i,maxmem:Vg});return c.length!==a.length?!1:dA(c,a)}var fA=lo.object({password:lo.string().min(1),label:lo.string().min(1).max(256).optional(),ttlSec:lo.number().int().positive().optional()}),pA=lo.object({id:lo.string().optional()}).optional();function Gg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=hA(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=fA.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await pc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await hc(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=pA.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 hA(t){return t.ip||"unknown"}jr();uo();import{nanoid as cf}from"nanoid";Md();Ot();an();import{randomBytes as Zg}from"crypto";import*as ey from"os";import*as ty from"path";function se(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function bA(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function dn(t,e,n){let s=t.get(e);if(!s)throw se(j.SessionNotFound,n??`session ${e} not found`);return s}async function mc(t,e){let n=co(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Zg(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=rf({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,f=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{f.unbind(l)})}return TA(d,t),sy(d.sessionId,t),d}function ny(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=yg({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=rs(n),a=new Kt(o),c={clientId:`hydra_client_${cf(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let d=(f,u)=>{if(c.attached.get(f)?.readonly)throw se(j.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=jh.parse(f??{});u.clientInfo?.name&&(c.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)),RA()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return f.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let S={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(S.outputSchema=b.outputSchema),S}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,y),{ok:!0,registered:y.length}});let u=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw se(j.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=u(p);if(!e.manager)throw se(j.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(m.value===void 0)throw se(j.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(j.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(j.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(j.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{f.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async u=>{let p=u??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw se(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw se(-32602,"emit_message requires method");let b=dn(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return b.dischargeClaim(S,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return dn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async u=>IA(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let p=u??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,S=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let P=e.manager.get(y);P&&(m=P.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:S,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,b=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let f=async(u,p)=>{let h=u??{};if(typeof h.sessionId!="string")throw se(j.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async u=>(await f(u,"session/delete"),{})),a.onRequest("session/close",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(j.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async u=>{let{id:p,existed:h}=await f(u,"hydra-acp/session/delete");if(!h)throw se(j.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw se(-32602,"await_child requires childSessionId");let w=dn(e.manager,h,`child session ${h} not found`);return new Promise(b=>{let A=[],E=[],P=0,B=!1,_,D,N=!1,L=()=>{N||(N=!0,clearTimeout(K),_?.(),D?.(),b(B?{entries:A,truncated:!0}:{entries:A}))};_=w.onBroadcast(X=>{let Z=bA(X);for(A.push(X),E.push(Z),P+=Z;A.length>0&&(A.length>1e3||P>1048576);)A.shift(),P-=E.shift()??0,B=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&L()});let K=setTimeout(L,y);typeof K.unref=="function"&&K.unref(),D=w.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>xA(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>AA(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let p=u??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw se(j.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,h=await e.manager.loadToolBlob(p,u.hash);if(h===null)throw se(j.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async f=>vA(f,e)),a.onRequest("logout",async f=>SA(f,e)),a.onRequest("session/new",async f=>{let u=qh.parse(f),p=rn(f?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(L=>typeof L=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,w,b=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Zg(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let K={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...u.mcpServers??[],K]}let S,k,A=co(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=rf({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Xg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(L){throw w!==void 0&&w.abandon(L instanceof Error?L:void 0),k!==void 0&&k.abandon(L instanceof Error?L:void 0),A!==void 0&&A.abandon(L instanceof Error?L:void 0),L}if(y!==void 0&&w!==void 0&&e.mcpTokenRegistry!==void 0){let L=y,K=e.mcpTokenRegistry;w.complete(P),P.onClose(()=>{K.unbind(L)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let L=S,K=e.mcpTokenRegistry;k.complete(P),P.onClose(()=>{K.unbind(L)})}A!==void 0&&A.bindToSession(P),sy(P.sessionId,e);let B,_;try{bc(c,P,P.sessionId),B=xa(a,P,c),{entries:_}=await P.attach(B,"full")}catch(L){throw await P.close({deleteRecord:!1}).catch(()=>{}),L}c.attached.set(P.sessionId,{sessionId:P.sessionId,clientId:B.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let L of _){if(a.isClosed())break;await a.notify(L.method,L.params).catch(()=>{})}})()});let D=gc(P),N=yc(P);return{sessionId:P.sessionId,...D?{modes:D}:{},...N?{models:N}:{},configOptions:P.buildConfigOptions(),_meta:wc(e.manager,P,{clientId:B.clientId})}}),a.onRequest("session/attach",async f=>{let u=zh.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=rn(u._meta),m=h.resume,y=h.readonly===!0,w=h.env;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,S=e.manager.get(b);if(!S&&y){let N=await e.manager.loadFromDisk(b);if(!N)throw se(j.SessionNotFound,`session ${u.sessionId} not found`);let L=await e.manager.loadHistory(b),K=u.clientId??`cli_${cf(8)}`;c.attached.set(N.hydraSessionId,{sessionId:N.hydraSessionId,clientId:K,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${N.hydraSessionId} clientId=${K} attachedCount=${c.attached.size} replayed=${L.length}`);for(let X of L)await a.notify(X.method,X.params).catch(()=>{});return{sessionId:N.hydraSessionId,clientId:K,connectedClients:[K],historyPolicy:"full",replayed:L.length,_meta:CA(N)}}let k=!S;if(!S){let N=await e.manager.loadFromDisk(b),L=N;if(m&&(L={...N,hydraSessionId:u.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!L)throw se(j.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(L.agentId,L.upstreamSessionId))throw se(j.SessionNotFound,`session ${u.sessionId} was deleted`);let K=L.originatingClient?L:{...L,originatingClient:c.clientInfo},X=w!==void 0?{...K,forwardedEnv:w}:K;S=await mc(e,{...X,onInstallProgress:Xg(a)})}bc(c,S,S.sessionId);let A=xa(a,S,c,u.clientInfo,u.clientId),E=h.replayMode==="drip",{entries:P,appliedPolicy:B}=await S.attach(A,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(S.sessionId,w).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${B} replayed=${P.length} readonly=${y}${E?" replayMode=drip":""}`),E){let N=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,L=750;(async()=>{let K=null;for(let X of P){let Z=typeof X.recordedAt=="number"?X.recordedAt:null;if(K!==null&&Z!==null){let Q=Math.min(L,Math.max(0,(Z-K)/N));Q>0&&await new Promise(fe=>setTimeout(fe,Q))}Z!==null&&(K=Z);try{await a.notify(X.method,X.params)}catch{return}}})()}else for(let N=0;N<P.length&&!a.isClosed();N++){let L=P[N],K=a.notify(L.method,L.params).catch(()=>{});(N+1)%200===0&&await K}S.replayPendingPermissions(A);let _=gc(S),D=yc(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:B,replayed:P.length,..._?{modes:_}:{},...D?{models:D}:{},configOptions:S.buildConfigOptions(),_meta:wc(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async f=>{let u=Kh.parse(f),p=c.attached.get(u.sessionId);if(!p)throw se(j.SessionNotFound,"client not attached to that session");let h=e.manager.get(u.sessionId);return h?.detach(p.clientId),c.attached.delete(u.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[Ft]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=Jh.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==qr).map(Yh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(j.InternalError,"agent registry unavailable");return qi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let u=f??{};if(typeof u.agentId!="string"||u.agentId.length===0)throw se(j.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(u.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let u=Vh.parse(f);d(u.sessionId,"session/prompt");let p=c.attached.get(u.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),se(j.SessionNotFound,"not attached to session");let h=e.manager.get(u.sessionId);if(!h){let m=await e.manager.loadFromDisk(u.sessionId);if(!m)throw se(j.SessionNotFound,`session ${u.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),h=await mc(e,m);let y=xa(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,u)});let l=f=>{let u;try{u=Cd.parse(f)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let h=e.manager.get(u.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${u.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Cd.parse(f);return d(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=Gh.parse(f);return d(u.sessionId,"hydra-acp/prompt/cancel"),dn(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Cd.parse(f);return d(u.sessionId,"hydra-acp/session/force_cancel"),dn(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=Xh.parse(f);return d(u.sessionId,"hydra-acp/prompt/update"),dn(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=Zh.parse(f);d(u.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(u.sessionId);if(!p)throw se(j.SessionNotFound,"not attached to session");return dn(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/resume",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let S=await e.manager.loadFromDisk(h);if(!S)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await mc(e,S)}bc(c,m,m.sessionId);let y=xa(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=gc(m),b=yc(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:wc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await mc(e,k)}bc(c,m,m.sessionId);let y=xa(a,m,c),{entries:w}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of w){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let b=gc(m),S=yc(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:wc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&d(u,"session/set_model");let p=kA(f,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),se(p.code,p.message);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:h}=p,m=await p.session.forwardRequest("session/set_model",{...f,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw se(j.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw se(j.InvalidParams,"session/set_mode requires string modeId");let h=dn(e.manager,u.sessionId),m=await h.forwardRequest("session/set_mode",f);return h.applyModeChange(u.modeId),m}),a.onRequest("session/set_config_option",async f=>{let u=f,p=w=>se(j.InvalidParams,w),h=u?.sessionId;if(typeof h=="string"&&d(h,"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 m=dn(e.manager,u.sessionId),y=m.buildConfigOptions().find(w=>w.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(w=>w.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!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),m.applyModelChange(u.value);break}case"mode":{u.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),m.applyModeChange(u.value);break}case"agent":{u.value!==m.agentId&&await m.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=u.startsWith("session/"),m=u.startsWith("hydra-acp/");if(!h&&!m||f===null||typeof f!="object"||p.has(u))throw se(j.MethodNotFound,`Method not found: ${u}`);let y=f.sessionId;if(typeof y!="string")throw se(j.MethodNotFound,`Method not found: ${u}`);return d(y,u),dn(e.manager,y).forwardRequest(u,f)})})}async function vA(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw se(j.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw se(j.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,f=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:f!==void 0?"terminal":"agent"))==="terminal"){let p=(S,k)=>{if(!Array.isArray(S))throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let A of S)if(typeof A!="string")throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(f?.args!==void 0){let S=typeof f.command=="string"?f.command:void 0;m=S!==void 0&&ty.isAbsolute(S)?S:h.command,y=p(f.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(w[S]=k);Object.assign(w,h.env);let b=ey.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw ir(p,a)}}async function SA(t,e){let s=(t??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function Xg(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(Rd,n).catch(()=>{})}}function gc(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 yc(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 kA(t,e){if(!t||typeof t!="object")return{kind:"error",code:j.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:j.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:j.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:j.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Vi(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(c=>c.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:j.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 IA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(j.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw se(j.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw se(j.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return dn(n.manager,r).addTransformer(i),{ok:!0}}async function xA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/set requires string reason");return dn(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function AA(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string reason");return dn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function CA(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,forkSynthesisState:t.forkSynthesisState,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{[Ft]:xd(e,n)}}function wc(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(),...n.resurrected===!0?{resurrected:!0}:{}};return na(e.agentMeta,xd(s,r))}function RA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:be},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:na(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function TA(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 sy(t,e){if(!e.transformers)return;let n=e.transformers.interestedIn("lifecycle:session.starting");for(let s of n)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:t}).catch(()=>{})}function xa(t,e,n,s,r){return{clientId:r??`cli_${cf(8)}`,connection:t,clientInfo:s}}function bc(t,e,n){let s=t.attached.get(n);s&&(e.detach(s.clientId),t.attached.delete(n))}var vc=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 EA}from"crypto";import{McpServer as PA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as MA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Lt}from"zod";function*lf(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function cn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var ry="Bearer ";function fo(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(ry))return;let n=e.slice(ry.length).trim();return n.length>0?n:void 0}function _A(t){let e=new PA({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:Lt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return cn(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:Lt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return cn(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:Lt.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:Lt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Lt.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 cn(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:Lt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Lt.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();return cn({outcome:r,writeCursor:i.writeCursor,closed:i.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:Lt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Lt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Lt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Lt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Lt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Lt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Lt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Lt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Lt.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);return cn(r)}),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 cn(n)}),e}var $A=1e4;function iy(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=_A(a),l=new MA({sessionIdGenerator:()=>EA()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=fo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),$A)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let f=await s(c,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)})}_d();import{randomUUID as FA}from"crypto";import{McpServer as OA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as LA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as cr}from"zod";function BA(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function NA(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function DA(t){let e=new OA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:cr.string().min(1).describe("Case-insensitive substring to search for."),limit:cr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:cr.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:f}of lf(o)){if(f==="tool_call"&&!r)continue;let u=Qi([l]),p=u.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=BA(f),m=NA(u,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return cn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:cr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:cr.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return cn({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),f=Qi(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:cr.string().optional(),file_path:cr.string().optional(),limit:cr.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of lf(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let w=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,b=l.get(w);b||(b={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(w,b),d.push(w)),typeof y.name=="string"&&y.name.length>0?b.toolName=y.name:(b.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(b.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[k,A]of Object.entries(S))b.rawInput[k]=A;if(Array.isArray(y.locations))for(let k of y.locations){let A=k?.path;typeof A=="string"&&A.length>0&&!b.locations.includes(A)&&b.locations.push(A)}typeof y.status=="string"&&(b.status=y.status),h.recordedAt!==void 0&&b.timestamp===void 0&&(b.timestamp=String(h.recordedAt))}let f=[];for(let p of d){let h=l.get(p);if(n!==void 0&&h.toolName.toLowerCase()!==n.toLowerCase())continue;if(a){let y=s.toLowerCase(),w=["file_path","filePath","path"],b=!1;for(let S of w){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let S of h.locations)if(S.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),f.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),f.length>=r)break}let u=f.length>=r;return cn({calls:f,truncated:u})}),e}var HA=1e4;function oy(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=DA(a),l=new LA({sessionIdGenerator:()=>FA()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=fo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),HA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var Sc=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 YA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as VA}from"crypto";import{Server as UA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as jA,ListToolsRequestSchema as qA}from"@modelcontextprotocol/sdk/types.js";function ay(t,e,n,s){let r=typeof n=="function"?async()=>n():async()=>n,i=new UA({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(qA,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(jA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,f=zA(l,c.sendNotification);try{let u=await r(),p=await KA(e.connection,t,d,a.params.arguments??{},u);return JA(p,d)}catch(u){return uf(u instanceof Error?u.message:String(u))}finally{f()}}),i}var WA=15e3;function zA(t,e,n=WA){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function KA(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function JA(t,e){if(t===null||typeof t!="object")return uf(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:uf(`extension ${e} omitted content array`)}function uf(t){return{content:[{type:"text",text:t}],isError:!0}}var QA=1e4;function dy(t,e,n){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let f of s.values()){let u=f.get(l);u!==void 0&&(f.delete(l),r(u))}}async function o(l,f){for(let[u,p]of s){if(e.lookup(u)?.session?.sessionId!==l)continue;let m=p.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}n.onChange(l=>{i(l)});async function a(l,f){let u=s.get(l);u===void 0&&(u=new Map,s.set(l,u),e.addDisposer(l,async()=>{let k=s.get(l);if(k!==void 0){s.delete(l);for(let A of k.values())await r(A)}}));let p=u.get(f);if(p!==void 0)return p.transport;let h=n.lookup(f);if(h===void 0)return;let b=ay(f,h,async()=>{let k=e.lookup(l);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let A,E=new Promise(B=>{A=setTimeout(()=>B(void 0),QA)}),P=await Promise.race([k.sessionReady.catch(()=>{}),E]);if(A!==void 0&&clearTimeout(A),P===void 0)throw new Error("session not ready");return P.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async k=>{let A=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:k});if(!A||typeof A!="object")return;let E=A.tools;if(!Array.isArray(E))return;let P=[];for(let B of E){if(!B||typeof B!="object")continue;let _=B;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let D={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(D.outputSchema=_.outputSchema),P.push(D)}return P}}),S=new YA({sessionIdGenerator:()=>VA()});return await b.connect(S),u.set(f,{server:b,transport:S}),S}async function c(l,f){let u=fo(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 h=l.params.name,m=await a(u,h);if(m===void 0){f.code(404).send({error:`unknown mcp server: ${h}`});return}f.hijack(),await m.handleRequest(l.raw,f.raw,l.body)}let d={config:{skipAuth:!0}};return t.post("/mcp/:name",d,async(l,f)=>{await c(l,f)}),t.get("/mcp/:name",d,async(l,f)=>{await c(l,f)}),t.delete("/mcp/:name",d,async(l,f)=>{await c(l,f)}),{notifyToolListChanged:o}}async function hy(t,e){sC(t);let n=t.daemon.tls?await is.readFile(tt(t.daemon.tls.key)):void 0,s=t.daemon.tls?await is.readFile(tt(t.daemon.tls.cert)):void 0;await is.mkdir(O.home(),{recursive:!0});let{stream:r,fileStream:i}=await tC(t.daemon.logLevel),o=GA({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(XA,{options:{handleProtocols:Ih}}),su(G=>{o.log.info(G)}),ou(G=>{o.log.info(G)});let a=await ec.load(),c=new ic,d=new rc,l=new sc([new tc(e),new nc(a),d]),f=gg({validator:l});o.addHook("onRequest",async(G,xe)=>{G.routeOptions.config?.skipAuth||G.url==="/acp"||G.url?.startsWith("/acp?")||await f(G,xe)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Sd(t,{onFetched:()=>{ag(h,b)}});Gu(G=>o.log.info(G));let m={info:G=>o.log.info(G),warn:G=>o.log.warn(G)},y=G=>sr.spawn({...G,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Rh(t.compressToolContent);let w=new Xd,b=new Wd(h,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:t.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:t.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:t.npmRegistry,extensionCommands:w,defaultCwd:t.defaultCwd}),S=new Qd(Vp(t),void 0,{tokenRegistry:d}),k=new Gd(Qp(t),void 0,{tokenRegistry:d});Hg(o,be,or(t));let A=new vc,E=new Sc,P,B=()=>{if(P!==void 0)return P;let G=o.server.address();return P=`http://127.0.0.1:${G&&typeof G=="object"?G.port:t.daemon.port}`,P};Ng(o,b,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:E,mcpTokenRegistry:A,getDaemonOrigin:B}),Dg(o,h,b,{npmRegistry:t.npmRegistry}),Ug(o,S),jg(o,k),qg(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),Gg(o,{store:a,rateLimiter:c}),iy(o,A),oy(o,A);let _=dy(o,A,E);ny(o,{validator:l,manager:b,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(G,xe)=>S.reportVersion(G,xe),onTransformerVersion:(G,xe)=>k.reportVersion(G,xe),transformers:k,extensionCommands:w,mcpTokenRegistry:A,extensionMcp:E,extensionMcpControls:_,getDaemonOrigin:B,registry:h});let D=!!t.daemon.tls;await o.listen({host:D?"127.0.0.1":t.daemon.host,port:D?0:t.daemon.port});let N=o.server.address(),L=N&&typeof N=="object"?N.port:t.daemon.port,K,X=t.daemon.host,Z=L;if(D&&n&&s){K=nC({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let G=K.address();G&&typeof G=="object"&&(Z=G.port)}await is.mkdir(O.home(),{recursive:!0}),await rh({pid:process.pid,host:X,port:Z,loopbackPort:L,startedAt:new Date().toISOString()});let Q={daemonUrl:`http://127.0.0.1:${L}`,daemonHost:"127.0.0.1",daemonPort:L,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${L}/acp`,hydraHome:O.home()};S.setContext(Q),k.setContext(Q),await S.start(),await k.start();try{await b.reconcilePermissionFlags()}catch(G){o.log.warn(`permission flag reconcile failed: ${G.message}`)}b.resurrectPendingQueues().catch(G=>{o.log.warn(`queue replay scan failed: ${G.message}`)}),b.resumePendingCompactions().catch(G=>{o.log.warn(`compaction resume scan failed: ${G.message}`)}),b.resumePendingAgentSwaps().catch(G=>{o.log.warn(`agent-swap resume scan failed: ${G.message}`)});let fe=t.daemon.agentSyncIntervalMinutes*60*1e3,Me=fe>0?dg({registry:h,manager:b,intervalMs:fe,logger:m}):void 0,In=t.daemon.sessionGcIntervalMinutes*60*1e3,He=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,us=In>0?cg({manager:b,intervalMs:In,maxAgeMs:He,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:d,shutdown:async()=>{us&&us(),Me&&Me(),clearInterval(u),clearInterval(p);let G=async(xe,qe)=>{try{await qe()}catch(Yt){o.log.warn(`shutdown step ${xe} failed: ${Yt instanceof Error?Yt.message:String(Yt)}`)}};await G("sessionTokenStore.flush",()=>a.flush()),await G("extensions.stop",()=>S.stop()),await G("transformers.stop",()=>k.stop()),await G("manager.closeAll",()=>b.closeAll()),await G("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await G("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await G("manager.flushMetaWrites",()=>b.flushMetaWrites()),await G("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),su(null),ou(null),Gu(null),K&&await G("tlsTerminator.close",()=>new Promise(xe=>K.close(()=>xe()))),await G("app.close",()=>o.close());try{uy.unlinkSync(O.pidFile())}catch{}await G("fileStream.flushSync",()=>i.flushSync())}}}var ly=20;async function eC(t,e){let n=po.dirname(t),s=po.basename(t,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await is.readdir(n)}catch{return}let o=[];for(let c of i){let d=c.match(r);d&&o.push({name:c,n:Number(d[1])})}if(o.length<=e)return;o.sort((c,d)=>c.n-d.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(c=>is.unlink(po.join(n,c.name))))}async function tC(t){await eC(O.logFile(),ly);let e=await ZA({file:O.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:ly,removeOtherLogFiles:!0}}),n=cy.destination(2);return{stream:cy.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function nC(t){let e=py.createServer(t.tlsOptions,n=>{let s=fy.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function sC(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.`)}Vr();an();ba();Aa();async function wy(t={}){let e=await Ae(),n=await Vo();if(await kc(e)){let r=await go();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
329
+ `);return}if(Mi(t,"foreground")){process.title="hydra-daemon";let r=await hy(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
330
330
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
331
331
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
332
332
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
333
333
  `),process.exit(1)},i);c.unref();try{await r.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
334
334
  `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Ic(),await xc(e);let s=await go();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
335
- `)}async function wy(){let t=await go();if(!t){process.stdout.write(`No running daemon found.
335
+ `)}async function by(){let t=await go();if(!t){process.stdout.write(`No running daemon found.
336
336
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
337
337
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
338
- `)}}async function by(){let t=await Ae();await Vo();let e=await go();if(e&&Fn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
338
+ `)}}async function vy(){let t=await Ae();await Vo();let e=await go();if(e&&Fn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
339
339
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
340
- `),process.exit(1)}await iC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
340
+ `),process.exit(1)}await lC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
341
341
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
342
342
  `);if(Ic(),await xc(t),await kc(t)){let n=await go();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
343
- `)}}async function iC(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Fn(t))return!0;await rC(50)}return!1}async function vy(t){await mo(O.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Sy(){let t=await go();if(!t){process.stdout.write(`Daemon: not running
343
+ `)}}async function lC(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Fn(t))return!0;await cC(50)}return!1}async function Sy(t){await mo(O.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function ky(){let t=await go();if(!t){process.stdout.write(`Daemon: not running
344
344
  `),process.stdout.write(`CLI version: ${be}
345
345
  `);return}let e=Fn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
346
- `);let n,s;if(e)try{let o=await Ae();n=await Yr(o),s=ir(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${be}
346
+ `);let n,s;if(e)try{let o=await Ae();n=await Yr(o),s=or(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${be}
347
347
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
348
348
  `);return}let r=n.version===be,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${be}
349
349
  `);return}process.stdout.write(`CLI version: ${be}
350
350
  `),process.stdout.write(`Daemon version: ${n.version}
351
- `),r||process.stdout.write(gy.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(gy.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function go(){return Cs()}Qe();xs();lr();Dr();Go();es();Ra();Kr();import*as vn from"fs/promises";import*as Fy from"os";import*as Sn from"path";_c();async function Oy(t={}){let e=await Ae(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Fe(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
351
+ `),r||process.stdout.write(yy.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(yy.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function go(){return Cs()}Ge();xs();ur();Dr();Go();es();Ra();Kr();import*as vn from"fs/promises";import*as Oy from"os";import*as Sn from"path";_c();async function Ly(t={}){let e=await Ae(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Oe(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
352
352
  `);return}if(a.length===0){if(o==="local"&&r.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
353
353
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
354
354
  `);return}process.stdout.write(`No active sessions.
355
- `);return}let c=a.slice().sort((y,w)=>{let b=(w.status==="warm"?1:0)-(y.status==="warm"?1:0);return b!==0?b:String(w.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(k=>k.status!=="cold").length,w=e.sessionListColdLimit,b=c.slice(y,y+w),S=c.length-y-b.length;d=[...c.slice(0,y),...b],l=S}let f=Date.now(),u=d.map(y=>ko(y,f)),p={columns:t.columns??e.tui.sessionColumns??vo,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Io(u,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(So,h,m,p)+`
356
- `);for(let y of u)process.stdout.write(ur(y,h,m,p)+`
355
+ `);return}let c=a.slice().sort((y,w)=>{let b=(w.status==="warm"?1:0)-(y.status==="warm"?1:0);return b!==0?b:String(w.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(k=>k.status!=="cold").length,w=e.sessionListColdLimit,b=c.slice(y,y+w),S=c.length-y-b.length;d=[...c.slice(0,y),...b],l=S}let f=Date.now(),u=d.map(y=>ko(y,f)),p={columns:t.columns??e.tui.sessionColumns??vo,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Io(u,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(fr(So,h,m,p)+`
356
+ `);for(let y of u)process.stdout.write(fr(y,h,m,p)+`
357
357
  `);l>0&&process.stdout.write(`
358
358
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
359
- `)}async function Ly(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
360
- `),process.exit(2));let e=await Fe(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
359
+ `)}async function By(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
360
+ `),process.exit(2));let e=await Oe(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
361
361
  `),process.exit(1)),process.stdout.write(`Killed ${t}
362
- `)}async function By(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
363
- `),process.exit(2));let e=await Fe(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
362
+ `)}async function Ny(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
363
+ `),process.exit(2));let e=await Oe(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
364
364
  `),process.exit(1)),process.stdout.write(`Removed ${t}
365
- `)}async function Ny(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Fe("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
365
+ `)}async function Dy(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Oe("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
366
366
  `);return}let i=t.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(r.considered===0){let a=e>0?` older than ${e}d`:"";process.stdout.write(`No ${i} sessions${a} found.
367
367
  `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${wo(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
368
368
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
369
369
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
370
- `)}async function Dy(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
370
+ `)}async function Hy(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
371
371
  `),process.exit(2));let s=await Fr(),r=await yo(),i=n==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
372
372
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
373
373
  `)||process.stdout.write(`
374
- `);return}let c=e==="."?IC(o,t):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
375
- `)}async function Hy(t,e,n={}){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
376
- `),process.exit(2));let s=n.includeTools??!1,r,i,o=await wC(t);if(o!==null){let c=bC(o.raw);r=cc(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${Sn.basename(t,Sn.extname(t))}-${d}.md`}else{let c=await Fr(),d=await yo(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(t)}/transcript`);s&&l.searchParams.set("tools","1");let f=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!f.ok){let p=await f.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${f.status}: ${p}
374
+ `);return}let c=e==="."?TC(o,t):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
375
+ `)}async function Uy(t,e,n={}){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
376
+ `),process.exit(2));let s=n.includeTools??!1,r,i,o=await IC(t);if(o!==null){let c=xC(o.raw);r=cc(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${Sn.basename(t,Sn.extname(t))}-${d}.md`}else{let c=await Fr(),d=await yo(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(t)}/transcript`);s&&l.searchParams.set("tools","1");let f=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!f.ok){let p=await f.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${f.status}: ${p}
377
377
  `),process.exit(1)}r=await f.text();let u=new Date().toISOString().replace(/[:.]/g,"-");i=`hydra-${t}-${u}.md`}if(!e){process.stdout.write(r),r.endsWith(`
378
378
  `)||process.stdout.write(`
379
379
  `);return}let a=e==="."?i:e;await vn.mkdir(Sn.dirname(Sn.resolve(a)),{recursive:!0}),await vn.writeFile(a,r,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${a}
380
- `)}async function wC(t){try{if(!(await vn.stat(t)).isFile())return null}catch{return null}let e=await vn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
381
- `),process.exit(1)}}function bC(t){try{return On(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
382
- `),process.exit(1)}}async function Uy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
380
+ `)}async function IC(t){try{if(!(await vn.stat(t)).isFile())return null}catch{return null}let e=await vn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
381
+ `),process.exit(1)}}function xC(t){try{return On(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
382
+ `),process.exit(1)}}async function jy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
383
383
  `),process.exit(2));let n;if(e.cwd!==void 0){let a=Sn.resolve(e.cwd);try{(await vn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
384
384
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
385
- `),process.exit(1)}n=a}let s;t==="-"?s=await kC():s=await vn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
386
- `),process.exit(1)}if(e.info===!0){let a=await Ae();SC(r,a.tui.cwdColumnMaxWidth);return}let i=await Fe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
385
+ `),process.exit(1)}n=a}let s;t==="-"?s=await RC():s=await vn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
386
+ `),process.exit(1)}if(e.info===!0){let a=await Ae();CC(r,a.tui.cwdColumnMaxWidth);return}let i=await Oe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
387
387
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
388
388
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
389
389
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
390
- `)}function vC(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",compactionState:t.session.compactionState}}function SC(t,e){let n;try{n=On(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
391
- `),process.exit(1)}let s=vC(n),r=ko(s),i={columns:Mc,cwdMaxWidth:e},o=Io([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(So,o,a,i)+`
392
- `),process.stdout.write(ur(r,o,a,i)+`
390
+ `)}function AC(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",compactionState:t.session.compactionState}}function CC(t,e){let n;try{n=On(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
391
+ `),process.exit(1)}let s=AC(n),r=ko(s),i={columns:Mc,cwdMaxWidth:e},o=Io([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(fr(So,o,a,i)+`
392
+ `),process.stdout.write(fr(r,o,a,i)+`
393
393
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
394
394
  lineage: ${n.session.lineageId}
395
395
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -397,75 +397,75 @@ origin session: ${n.session.sessionId}
397
397
  origin upstream: ${c}
398
398
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
399
399
  `:`
400
- `))}async function kC(){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 IC(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`}async function jy(t,e={}){let n=await Ae(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ht(n),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),f=await Ln(d,{cwd:l,all:!0}),u=Ec(f,l);u||(process.stderr.write(`No sessions found for ${l}.
401
- `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=xC(e.host,n),a=pt(s),c=th({host:r,port:i,sessionId:a});process.stdout.write(c+`
400
+ `))}async function RC(){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 TC(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`}async function qy(t,e={}){let n=await Ae(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ht(n),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),f=await Ln(d,{cwd:l,all:!0}),u=Ec(f,l);u||(process.stderr.write(`No sessions found for ${l}.
401
+ `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=EC(e.host,n),a=pt(s),c=th({host:r,port:i,sessionId:a});process.stdout.write(c+`
402
402
  `),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.
403
- `)}function xC(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=$y(t,$n);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=$y(e.daemon.publicHost,$n);return{host:n,port:s,isFallback:!1}}return AC(e.daemon.host)?{host:CC(),port:e.daemon.port,isFallback:!1}:Lr(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 AC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function CC(){let t=Fy.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function $y(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}}Ef();_c();Af();Qe();we();Aa();lr();var cR={extension:{singular:"extension",plural:"extensions",logFile:t=>O.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>O.transformerLogFile(t)}};function Nc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Co(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Dc(t){let e=cR[t],n=`/v1/${e.plural}`;async function s(){let f=(await Fe(n,{expectStatus:200})).body[e.plural]??[];if(f.length===0){process.stdout.write(`No ${e.plural} configured.
403
+ `)}function EC(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Fy(t,$n);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Fy(e.daemon.publicHost,$n);return{host:n,port:s,isFallback:!1}}return PC(e.daemon.host)?{host:MC(),port:e.daemon.port,isFallback:!1}:Lr(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 PC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function MC(){let t=Oy.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Fy(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}}Pf();_c();Cf();Ge();we();Aa();ur();var hR={extension:{singular:"extension",plural:"extensions",logFile:t=>O.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>O.transformerLogFile(t)}};function Nc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Co(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Dc(t){let e=hR[t],n=`/v1/${e.plural}`;async function s(){let f=(await Oe(n,{expectStatus:200})).body[e.plural]??[];if(f.length===0){process.stdout.write(`No ${e.plural} configured.
404
404
  `);return}let u=f.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?wo(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:Co(p.name,u.map(y=>y.name)),status:Co(p.status,u.map(y=>y.status)),version:Co(p.version,u.map(y=>y.version)),pid:Co(p.pid,u.map(y=>y.pid)),restarts:Co(p.restarts,u.map(y=>y.restarts)),started:Co(p.started,u.map(y=>y.started))},m=y=>[y.name.padEnd(h.name),y.status.padEnd(h.status),y.version.padEnd(h.version),y.pid.padStart(h.pid),y.restarts.padStart(h.restarts),y.started.padEnd(h.started),y.log].join(" ");process.stdout.write(m(p)+`
405
405
  `);for(let y of u)process.stdout.write(m(y)+`
406
406
  `);for(let y of f)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
407
407
  `)}async function r(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
408
408
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(d)){process.stderr.write(`Invalid ${e.singular} name '${d}': must match [A-Za-z0-9._-]+
409
- `),process.exit(2);return}await Ae();let f=await bo(),u=f;(!u[e.plural]||typeof u[e.plural]!="object")&&(u[e.plural]={});let p=u[e.plural];if(p[d]){process.stderr.write(`${rw(e.singular)} '${d}' already exists in config.
410
- `),process.exit(1);return}let h=Rc(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await ff(f),process.stdout.write(`Added ${e.singular} '${d}' to ${O.config()}
411
- `);let w={name:d,...y};try{let b=await Fe(n,{method:"POST",body:w,rethrowNetworkError:!0});if(b.ok){let S=b.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
409
+ `),process.exit(2);return}await Ae();let f=await bo(),u=f;(!u[e.plural]||typeof u[e.plural]!="object")&&(u[e.plural]={});let p=u[e.plural];if(p[d]){process.stderr.write(`${iw(e.singular)} '${d}' already exists in config.
410
+ `),process.exit(1);return}let h=Rc(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await pf(f),process.stdout.write(`Added ${e.singular} '${d}' to ${O.config()}
411
+ `);let w={name:d,...y};try{let b=await Oe(n,{method:"POST",body:w,rethrowNetworkError:!0});if(b.ok){let S=b.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
412
412
  `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${b.status}${Nc(b.body)}). Restart the daemon to apply.
413
413
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
414
- `),process.exit(2);return}await Ae();let l=await bo(),f=l,u=f[e.plural]??{};if(!u[d]){process.stderr.write(`${rw(e.singular)} '${d}' not found in config.
415
- `),process.exit(1);return}delete u[d],f[e.plural]=u,await ff(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${O.config()}
416
- `);try{let p=await Fe(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
414
+ `),process.exit(2);return}await Ae();let l=await bo(),f=l,u=f[e.plural]??{};if(!u[d]){process.stderr.write(`${iw(e.singular)} '${d}' not found in config.
415
+ `),process.exit(1);return}delete u[d],f[e.plural]=u,await pf(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${O.config()}
416
+ `);try{let p=await Oe(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
417
417
  `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Nc(p.body)}).
418
418
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
419
419
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
420
- `),process.exit(2);return}if(d==="all"){await a(l);return}let f=await Fe(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!f.ok){process.stderr.write(`HTTP ${f.status}${Nc(f.body)}
420
+ `),process.exit(2);return}if(d==="all"){await a(l);return}let f=await Oe(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!f.ok){process.stderr.write(`HTTP ${f.status}${Nc(f.body)}
421
421
  `),process.exit(1);return}let u=f.body,p=u.pid!=null?` pid=${u.pid}`:"";process.stdout.write(`${d}: ${u.status}${p}
422
- `)}async function a(d){let p=((await Fe(n,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
423
- `);return}let h=0;for(let m of p)try{let y=await Fe(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${Nc(y.body)}
422
+ `)}async function a(d){let p=((await Oe(n,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
423
+ `);return}let h=0;for(let m of p)try{let y=await Oe(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${Nc(y.body)}
424
424
  `),h+=1;continue}let w=y.body,b=w.pid!=null?` pid=${w.pid}`:"";process.stdout.write(`${m.name}: ${w.status}${b}
425
425
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
426
426
  `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:f}=Ac(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
427
- `),process.exit(2);return}let u=e.logFile(l);await mo(u,f,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function rw(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Xr=Dc("extension"),iw=Xr.list,ow=Xr.add,aw=Xr.remove,dw=Xr.start,cw=Xr.stop,lw=Xr.restart,uw=Xr.logs;var Zr=Dc("transformer"),fw=Zr.list,pw=Zr.add,hw=Zr.remove,mw=Zr.start,gw=Zr.stop,yw=Zr.restart,ww=Zr.logs;zc();Ca();uo();jr();Qe();Dr();Vr();Ot();an();Id();qf();import CR from"os";import{spawn as RR}from"child_process";async function TR({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){let i;try{let c=await t.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",f=>{d({exitCode:f})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await ER(c,s),f=await jf(l,{authenticate:u=>t.request("authenticate",{methodId:u,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return f.kind==="terminal-completed"?{exitCode:0}:f.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
427
+ `),process.exit(2);return}let u=e.logFile(l);await mo(u,f,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function iw(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Xr=Dc("extension"),ow=Xr.list,aw=Xr.add,dw=Xr.remove,cw=Xr.start,lw=Xr.stop,uw=Xr.restart,fw=Xr.logs;var Zr=Dc("transformer"),pw=Zr.list,hw=Zr.add,mw=Zr.remove,gw=Zr.start,yw=Zr.stop,ww=Zr.restart,bw=Zr.logs;zc();Ca();uo();jr();Ge();Dr();Vr();Ot();an();Id();Wf();import MR from"os";import{spawn as _R}from"child_process";async function $R({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){let i;try{let c=await t.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",f=>{d({exitCode:f})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await FR(c,s),f=await qf(l,{authenticate:u=>t.request("authenticate",{methodId:u,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return f.kind==="terminal-completed"?{exitCode:0}:f.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
428
428
  `),{exitCode:0}):f.kind==="error"?(process.stderr.write(`${f.message}
429
429
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${f.exitCode}
430
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:CR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
431
- `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===j.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,f=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,f)}throw c}}async function ER(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
430
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:MR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
431
+ `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===j.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,f=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,f)}throw c}}async function FR(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
432
432
  `),process.exit(2)}if(t.length===1)return t[0];if(process.stdin.isTTY===!0){let s=t.map((c,d)=>`${d+1}) ${c.id} \u2014 ${c.name??c.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
433
433
  ${s.join(`
434
434
  `)}
435
435
  `);let{createInterface:r}=await import("readline/promises"),i=r({input:process.stdin,output:process.stdout}),o=await i.question("method> ");i.close();let a=parseInt(o.trim(),10);return(Number.isNaN(a)||a<1||a>t.length)&&(process.stderr.write(`invalid selection "${o}" \u2014 enter a number between 1 and ${t.length}
436
436
  `),process.exit(2)),t[a-1]}let n=t.map(s=>s.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${n})
437
- `),process.exit(2)}async function Uw(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
438
- `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(zc(),Iw)),s=await n(t,"hydra agent auth"),r=await Ae(),i=await Ht(r);await cr(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Qr(i.wsUrl,o),c=rs(a),d=new Kt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:be}})}catch{}let l;try{l=await TR({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:RR})}finally{a.close()}process.exit(l.exitCode)}Aa();jl();lr();async function jw(t){let e=Mi(t,"force");if(await pc()&&!e){let r=await Bi("Current password: ");await hc(r)||(process.stderr.write(`Wrong password.
437
+ `),process.exit(2)}async function jw(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
438
+ `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(zc(),xw)),s=await n(t,"hydra agent auth"),r=await Ae(),i=await Ht(r);await lr(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Qr(i.wsUrl,o),c=rs(a),d=new Kt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:be}})}catch{}let l;try{l=await $R({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:_R})}finally{a.close()}process.exit(l.exitCode)}Aa();ql();ur();async function qw(t){let e=Mi(t,"force");if(await pc()&&!e){let r=await Bi("Current password: ");await hc(r)||(process.stderr.write(`Wrong password.
439
439
  `),process.exit(1))}let n=await Bi("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
440
440
  `),process.exit(2));let s=await Bi("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
441
- `),process.exit(1)),await Vg(n),process.stdout.write(`Password set.
442
- `)}async function qw(){let e=(await Fe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
441
+ `),process.exit(1)),await Qg(n),process.stdout.write(`Password set.
442
+ `)}async function Ww(){let e=(await Oe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
443
443
  `);return}let n={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:Qc(n.id,s.map(o=>o.id)),label:Qc(n.label,s.map(o=>o.label)),createdAt:Qc(n.createdAt,s.map(o=>o.createdAt)),expiresAt:Qc(n.expiresAt,s.map(o=>o.expiresAt))},i=o=>[o.id.padEnd(r.id),o.label.padEnd(r.label),o.createdAt.padEnd(r.createdAt),o.expiresAt.padEnd(r.expiresAt),o.lastUsedAt].join(" ");process.stdout.write(i(n)+`
444
444
  `);for(let o of s)process.stdout.write(i(o)+`
445
- `)}async function Ww(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
446
- `),process.exit(2));let e=await Fe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
445
+ `)}async function zw(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
446
+ `),process.exit(2));let e=await Oe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
447
447
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
448
448
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
449
- `),process.exit(1)}function Qc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as mr from"fs";Qe();Dr();Vr();Wf();Ot();var Gc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Kf(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(zf(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(!zf(e)&&!Kf(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(zf(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,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:u,toolCallId:h,params:f};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!Kf(e)||e.id===null)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=rn(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,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);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function zf(t){return"method"in t&&"id"in t&&t.id!==void 0}function Kf(t){return!("method"in t)&&"id"in t}Zc();an();we();Xo();import{writeFileSync as OR}from"fs";var LR=t=>{OR("/proc/self/comm",t)};function $o(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??LR;try{s(e.commName??Gn())}catch{}}function Fo(t,e=Gn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function tl(t){$o(Fo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ae(),n=t.target??await Ht(e);n.isLocal&&!t.target&&await cr(e);let s=new Gc,r=Td(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ht(await Ae())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new _o({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await jR(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
450
- `);for(let l of d)await qR(a,l,s.lastMessageId(l.sessionId))}}});BR({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
451
- `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function BR({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(Gw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&JR(i)){e.send({jsonrpc:"2.0",id:i.id,result:ii(i.params)});return}NR(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(Gw("client\u2192daemon",i),s.observeFromClient(i),zR(i)){e.send(KR(i));return}if(WR(i)){if(t.sessionId){e.send(YR(i,t.sessionId));return}let o=i;t.agentId&&(o=el(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=el(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=el(o,{title:r.name}),r.used=!0),t.model&&(o=el(o,{model:t.model})),e.send(o);return}e.send(i)})}function NR(t,e,n){let s=DR(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=UR(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function DR(t){if(!HR(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function HR(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function UR(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function jR(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
452
- `);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 qR(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}
449
+ `),process.exit(1)}function Qc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as gr from"fs";Ge();Dr();Vr();zf();Ot();var Gc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Jf(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(Kf(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(!Kf(e)&&!Jf(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(Kf(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,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:u,toolCallId:h,params:f};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!Jf(e)||e.id===null)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=rn(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,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);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Kf(t){return"method"in t&&"id"in t&&t.id!==void 0}function Jf(t){return!("method"in t)&&"id"in t}Zc();an();we();Xo();import{writeFileSync as HR}from"fs";var UR=t=>{HR("/proc/self/comm",t)};function $o(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??UR;try{s(e.commName??Gn())}catch{}}function Fo(t,e=Gn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function tl(t){$o(Fo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ae(),n=t.target??await Ht(e);n.isLocal&&!t.target&&await lr(e);let s=new Gc,r=Td(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ht(await Ae())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new _o({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await JR(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
450
+ `);for(let l of d)await YR(a,l,s.lastMessageId(l.sessionId))}}});jR({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
451
+ `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function jR({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(Xw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&XR(i)){e.send({jsonrpc:"2.0",id:i.id,result:ii(i.params)});return}qR(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(Xw("client\u2192daemon",i),s.observeFromClient(i),QR(i)){e.send(GR(i));return}if(VR(i)){if(t.sessionId){e.send(ZR(i,t.sessionId));return}let o=i;t.agentId&&(o=el(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=el(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=el(o,{title:r.name}),r.used=!0),t.model&&(o=el(o,{model:t.model})),e.send(o);return}e.send(i)})}function qR(t,e,n){let s=WR(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=KR(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function WR(t){if(!zR(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function zR(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function KR(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function JR(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
452
+ `);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 YR(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}
453
453
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
454
- `)}}function WR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function zR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function KR(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:be}}}}function JR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function YR(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var VR=25*1024*1024,Qw=!1,oi=null;function Gw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Qw){Qw=!0;try{oi=O.shimWireLogFile(),mr.mkdirSync(O.home(),{recursive:!0});let n=mr.statSync(oi,{throwIfNoEntry:!1});n&&n.size>VR&&mr.renameSync(oi,`${oi}.1`)}catch{oi=null}}if(oi)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
455
- `;mr.appendFile(oi,n,()=>{})}catch{}}}function el(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}jr();uo();Ca();Qe();Dr();Vr();or();Ot();an();Zc();import{mkdtempSync as o0,rmSync as a0}from"fs";import{tmpdir as d0}from"os";import{join as c0}from"path";function Xw(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())}}}Ao();import QR from"chalk";import GR from"strip-ansi";var nl=new QR.Instance({level:3});function Zw(t,e){if(t.length===0)return"";let n=hr(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(XR(i,e));let r=s.join(`
454
+ `)}}function VR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function QR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function GR(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:be}}}}function XR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function ZR(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var e0=25*1024*1024,Gw=!1,oi=null;function Xw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Gw){Gw=!0;try{oi=O.shimWireLogFile(),gr.mkdirSync(O.home(),{recursive:!0});let n=gr.statSync(oi,{throwIfNoEntry:!1});n&&n.size>e0&&gr.renameSync(oi,`${oi}.1`)}catch{oi=null}}if(oi)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
455
+ `;gr.appendFile(oi,n,()=>{})}catch{}}}function el(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}jr();uo();Ca();Ge();Dr();Vr();ar();Ot();an();Zc();import{mkdtempSync as u0,rmSync as f0}from"fs";import{tmpdir as p0}from"os";import{join as h0}from"path";function Zw(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())}}}Ao();import t0 from"chalk";import n0 from"strip-ansi";var nl=new t0.Instance({level:3});function eb(t,e){if(t.length===0)return"";let n=mr(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(s0(i,e));let r=s.join(`
456
456
  `);return r.endsWith(`
457
457
  `)||(r+=`
458
- `),r}function XR(t,e){let n=r0(t.body,e);return e==="ansi"?n=i0(n,t.bodyStyle):n=GR(n),n}var ZR="\x1B[1m",e0="\x1B[96m",t0="\x1B[93m",n0="\x1B[0m",s0="\0";function r0(t,e){let n=t.replace(/\^\^/g,s0);return e==="ansi"&&(n=n.replace(/\^\+/g,ZR).replace(/\^C/g,e0).replace(/\^Y/g,t0).replace(/\^:/g,n0)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function i0(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return nl.bold.yellowBright(t);case"heading-2":return nl.bold.cyanBright(t);case"heading-3":return nl.bold(t);case"dim":return nl.dim(t);default:return t}}var l0=1*1024*1024,eb="mcp__hydra-acp-stdin__";function tb(t,e){return{sessionId:t,prompt:e,_meta:{[Ft]:{ancillary:!0}}}}function u0(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 f0(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(eb))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(eb))}async function nb(t){if($o(Fo(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.
459
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=o0(c0(d0(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{a0(c,{recursive:!0,force:!0})}catch{}})}let e=await Ae(),n=t.target??await Ht(e);n.isLocal&&!t.target&&await cr(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Qr(n.wsUrl,s),i=rs(r),o=new Kt(i),a=await h0({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:p0(n.baseUrl,n.token)});process.exit(a.exitCode)}function p0(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 h0(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=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 Q=>n.dangerouslySkipPermissions?ii(Q):f0(Q)?ii(Q):Jw(Q));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:qr,version:be}})}catch{}let f=await y0(e,n,l),u=!1,p=!0,h="",m=0,y=Q=>{Q.length!==0&&(o(Q),p=Q.charCodeAt(Q.length-1)===10,u=!0)},w=()=>{if(d||h.length===0)return;let Q=Zw(h,c);if(h="",Q.length===0)return;let fe=m>0?`
458
+ `),r}function s0(t,e){let n=c0(t.body,e);return e==="ansi"?n=l0(n,t.bodyStyle):n=n0(n),n}var r0="\x1B[1m",i0="\x1B[96m",o0="\x1B[93m",a0="\x1B[0m",d0="\0";function c0(t,e){let n=t.replace(/\^\^/g,d0);return e==="ansi"&&(n=n.replace(/\^\+/g,r0).replace(/\^C/g,i0).replace(/\^Y/g,o0).replace(/\^:/g,a0)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function l0(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return nl.bold.yellowBright(t);case"heading-2":return nl.bold.cyanBright(t);case"heading-3":return nl.bold(t);case"dim":return nl.dim(t);default:return t}}var m0=1*1024*1024,tb="mcp__hydra-acp-stdin__";function nb(t,e){return{sessionId:t,prompt:e,_meta:{[Ft]:{ancillary:!0}}}}function g0(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 y0(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(tb))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(tb))}async function sb(t){if($o(Fo(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.
459
+ `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=u0(h0(p0(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{f0(c,{recursive:!0,force:!0})}catch{}})}let e=await Ae(),n=t.target??await Ht(e);n.isLocal&&!t.target&&await lr(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Qr(n.wsUrl,s),i=rs(r),o=new Kt(i),a=await b0({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:w0(n.baseUrl,n.token)});process.exit(a.exitCode)}function w0(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 b0(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=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 Q=>n.dangerouslySkipPermissions?ii(Q):y0(Q)?ii(Q):Yw(Q));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:qr,version:be}})}catch{}let f=await k0(e,n,l),u=!1,p=!0,h="",m=0,y=Q=>{Q.length!==0&&(o(Q),p=Q.charCodeAt(Q.length-1)===10,u=!0)},w=()=>{if(d||h.length===0)return;let Q=eb(h,c);if(h="",Q.length===0)return;let fe=m>0?`
460
460
  `:"";y(fe+Q),m+=1},b=()=>{w(),u&&!p&&y(`
461
- `),u=!1};e.onNotification("session/update",Q=>{let fe=Q?.update,Me=ss(fe,{cwd:n.cwd});if(Me){if(Me.kind==="agent-text"){d?y(Me.text):h+=Me.text;return}if(Me.kind==="turn-complete"){b();return}switch(Me.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":w();return;default:return}}});let S=!1,k=async Q=>{let fe=[];if(n.prompt&&!S&&fe.push({type:"text",text:n.prompt}),Q.length>0&&fe.push({type:"text",text:Q}),fe.length!==0){try{await e.request("session/prompt",tb(f,fe)),S=!0}catch(Me){a(`hydra-acp cat: prompt failed: ${Me.message}
461
+ `),u=!1};e.onNotification("session/update",Q=>{let fe=Q?.update,Me=ss(fe,{cwd:n.cwd});if(Me){if(Me.kind==="agent-text"){d?y(Me.text):h+=Me.text;return}if(Me.kind==="turn-complete"){b();return}switch(Me.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":w();return;default:return}}});let S=!1,k=async Q=>{let fe=[];if(n.prompt&&!S&&fe.push({type:"text",text:n.prompt}),Q.length>0&&fe.push({type:"text",text:Q}),fe.length!==0){try{await e.request("session/prompt",nb(f,fe)),S=!0}catch(Me){a(`hydra-acp cat: prompt failed: ${Me.message}
462
462
  `);return}b()}},A=0,E,P=new Promise(Q=>{E=Q}),B=!1,_=async Q=>{B||(B=!0,b(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:f}))().catch(()=>{}),new Promise(Me=>setTimeout(Me,500))]),await e.close().catch(()=>{}),E({exitCode:Q}))};e.onClose(Q=>{Q&&(a(`hydra-acp cat: ${Q.message}
463
- `),A=1),B||(B=!0,b(),E({exitCode:A}))});let D=[],N=!1,L=!1,K=async()=>{if(!N){N=!0;try{for(;D.length>0;){let Q=D.shift();if(Q===void 0)break;await k(Q)}}finally{N=!1,L&&D.length===0&&await _(A)}}};if(r&&!n.sessionId)return n.prompt&&await k(""),await _(0),P;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),m0({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:k,onEof:()=>{L=!0,!N&&D.length===0&&_(A)},onError:Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
463
+ `),A=1),B||(B=!0,b(),E({exitCode:A}))});let D=[],N=!1,L=!1,K=async()=>{if(!N){N=!0;try{for(;D.length>0;){let Q=D.shift();if(Q===void 0)break;await k(Q)}}finally{N=!1,L&&D.length===0&&await _(A)}}};if(r&&!n.sessionId)return n.prompt&&await k(""),await _(0),P;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),v0({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:k,onEof:()=>{L=!0,!N&&D.length===0&&_(A)},onError:Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
464
464
  `),A=1,L=!0,!N&&D.length===0&&_(A)},onPromptFailed:Q=>{a(`hydra-acp cat: ${Q.message}
465
- `),A=1,L=!0,!N&&D.length===0&&_(A)}}),P;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let Q=Xw({scheduleFlushCheck:fe=>{let Me=setImmediate(fe);return()=>clearImmediate(Me)},onChunk:fe=>{D.push(fe),K()}});return s.on("data",fe=>{Q.feed(typeof fe=="string"?fe:fe.toString("utf8"))}),s.on("end",()=>{Q.eof(),L=!0,!N&&D.length===0&&_(A)}),s.on("error",fe=>{a(`hydra-acp cat: stdin error: ${fe.message}
465
+ `),A=1,L=!0,!N&&D.length===0&&_(A)}}),P;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let Q=Zw({scheduleFlushCheck:fe=>{let Me=setImmediate(fe);return()=>clearImmediate(Me)},onChunk:fe=>{D.push(fe),K()}});return s.on("data",fe=>{Q.feed(typeof fe=="string"?fe:fe.toString("utf8"))}),s.on("end",()=>{Q.eof(),L=!0,!N&&D.length===0&&_(A)}),s.on("error",fe=>{a(`hydra-acp cat: stdin error: ${fe.message}
466
466
  `),A=1,L=!0,!N&&D.length===0&&_(A)}),P}let Z="";return s.on("data",Q=>{Z+=typeof Q=="string"?Q:Q.toString("utf8")}),s.on("end",()=>{L=!0,Z.length>0&&D.push(Z),K()}),s.on("error",Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
467
- `),A=1,L=!0,!N&&D.length===0&&_(A)}),P}function m0(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??l0,d="undecided",l=!1,f=[],u=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let k=b.toString("base64");h=h.then(()=>n.write(s,k,S)).catch(A=>{o(`hydra-acp cat: stdin write failed: ${A.message}
468
- `)})},y=async()=>{d="inline";let b=Buffer.concat(f,u).toString("utf8");f=[],u=0;try{await a(b)}catch(S){t.onPromptFailed(S);return}t.onEof()},w=async()=>{d="pivoting";let b;try{let A={mode:"memory"};r.streamBufferBytes!==void 0&&(A.capacityBytes=r.streamBufferBytes),b=await n.open(s,A)}catch(A){t.onPromptFailed(new Error(`stdin/open failed: ${A.message}`));return}u>0&&(m(Buffer.concat(f,u),!1),f=[],u=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=g0(r.prompt,b.capacityBytes);e.request("session/prompt",tb(s,[{type:"text",text:S}])).catch(A=>{t.onPromptFailed(new Error(`prompt failed: ${A.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",b=>{let S=typeof b=="string"?Buffer.from(b,"utf8"):b;if(d==="undecided"){f.push(S),u+=S.length,u>c&&w();return}if(d==="pivoting"){f.push(S),u+=S.length;return}if(d==="file"){m(S,!1);return}f.push(S),u+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function g0(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:
467
+ `),A=1,L=!0,!N&&D.length===0&&_(A)}),P}function v0(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??m0,d="undecided",l=!1,f=[],u=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let k=b.toString("base64");h=h.then(()=>n.write(s,k,S)).catch(A=>{o(`hydra-acp cat: stdin write failed: ${A.message}
468
+ `)})},y=async()=>{d="inline";let b=Buffer.concat(f,u).toString("utf8");f=[],u=0;try{await a(b)}catch(S){t.onPromptFailed(S);return}t.onEof()},w=async()=>{d="pivoting";let b;try{let A={mode:"memory"};r.streamBufferBytes!==void 0&&(A.capacityBytes=r.streamBufferBytes),b=await n.open(s,A)}catch(A){t.onPromptFailed(new Error(`stdin/open failed: ${A.message}`));return}u>0&&(m(Buffer.concat(f,u),!1),f=[],u=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=S0(r.prompt,b.capacityBytes);e.request("session/prompt",nb(s,[{type:"text",text:S}])).catch(A=>{t.onPromptFailed(new Error(`prompt failed: ${A.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",b=>{let S=typeof b=="string"?Buffer.from(b,"utf8"):b;if(d==="undecided"){f.push(S),u+=S.length,u>c&&w();return}if(d==="pivoting"){f.push(S),u+=S.length;return}if(d==="file"){m(S,!1);return}f.push(S),u+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function S0(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:
469
469
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
470
470
  - \`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.
471
471
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -480,50 +480,50 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
480
480
  User's question:
481
481
  ${t}`:`${s}
482
482
 
483
- 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 y0(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:qr,version:be}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=u0(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={[Ft]:s});let o=await t.request("session/new",i);return rn(o._meta),o.sessionId}Qe();we();function sl(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function sb(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function w0(t){try{return JSON.parse(t)}catch{return t}}function rb(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function ib(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
484
- `),process.exit(2));let e=sl(t),n=await Ae(),s=sb(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
485
- `),process.exit(1)),process.stdout.write(`${rb(s)}
486
- `)}async function ob(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
487
- `),process.exit(2));let n=sl(t),s=w0(e);try{await As(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
488
- `),process.exit(1)}process.stdout.write(`set ${t} = ${rb(s)}
489
- `)}async function ab(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
483
+ 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 k0(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:qr,version:be}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=g0(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={[Ft]:s});let o=await t.request("session/new",i);return rn(o._meta),o.sessionId}Ge();we();function sl(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function rb(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function I0(t){try{return JSON.parse(t)}catch{return t}}function ib(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function ob(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
484
+ `),process.exit(2));let e=sl(t),n=await Ae(),s=rb(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
485
+ `),process.exit(1)),process.stdout.write(`${ib(s)}
486
+ `)}async function ab(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
487
+ `),process.exit(2));let n=sl(t),s=I0(e);try{await As(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
488
+ `),process.exit(1)}process.stdout.write(`set ${t} = ${ib(s)}
489
+ `)}async function db(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
490
490
  `),process.exit(2));let e=sl(t);try{await As(n=>{let s=n;for(let r=0;r<e.length-1;r++){let i=e[r],o=s[i];if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}delete s[e[e.length-1]]})}catch(n){process.stderr.write(`${n.message}
491
491
  `),process.exit(1)}process.stdout.write(`unset ${t}
492
- `)}async function db(t){let e=await Ae(),n=t?sb(e,sl(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
492
+ `)}async function cb(t){let e=await Ae(),n=t?rb(e,sl(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
493
493
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
494
- `)}function cb(){process.stdout.write(`${O.config()}
495
- `)}Qe();xs();Vr();an();lr();async function fb(t={}){let{report:e,configLoaded:n}=await b0();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
494
+ `)}function lb(){process.stdout.write(`${O.config()}
495
+ `)}Ge();xs();Vr();an();ur();async function pb(t={}){let{report:e,configLoaded:n}=await x0();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
496
496
  `);return}process.stdout.write(`CLI: ${e.cli}
497
497
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
498
- `),e.daemonReachable&&(lb("Extensions",e.extensions),lb("Transformers",e.transformers)))}function lb(t,e){if(process.stdout.write(`
498
+ `),e.daemonReachable&&(ub("Extensions",e.extensions),ub("Transformers",e.transformers)))}function ub(t,e){if(process.stdout.write(`
499
499
  ${t}:
500
500
  `),e.length===0){process.stdout.write(` (none)
501
501
  `);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}
502
- `)}}async function b0(){let t={cli:be,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ae()}catch{return{report:t,configLoaded:!1}}let n=await Yr(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 Fr()}catch{return{report:t,configLoaded:!0}}let r=await yo(),i={Authorization:`Bearer ${s}`};return t.extensions=await ub(`${r}/v1/extensions`,i,"extensions"),t.transformers=await ub(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function ub(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 v0}from"child_process";import{accessSync as S0,constants as k0,statSync as I0}from"fs";import{delimiter as x0,join as A0}from"path";var C0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function R0(t){return C0.has(t)}function T0(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function E0(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 P0(t){try{if(!I0(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return S0(t,k0.X_OK),!0}catch{return!1}}function M0(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(x0).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 c=A0(o,r+a);if(P0(c))return c}}function _0(t,e){let n=v0(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
503
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function pb(t){let e=T0(t);if(e===void 0||R0(e))return!1;let n=M0(e);if(n===void 0)return!1;_0(n,E0(t))}Jf();var vr=!1,Nv=!1;function Dv(t){!t||Nv||(Nv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
504
- `))}async function BE(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(ta(),lh));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let w=e.slice(0,n),b=e.slice(n+1),S=b[0],k=b.slice(1),{flags:A}=$l(w);if(Uv(A),A.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
502
+ `)}}async function x0(){let t={cli:be,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ae()}catch{return{report:t,configLoaded:!1}}let n=await Yr(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 Fr()}catch{return{report:t,configLoaded:!0}}let r=await yo(),i={Authorization:`Bearer ${s}`};return t.extensions=await fb(`${r}/v1/extensions`,i,"extensions"),t.transformers=await fb(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function fb(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 A0}from"child_process";import{accessSync as C0,constants as R0,statSync as T0}from"fs";import{delimiter as E0,join as P0}from"path";var M0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function _0(t){return M0.has(t)}function $0(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function F0(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 O0(t){try{if(!T0(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return C0(t,R0.X_OK),!0}catch{return!1}}function L0(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(E0).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 c=P0(o,r+a);if(O0(c))return c}}function B0(t,e){let n=A0(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
503
+ `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function hb(t){let e=$0(t);if(e===void 0||_0(e))return!1;let n=L0(e);if(n===void 0)return!1;B0(n,F0(t))}Yf();var vr=!1,Dv=!1;function Hv(t){!t||Dv||(Dv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
504
+ `))}async function WE(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(ta(),lh));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let w=e.slice(0,n),b=e.slice(n+1),S=b[0],k=b.slice(1),{flags:A}=Fl(w);if(jv(A),A.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
505
505
  `),process.exit(2);return}let E=S??It(A,"agent");if(!E){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
506
- `),process.exit(2);return}let P=await jv(Ql(A),{allowPrompt:!1}),B=It(A,"name"),_=It(A,"model");vr=!0;let D=A["dangerously-skip-permissions"]===!0;Dv(D);let N={agentId:E,agentArgs:k,name:B,model:_,dangerouslySkipPermissions:D};P?.sessionId!==void 0&&(N.sessionId=P.sessionId),P?.target!==void 0&&P.fromUrl&&(N.target=P.target),await tl(N);return}Op(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&pb(e);let{positional:s,flags:r}=$l(e);if(Uv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${NE()}
507
- `);return}if(r.help===!0){Dp(s[0]);return}let i=Op(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=It(r,"name"),d=It(r,"agent"),l=It(r,"model"),f=r["dangerously-skip-permissions"]===!0;Dv(f);let u=Ql(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await jv(u,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
508
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){vr=!0,await Hv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:f});return}vr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await tl(w);return}switch(a){case"acp":case"shim":{vr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await tl(w);return}case"cat":{let w=Op(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=w??b,k=It(r,"cwd"),A={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:f};k!==void 0&&(A.cwd=k),y!==void 0&&(A.target=y);let E=Np(r,"stream-threshold");E!==void 0&&(A.streamThreshold=E);let P=Np(r,"stream-bytes");P!==void 0&&(A.streamBufferBytes=P),d!==void 0&&await Uc(d),vr=!0,await nb(A);return}case"version":{vr=!0,await fb({json:r.json===!0});return}case"init":await Sh(r);return;case"daemon":{let w=e.indexOf("daemon"),b=e.slice(w+1),S=b[0];if(S===void 0||S==="status"){await Sy();return}if(S==="start"){await yy(r);return}if(S==="stop"){await wy();return}if(S==="restart"){await by();return}if(S==="log"||S==="logs"){await vy(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
509
- `),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=It(r,"columns"),S;if(b!==void 0)try{S=_y(b)}catch(k){process.stderr.write(`${k.message}
510
- `),process.exit(2);return}await Oy({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(w==="info"){await sw(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(w==="diff"){await nw(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(w==="kill"){await Ly(s[2]);return}if(w==="remove"){await By(s[2]);return}if(w==="collect"){let b=It(r,"max-age-days"),S=It(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(b!==void 0){let A=Number(b);if(!Number.isFinite(A)||A<0){process.stderr.write(`--max-age-days must be a non-negative number
506
+ `),process.exit(2);return}let P=await qv(Gl(A),{allowPrompt:!1}),B=It(A,"name"),_=It(A,"model");vr=!0;let D=A["dangerously-skip-permissions"]===!0;Hv(D);let N={agentId:E,agentArgs:k,name:B,model:_,dangerouslySkipPermissions:D};P?.sessionId!==void 0&&(N.sessionId=P.sessionId),P?.target!==void 0&&P.fromUrl&&(N.target=P.target),await tl(N);return}Op(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&hb(e);let{positional:s,flags:r}=Fl(e);if(jv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${zE()}
507
+ `);return}if(r.help===!0){Dp(s[0]);return}let i=Op(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=It(r,"name"),d=It(r,"agent"),l=It(r,"model"),f=r["dangerously-skip-permissions"]===!0;Hv(f);let u=Gl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await qv(u,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
508
+ `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){vr=!0,await Uv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:f});return}vr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await tl(w);return}switch(a){case"acp":case"shim":{vr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await tl(w);return}case"cat":{let w=Op(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=w??b,k=It(r,"cwd"),A={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:f};k!==void 0&&(A.cwd=k),y!==void 0&&(A.target=y);let E=Np(r,"stream-threshold");E!==void 0&&(A.streamThreshold=E);let P=Np(r,"stream-bytes");P!==void 0&&(A.streamBufferBytes=P),d!==void 0&&await Uc(d),vr=!0,await sb(A);return}case"version":{vr=!0,await pb({json:r.json===!0});return}case"init":await Sh(r);return;case"daemon":{let w=e.indexOf("daemon"),b=e.slice(w+1),S=b[0];if(S===void 0||S==="status"){await ky();return}if(S==="start"){await wy(r);return}if(S==="stop"){await by();return}if(S==="restart"){await vy();return}if(S==="log"||S==="logs"){await Sy(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
509
+ `),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=It(r,"columns"),S;if(b!==void 0)try{S=$y(b)}catch(k){process.stderr.write(`${k.message}
510
+ `),process.exit(2);return}await Ly({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(w==="info"){await rw(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(w==="diff"){await sw(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(w==="kill"){await By(s[2]);return}if(w==="remove"){await Ny(s[2]);return}if(w==="collect"){let b=It(r,"max-age-days"),S=It(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(b!==void 0){let A=Number(b);if(!Number.isFinite(A)||A<0){process.stderr.write(`--max-age-days must be a non-negative number
511
511
  `),process.exit(2);return}k.maxAgeDays=A}if(S!==void 0){let A=Number(S);if(!Number.isFinite(A)||A<=0){process.stderr.write(`--limit must be a positive number
512
- `),process.exit(2);return}k.limit=A}await Ny(k);return}if(w==="export"){let b=It(r,"out"),S=It(r,"tools");await Dy(s[2],b,S);return}if(w==="transcript"){let b=It(r,"out"),S=r.tools===!0;await Hy(s[2],b,{includeTools:S});return}if(w==="import"){let b=It(r,"cwd");await Uy(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(w==="share"){let b=It(r,"host"),S=It(r,"cwd");await jy(s[2],{...b!==void 0?{host:b}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
513
- `),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await iw();return}if(S==="add"){await ow(k,A);return}if(S==="remove"){await aw(k);return}if(S==="start"){await dw(k);return}if(S==="stop"){await cw(k);return}if(S==="restart"){await lw(k);return}if(S==="log"||S==="logs"){await uw(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
514
- `),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await fw();return}if(S==="add"){await pw(k,A);return}if(S==="remove"){await hw(k);return}if(S==="start"){await mw(k);return}if(S==="stop"){await gw(k);return}if(S==="restart"){await yw(k);return}if(S==="log"||S==="logs"){await ww(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
515
- `),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await Mf();return}if(w==="refresh"){await qc();return}if(w==="install"){await _f(s[2]);return}if(w==="sync"){await $f(s[2]);return}if(w==="set"){await Of(s[2],s[3]);return}if(w==="pin"){await Lf(s[2],s[3]);return}if(w==="add"){let b=e.indexOf(a),S=e.slice(b+1);await Bf(S[1],S.slice(2));return}if(w==="remove"){await Nf(s[2]);return}if(w==="uninstall"){await Df(s[2]);return}if(w==="log"||w==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:k,rest:A}=Ac(S);await Ff(k,A);return}if(w==="auth"){await Uw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
512
+ `),process.exit(2);return}k.limit=A}await Dy(k);return}if(w==="export"){let b=It(r,"out"),S=It(r,"tools");await Hy(s[2],b,S);return}if(w==="transcript"){let b=It(r,"out"),S=r.tools===!0;await Uy(s[2],b,{includeTools:S});return}if(w==="import"){let b=It(r,"cwd");await jy(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(w==="share"){let b=It(r,"host"),S=It(r,"cwd");await qy(s[2],{...b!==void 0?{host:b}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
513
+ `),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await ow();return}if(S==="add"){await aw(k,A);return}if(S==="remove"){await dw(k);return}if(S==="start"){await cw(k);return}if(S==="stop"){await lw(k);return}if(S==="restart"){await uw(k);return}if(S==="log"||S==="logs"){await fw(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
514
+ `),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await pw();return}if(S==="add"){await hw(k,A);return}if(S==="remove"){await mw(k);return}if(S==="start"){await gw(k);return}if(S==="stop"){await yw(k);return}if(S==="restart"){await ww(k);return}if(S==="log"||S==="logs"){await bw(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
515
+ `),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await _f();return}if(w==="refresh"){await qc();return}if(w==="install"){await $f(s[2]);return}if(w==="sync"){await Ff(s[2]);return}if(w==="set"){await Lf(s[2],s[3]);return}if(w==="pin"){await Bf(s[2],s[3]);return}if(w==="add"){let b=e.indexOf(a),S=e.slice(b+1);await Nf(S[1],S.slice(2));return}if(w==="remove"){await Df(s[2]);return}if(w==="uninstall"){await Hf(s[2]);return}if(w==="log"||w==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:k,rest:A}=Ac(S);await Of(k,A);return}if(w==="auth"){await jw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
516
516
  `),process.exit(2);return}case"registry":{let w=s[1];if(w==="refresh"){await qc();return}if(w==="pin"){await Wc(!0);return}if(w==="unpin"){await Wc(!1);return}process.stderr.write(`Unknown registry subcommand: ${w}
517
- `),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let b=s[2];if(b===void 0||b==="set"){await jw(r);return}process.stderr.write(`Unknown auth password action: ${b}
518
- `),process.exit(2);return}if(w===void 0||w==="list"){await qw();return}if(w==="revoke"){await Ww(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
519
- `),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await db(s[2]);return}if(w==="get"){await ib(s[2]);return}if(w==="set"){await ob(s[2],s[3]);return}if(w==="unset"){await ab(s[2]);return}if(w==="path"){cb();return}process.stderr.write(`Unknown config subcommand: ${w}
520
- `),process.exit(2);return}case"tui":vr=!0,await Hv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:f});return;default:process.stderr.write(`Unknown command: ${a}
521
- `),Dp(),process.exit(2)}}async function Hv(t,e){let n=It(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 Uc(e.agentId),$o(Fo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Bv(),Lv)),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.
522
- `),process.exit(2)),a.drip=!0;let c=Np(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Np(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 Uv(t){let e=Wp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
517
+ `),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let b=s[2];if(b===void 0||b==="set"){await qw(r);return}process.stderr.write(`Unknown auth password action: ${b}
518
+ `),process.exit(2);return}if(w===void 0||w==="list"){await Ww();return}if(w==="revoke"){await zw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
519
+ `),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await cb(s[2]);return}if(w==="get"){await ob(s[2]);return}if(w==="set"){await ab(s[2],s[3]);return}if(w==="unset"){await db(s[2]);return}if(w==="path"){lb();return}process.stderr.write(`Unknown config subcommand: ${w}
520
+ `),process.exit(2);return}case"tui":vr=!0,await Uv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:f});return;default:process.stderr.write(`Unknown command: ${a}
521
+ `),Dp(),process.exit(2)}}async function Uv(t,e){let n=It(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 Uc(e.agentId),$o(Fo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Nv(),Bv)),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.
522
+ `),process.exit(2)),a.drip=!0;let c=Np(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Np(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 jv(t){let e=Wp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
523
523
 
524
- `),Dp(),process.exit(2))}function Op(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 jv(t,e){try{return await yh(t,e)}catch(n){oe({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
525
- `),process.exit(1)}}function NE(){try{let t=OE(FE(import.meta.url));return JSON.parse($E(LE(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Lp=["tui"],qv=["shim","acp"],At=["cat"],xl=["launch"],DE=["init"],Al=["daemon"],HE=["version"],ht=["session","sessions"],Ga=["extension","extensions"],Xa=["transformer","transformers"],Hn=["agent","agents"],UE=["registry"],Za=["config"],Bp=["auth"];function Dp(t){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[Lp," hydra-acp tui [same flags] Force TUI explicitly."],[qv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[qv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[At," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[At," Pipe-friendly headless mode. Reads stdin and sends it"],[At," as a prompt to a fresh session, streams the agent's"],[At," response to stdout, exits when stdin closes. A bounded"],[At,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[At," as one turn; a streaming input (e.g. `tail -f`) is"],[At," chunked by the natural pauses in the writer. -p is an"],[At," optional standing instruction prepended to every chunk;"],[At," if stdin already contains the question, -p is not needed."],[At," By default, agent markdown is post-processed: ANSI-styled"],[At," on a TTY, stripped to plain text on a pipe, tables laid"],[At," out in both modes. Tool calls / thoughts split paragraphs"],[At," but otherwise stay hidden. --raw bypasses the renderer"],[At," and emits chunks immediately, the way cat used to behave."],[At," With --session, attach to an existing session instead"],[At," of creating a new one. With --detach, the session"],[At," survives in the daemon for slack/browser/notifier"],[At," extensions."],[xl," hydra-acp launch <agent> [agent-args...]"],[xl," Shim mode, force daemon to spawn <agent>"],[xl," from the registry. Args after <agent>"],[xl," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[DE," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Al," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Al," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Al," hydra-acp daemon stop|restart"],[Al," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[HE," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ht," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ht," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ht," --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."],[ht," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ht," --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."],[ht," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ht," 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)."],[ht," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ht," 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."],[ht," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ht," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ht," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ht," 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."],[ht," hydra-acp session export <id> [--out <file>|.]"],[ht," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ht," 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"],[ht," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ht," 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"],[ht," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ht," 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)."],[Ga," hydra-acp extension list List configured extensions and live state"],[Ga," hydra-acp extension add <name> [opts] Add an extension to config"],[Ga," hydra-acp extension remove <name> Remove an extension from config"],[Ga," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[Ga," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Xa," hydra-acp transformer list List configured transformers and live state"],[Xa," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Xa," hydra-acp transformer remove <name> Remove a transformer from config"],[Xa," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Xa," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Hn," hydra-acp agent [list] List agents in the cached registry"],[Hn," hydra-acp agent refresh Force a registry re-fetch"],[Hn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Hn," 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>])."],[Hn," 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."],[Hn," 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)."],[Hn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Hn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[UE," 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."],[Hn," 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`"],[Hn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Hn," hydra-acp agent auth <id> Run the auth flow for <id>"],[Za," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Za," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Za," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."],[Za," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Za," hydra-acp config path Print the config file path"],[Bp," hydra-acp auth password [--force] Set the daemon's master password"],[Bp," hydra-acp auth [list] List active session tokens"],[Bp," hydra-acp auth revoke <id> Revoke a session token"],[Lp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Lp," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],n=[];for(let s of e){if(typeof s=="string"){n.push(s);continue}if("globalOnly"in s){t===void 0&&n.push(s.globalOnly);continue}let[r,i]=s;(t===void 0||r.includes(t))&&n.push(i)}process.stdout.write(n.join(`
524
+ `),Dp(),process.exit(2))}function Op(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 qv(t,e){try{return await yh(t,e)}catch(n){oe({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
525
+ `),process.exit(1)}}function zE(){try{let t=jE(UE(import.meta.url));return JSON.parse(HE(qE(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Lp=["tui"],Wv=["shim","acp"],At=["cat"],Al=["launch"],KE=["init"],Cl=["daemon"],JE=["version"],ht=["session","sessions"],Ga=["extension","extensions"],Xa=["transformer","transformers"],Hn=["agent","agents"],YE=["registry"],Za=["config"],Bp=["auth"];function Dp(t){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[Lp," hydra-acp tui [same flags] Force TUI explicitly."],[Wv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Wv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[At," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[At," Pipe-friendly headless mode. Reads stdin and sends it"],[At," as a prompt to a fresh session, streams the agent's"],[At," response to stdout, exits when stdin closes. A bounded"],[At,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[At," as one turn; a streaming input (e.g. `tail -f`) is"],[At," chunked by the natural pauses in the writer. -p is an"],[At," optional standing instruction prepended to every chunk;"],[At," if stdin already contains the question, -p is not needed."],[At," By default, agent markdown is post-processed: ANSI-styled"],[At," on a TTY, stripped to plain text on a pipe, tables laid"],[At," out in both modes. Tool calls / thoughts split paragraphs"],[At," but otherwise stay hidden. --raw bypasses the renderer"],[At," and emits chunks immediately, the way cat used to behave."],[At," With --session, attach to an existing session instead"],[At," of creating a new one. With --detach, the session"],[At," survives in the daemon for slack/browser/notifier"],[At," extensions."],[Al," hydra-acp launch <agent> [agent-args...]"],[Al," Shim mode, force daemon to spawn <agent>"],[Al," from the registry. Args after <agent>"],[Al," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[KE," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Cl," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Cl," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Cl," hydra-acp daemon stop|restart"],[Cl," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[JE," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ht," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ht," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ht," --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."],[ht," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ht," --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."],[ht," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ht," 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)."],[ht," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ht," 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."],[ht," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ht," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ht," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ht," 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."],[ht," hydra-acp session export <id> [--out <file>|.]"],[ht," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ht," 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"],[ht," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ht," 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"],[ht," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ht," 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)."],[Ga," hydra-acp extension list List configured extensions and live state"],[Ga," hydra-acp extension add <name> [opts] Add an extension to config"],[Ga," hydra-acp extension remove <name> Remove an extension from config"],[Ga," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[Ga," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Xa," hydra-acp transformer list List configured transformers and live state"],[Xa," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Xa," hydra-acp transformer remove <name> Remove a transformer from config"],[Xa," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Xa," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Hn," hydra-acp agent [list] List agents in the cached registry"],[Hn," hydra-acp agent refresh Force a registry re-fetch"],[Hn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Hn," 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>])."],[Hn," 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."],[Hn," 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)."],[Hn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Hn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[YE," 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."],[Hn," 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`"],[Hn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Hn," hydra-acp agent auth <id> Run the auth flow for <id>"],[Za," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Za," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Za," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."],[Za," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Za," hydra-acp config path Print the config file path"],[Bp," hydra-acp auth password [--force] Set the daemon's master password"],[Bp," hydra-acp auth [list] List active session tokens"],[Bp," hydra-acp auth revoke <id> Revoke a session token"],[Lp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Lp," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],n=[];for(let s of e){if(typeof s=="string"){n.push(s);continue}if("globalOnly"in s){t===void 0&&n.push(s.globalOnly);continue}let[r,i]=s;(t===void 0||r.includes(t))&&n.push(i)}process.stdout.write(n.join(`
526
526
  `)+`
527
- `)}async function Wv(){if(!vr)try{let t=await Na();t&&process.stderr.write(`\u2728 ${Da(t)}
528
- `)}catch{}}BE().then(Wv).catch(async t=>{oe({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
529
- `),await Wv(),process.exit(1)});
527
+ `)}async function zv(){if(!vr)try{let t=await Na();t&&process.stderr.write(`\u2728 ${Da(t)}
528
+ `)}catch{}}WE().then(zv).catch(async t=>{oe({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
529
+ `),await zv(),process.exit(1)});