@hydra-acp/cli 0.1.102 → 0.1.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +154 -154
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,34 +1,34 @@
1
1
  #!/usr/bin/env node
2
- var vv=Object.defineProperty;var K=(t,e)=>()=>(t&&(e=t(t=0)),e);var ul=(t,e)=>{for(var n in e)vv(t,n,{get:e[n],enumerable:!0})};import*as be from"path";import*as pl from"os";function st(t){let e=pl.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function Cv(){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 Ae(){let t=process.env[Av];if(t&&t.length>0)return be.resolve(t);let e=Cv();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 be.join(pl.homedir(),".hydra-acp")}var Av,$,ye=K(()=>{"use strict";Av="HYDRA_ACP_HOME";$={home:Ae,config:()=>be.join(Ae(),"config.json"),authToken:()=>be.join(Ae(),"auth-token"),remotes:()=>be.join(Ae(),"remotes.json"),pidFile:()=>be.join(Ae(),"daemon.pid"),logFile:()=>be.join(Ae(),"daemon.log"),currentLogFile:()=>be.join(Ae(),"current.log"),registryCache:()=>be.join(Ae(),"registry.json"),agentsDir:()=>be.join(Ae(),"agents"),agentLogFile:t=>be.join(Ae(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>be.join(Ae(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>be.join(Ae(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>be.join(Ae(),"sessions"),sessionDir:t=>be.join(Ae(),"sessions",t),sessionFile:t=>be.join(Ae(),"sessions",t,"meta.json"),historyFile:t=>be.join(Ae(),"sessions",t,"history.jsonl"),toolsDir:t=>be.join(Ae(),"sessions",t,"tools"),toolBlobFile:(t,e)=>be.join(Ae(),"sessions",t,"tools",e),queueFile:t=>be.join(Ae(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>be.join(Ae(),"sessions",".tombstones"),tombstoneAgentDir:t=>be.join(Ae(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>be.join(Ae(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>be.join(Ae(),"extensions"),extensionLogDir:t=>be.join(Ae(),"extensions",t),extensionLogFile:t=>be.join(Ae(),"extensions",t,"current.log"),extensionPidFile:t=>be.join(Ae(),"extensions",t,"extension.pid"),transformersDir:()=>be.join(Ae(),"transformers"),transformerLogDir:t=>be.join(Ae(),"transformers",t),transformerLogFile:t=>be.join(Ae(),"transformers",t,"current.log"),transformerPidFile:t=>be.join(Ae(),"transformers",t,"transformer.pid"),transformerState:(t,e)=>be.join(Ae(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>be.join(Ae(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>be.join(Ae(),"prompt-history"),tuiLogFile:()=>be.join(Ae(),"tui.log"),shimWireLogFile:()=>be.join(Ae(),"shim-wire.log")}});import*as hi from"fs/promises";function mi(){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 gi(){try{let e=(await hi.readFile($.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function kr(){let t=await gi();if(!t)throw new Error(`No service token found at ${$.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function yi(t){await hi.mkdir($.home(),{recursive:!0}),await hi.writeFile($.authToken(),t+`
2
+ var Sv=Object.defineProperty;var K=(t,e)=>()=>(t&&(e=t(t=0)),e);var ul=(t,e)=>{for(var n in e)Sv(t,n,{get:e[n],enumerable:!0})};import*as be from"path";import*as pl from"os";function st(t){let e=pl.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function Rv(){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 Ae(){let t=process.env[Cv];if(t&&t.length>0)return be.resolve(t);let e=Rv();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 be.join(pl.homedir(),".hydra-acp")}var Cv,$,ye=K(()=>{"use strict";Cv="HYDRA_ACP_HOME";$={home:Ae,config:()=>be.join(Ae(),"config.json"),authToken:()=>be.join(Ae(),"auth-token"),remotes:()=>be.join(Ae(),"remotes.json"),pidFile:()=>be.join(Ae(),"daemon.pid"),logFile:()=>be.join(Ae(),"daemon.log"),currentLogFile:()=>be.join(Ae(),"current.log"),registryCache:()=>be.join(Ae(),"registry.json"),agentsDir:()=>be.join(Ae(),"agents"),agentLogFile:t=>be.join(Ae(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>be.join(Ae(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>be.join(Ae(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>be.join(Ae(),"sessions"),sessionDir:t=>be.join(Ae(),"sessions",t),sessionFile:t=>be.join(Ae(),"sessions",t,"meta.json"),historyFile:t=>be.join(Ae(),"sessions",t,"history.jsonl"),toolsDir:t=>be.join(Ae(),"sessions",t,"tools"),toolBlobFile:(t,e)=>be.join(Ae(),"sessions",t,"tools",e),queueFile:t=>be.join(Ae(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>be.join(Ae(),"sessions",".tombstones"),tombstoneAgentDir:t=>be.join(Ae(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>be.join(Ae(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>be.join(Ae(),"extensions"),extensionLogDir:t=>be.join(Ae(),"extensions",t),extensionLogFile:t=>be.join(Ae(),"extensions",t,"current.log"),extensionPidFile:t=>be.join(Ae(),"extensions",t,"extension.pid"),transformersDir:()=>be.join(Ae(),"transformers"),transformerLogDir:t=>be.join(Ae(),"transformers",t),transformerLogFile:t=>be.join(Ae(),"transformers",t,"current.log"),transformerPidFile:t=>be.join(Ae(),"transformers",t,"transformer.pid"),transformerState:(t,e)=>be.join(Ae(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>be.join(Ae(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>be.join(Ae(),"prompt-history"),tuiLogFile:()=>be.join(Ae(),"tui.log"),shimWireLogFile:()=>be.join(Ae(),"shim-wire.log")}});import*as hi from"fs/promises";function mi(){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 gi(){try{let e=(await hi.readFile($.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function kr(){let t=await gi();if(!t)throw new Error(`No service token found at ${$.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function yi(t){await hi.mkdir($.home(),{recursive:!0}),await hi.writeFile($.authToken(),t+`
3
3
  `,{encoding:"utf8",mode:384})}async function Fo(){let t=await gi();if(t)return t;let e=mi();return await yi(e),process.stderr.write(`hydra-acp: initialized ${$.authToken()} with a fresh service token.
4
- `),e}var ms=K(()=>{"use strict";ye()});import*as Ft from"fs/promises";import*as kp from"fs";import*as In from"path";import{randomBytes as Rv}from"crypto";async function Zt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await Tv(t,r,n)}async function Tv(t,e,n={}){let s=await Ev(t),r=Pv(s);await Ft.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Mv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await Ft.writeFile(i,e,o),await Ft.rename(i,s)}catch(o){throw await Ft.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{kp.chmodSync(s,n.mode)}catch{}}async function Ev(t){let e;try{e=await Ft.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await Ft.readlink(t),s=In.isAbsolute(n)?n:In.resolve(In.dirname(t),n);try{let r=await Ft.realpath(In.dirname(s));return In.join(r,In.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function hn(t){let e;try{e=await Ft.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 Pv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Mv(){return Rv(4).toString("hex")}var Ir=K(()=>{"use strict"});import*as Ds from"fs/promises";import{homedir as hl}from"os";import{z as j}from"zod";function Ap(t){return t.tui.inAppSelection??t.tui.mouse}function Cp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Rp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ya(){return await Hv(),await hn($.config())??{}}async function Hv(){let t;try{t=await Ds.lstat($.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Ds.stat($.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Ds.readlink($.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${$.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 Va(){let t=await Ya(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Ds.access($.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${$.authToken()} and ${$.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await yi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Zt($.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${$.config()} to ${$.authToken()}.
6
- `)}async function Ie(){return await Va(),ml.parse(await Ya())}async function gs(t){await Va();let e=await Ya();t(e),ml.parse(e),await Zt($.config(),e,{mode:384})}async function Oo(t,e){await gs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Qa(t){await gs(e=>{e.defaultAgent=t})}async function Tp(t,e){await gs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Ep(t,e){await gs(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 gl(t,e){await gs(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 Pp(t){await gs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Mp(){let t=await Ya();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function rt(t){return t==="~"||t==="$HOME"?hl():t.startsWith("~/")?hl()+t.slice(1):t.startsWith("$HOME/")?hl()+t.slice(5):t}var xp,_v,xn,$v,Fv,Ov,Lv,Bv,Ip,Nv,Dv,ml,tt=K(()=>{"use strict";ye();ms();Ir();xp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",_v=j.object({cert:j.string(),key:j.string()}),xn=55514,$v=j.object({host:j.string().default("127.0.0.1"),port:j.number().int().positive().default(xn),logLevel:j.enum(["debug","info","warn","error"]).default("info"),tls:_v.optional(),sessionIdleTimeoutSeconds:j.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:j.number().int().positive().default(1e4),agentStderrTailBytes:j.number().int().positive().default(4096),publicHost:j.string().optional(),agentSyncIntervalMinutes:j.number().nonnegative().default(60),sessionGcIntervalMinutes:j.number().nonnegative().default(60),sessionGcMaxAgeDays:j.number().positive().default(2)}),Fv=j.object({url:j.string().url().default(xp),ttlHours:j.number().positive().default(24),pinned:j.boolean().default(!1)}),Ov=j.object({name:j.string().optional(),description:j.string().optional(),command:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Lv=j.object({packageSpec:j.string().optional()}),Bv=j.object({repaintThrottleMs:j.number().int().nonnegative().default(1e3),maxScrollbackLines:j.number().int().positive().default(1e4),mouse:j.boolean().default(!0),inAppSelection:j.boolean().optional(),selectionClipboard:j.enum(["primary","clipboard","both"]).default("both"),openFileCommand:j.union([j.string(),j.array(j.string())]).optional(),logMaxBytes:j.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:j.number().int().positive().default(32),progressIndicator:j.boolean().default(!0),defaultEnterAction:j.enum(["enqueue","amend"]).default("amend"),showThoughts:j.boolean().default(!0),ambiguousWidth:j.enum(["auto","narrow","wide"]).default("auto"),toolContent:j.enum(["inline","references"]).default("references"),diffContextLines:j.number().int().min(0).default(3),promptHistoryMaxEntries:j.number().int().positive().default(2e3),maxToolItems:j.number().int().nonnegative().default(5),maxPlanItems:j.number().int().nonnegative().default(5),showFileUpdates:j.enum(["none","edit","diff"]).default("edit"),sessionColumns:j.array(j.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Ip=j.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Nv=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),Dv=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),ml=j.object({daemon:$v.default({}),registry:Fv.default({url:xp,ttlHours:24,pinned:!1}),agents:j.record(j.string(),Ov).default({}),agentOverrides:j.record(j.string(),Lv).default({}),defaultAgent:j.string().default("opencode"),defaultModels:j.record(j.string(),j.string()).default({}),synopsisAgent:j.string().optional(),synopsisModel:j.string().optional(),compaction:j.object({agent:j.string().optional(),model:j.string().optional(),tailK:j.number().int().nonnegative().default(20),maxIterations:j.number().int().positive().default(3),contextFraction:j.number().min(0).max(1).default(.5),hardCeilingFraction:j.number().min(0).max(1).default(.85),absoluteFallback:j.number().int().positive().default(12e4),idleBeforePromptMs:j.number().int().nonnegative().default(3e5),modelContextWindows:j.record(j.string(),j.number().int().positive()).default({})}).default({}),defaultCwd:j.string().default("~"),compressToolContent:j.boolean().default(!0),sessionListColdLimit:j.number().int().nonnegative().default(20),extensions:j.record(Ip,Nv).default({}),transformers:j.record(Ip,Dv).default({}),defaultTransformers:j.array(j.string()).default([]),npmRegistry:j.string().url().optional(),tui:Bv.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 xr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function yl(t){return{httpScheme:"https",wsScheme:"wss"}}function wl(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 ${Ga(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Ga(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=Uv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Ga(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Ga(t)}`);let i=xr(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=xn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function _p(t){let e=t.port!==void 0&&t.port!==xn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Uv(t){try{return new URL(t)}catch{return null}}function Ga(t){return t.length>80?`${t.slice(0,77)}...`:t}var Lo=K(()=>{"use strict";tt()});function Ar(t,e){return`${t}:${e}`}function $p(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function jv(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 qv(){let t=await hn($.remotes());return t===void 0?{version:1,entries:{}}:Wv(t)}function Wv(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 bl(t){await Zt($.remotes(),t,{mode:384})}var Xa,vl=K(()=>{"use strict";ye();Ir();Xa=class t{data;constructor(e){this.data=e}static async load(){let e=await qv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if($p(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await bl(i),new t(i)}get(e,n){let s=this.data.entries[Ar(e,n)];if(s&&!$p(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ar(e,n)]=s,await bl(this.data)}async delete(e,n){let s=Ar(e,n);return s in this.data.entries?(delete this.data.entries[s],await bl(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=jv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function wi(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)}):zv()}function zv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
4
+ `),e}var ms=K(()=>{"use strict";ye()});import*as Ft from"fs/promises";import*as kp from"fs";import*as In from"path";import{randomBytes as Tv}from"crypto";async function en(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await Ev(t,r,n)}async function Ev(t,e,n={}){let s=await Pv(t),r=Mv(s);await Ft.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${_v()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await Ft.writeFile(i,e,o),await Ft.rename(i,s)}catch(o){throw await Ft.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{kp.chmodSync(s,n.mode)}catch{}}async function Pv(t){let e;try{e=await Ft.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await Ft.readlink(t),s=In.isAbsolute(n)?n:In.resolve(In.dirname(t),n);try{let r=await Ft.realpath(In.dirname(s));return In.join(r,In.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function mn(t){let e;try{e=await Ft.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 Mv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function _v(){return Tv(4).toString("hex")}var Ir=K(()=>{"use strict"});import*as Ds from"fs/promises";import{homedir as hl}from"os";import{z as j}from"zod";function Ap(t){return t.tui.inAppSelection??t.tui.mouse}function Cp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Rp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ya(){return await Uv(),await mn($.config())??{}}async function Uv(){let t;try{t=await Ds.lstat($.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Ds.stat($.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Ds.readlink($.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${$.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 Va(){let t=await Ya(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Ds.access($.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${$.authToken()} and ${$.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await yi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await en($.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${$.config()} to ${$.authToken()}.
6
+ `)}async function Ie(){return await Va(),ml.parse(await Ya())}async function gs(t){await Va();let e=await Ya();t(e),ml.parse(e),await en($.config(),e,{mode:384})}async function Oo(t,e){await gs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Qa(t){await gs(e=>{e.defaultAgent=t})}async function Tp(t,e){await gs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Ep(t,e){await gs(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 gl(t,e){await gs(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 Pp(t){await gs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Mp(){let t=await Ya();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function rt(t){return t==="~"||t==="$HOME"?hl():t.startsWith("~/")?hl()+t.slice(1):t.startsWith("$HOME/")?hl()+t.slice(5):t}var xp,$v,xn,Fv,Ov,Lv,Bv,Nv,Ip,Dv,Hv,ml,tt=K(()=>{"use strict";ye();ms();Ir();xp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",$v=j.object({cert:j.string(),key:j.string()}),xn=55514,Fv=j.object({host:j.string().default("127.0.0.1"),port:j.number().int().positive().default(xn),logLevel:j.enum(["debug","info","warn","error"]).default("info"),tls:$v.optional(),sessionIdleTimeoutSeconds:j.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:j.number().int().positive().default(1e4),agentStderrTailBytes:j.number().int().positive().default(4096),publicHost:j.string().optional(),agentSyncIntervalMinutes:j.number().nonnegative().default(60),sessionGcIntervalMinutes:j.number().nonnegative().default(60),sessionGcMaxAgeDays:j.number().positive().default(2)}),Ov=j.object({url:j.string().url().default(xp),ttlHours:j.number().positive().default(24),pinned:j.boolean().default(!1)}),Lv=j.object({name:j.string().optional(),description:j.string().optional(),command:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),Bv=j.object({packageSpec:j.string().optional()}),Nv=j.object({repaintThrottleMs:j.number().int().nonnegative().default(1e3),maxScrollbackLines:j.number().int().positive().default(1e4),mouse:j.boolean().default(!0),inAppSelection:j.boolean().optional(),selectionClipboard:j.enum(["primary","clipboard","both"]).default("both"),openFileCommand:j.union([j.string(),j.array(j.string())]).optional(),logMaxBytes:j.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:j.number().int().positive().default(32),progressIndicator:j.boolean().default(!0),defaultEnterAction:j.enum(["enqueue","amend"]).default("amend"),showThoughts:j.boolean().default(!0),ambiguousWidth:j.enum(["auto","narrow","wide"]).default("auto"),toolContent:j.enum(["inline","references"]).default("references"),diffContextLines:j.number().int().min(0).default(3),promptHistoryMaxEntries:j.number().int().positive().default(2e3),maxToolItems:j.number().int().nonnegative().default(5),maxPlanItems:j.number().int().nonnegative().default(5),showFileUpdates:j.enum(["none","edit","diff"]).default("edit"),sessionColumns:j.array(j.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Ip=j.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Dv=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),Hv=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),ml=j.object({daemon:Fv.default({}),registry:Ov.default({url:xp,ttlHours:24,pinned:!1}),agents:j.record(j.string(),Lv).default({}),agentOverrides:j.record(j.string(),Bv).default({}),defaultAgent:j.string().default("opencode"),defaultModels:j.record(j.string(),j.string()).default({}),synopsisAgent:j.string().optional(),synopsisModel:j.string().optional(),compaction:j.object({agent:j.string().optional(),model:j.string().optional(),tailK:j.number().int().nonnegative().default(20),maxIterations:j.number().int().positive().default(3),contextFraction:j.number().min(0).max(1).default(.5),hardCeilingFraction:j.number().min(0).max(1).default(.85),absoluteFallback:j.number().int().positive().default(12e4),idleBeforePromptMs:j.number().int().nonnegative().default(3e5),modelContextWindows:j.record(j.string(),j.number().int().positive()).default({})}).default({}),defaultCwd:j.string().default("~"),compressToolContent:j.boolean().default(!0),sessionListColdLimit:j.number().int().nonnegative().default(20),extensions:j.record(Ip,Dv).default({}),transformers:j.record(Ip,Hv).default({}),defaultTransformers:j.array(j.string()).default([]),npmRegistry:j.string().url().optional(),tui:Nv.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 xr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function yl(t){return{httpScheme:"https",wsScheme:"wss"}}function wl(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 ${Ga(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Ga(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=jv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Ga(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Ga(t)}`);let i=xr(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=xn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function _p(t){let e=t.port!==void 0&&t.port!==xn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function jv(t){try{return new URL(t)}catch{return null}}function Ga(t){return t.length>80?`${t.slice(0,77)}...`:t}var Lo=K(()=>{"use strict";tt()});function Ar(t,e){return`${t}:${e}`}function $p(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function qv(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 Wv(){let t=await mn($.remotes());return t===void 0?{version:1,entries:{}}:zv(t)}function zv(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 bl(t){await en($.remotes(),t,{mode:384})}var Xa,vl=K(()=>{"use strict";ye();Ir();Xa=class t{data;constructor(e){this.data=e}static async load(){let e=await Wv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if($p(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await bl(i),new t(i)}get(e,n){let s=this.data.entries[Ar(e,n)];if(s&&!$p(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ar(e,n)]=s,await bl(this.data)}async delete(e,n){let s=Ar(e,n);return s in this.data.entries?(delete this.data.entries[s],await bl(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=qv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function wi(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)}):Kv()}function Kv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
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 Sl=K(()=>{"use strict"});import*as Fp from"path";function Dn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=Fp.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Bo=K(()=>{"use strict"});import*as Za from"fs/promises";async function ys(){try{let t=await Za.readFile($.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 Op(t){await Za.writeFile($.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function An(t){try{return process.kill(t,0),!0}catch{return!1}}var bi=K(()=>{"use strict";ye()});var Up={};ul(Up,{_resetForTests:()=>eS,clearPin:()=>Xv,fetchPeerFingerprint:()=>Al,formatFingerprint:()=>ed,getPin:()=>Il,installGlobalTlsTrust:()=>Rl,loadPinsFromStore:()=>xl,setPin:()=>No,sha256Hex:()=>Cl,wsTlsOptions:()=>Do});import{createHash as Kv}from"crypto";import*as Lp from"tls";import{Agent as Jv,Dispatcher as Yv,buildConnector as Vv,getGlobalDispatcher as Qv,setGlobalDispatcher as Gv}from"undici";function No(t,e,n){Cr.set(Ar(t,e),Bp(n))}function Xv(t,e){Cr.delete(Ar(t,e))}function Il(t,e){return Cr.get(Ar(t,e))}function xl(t){Cr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&No(e.host,e.port,e.entry.pinnedFingerprint)}async function Al(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Lp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},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,Cl(l.raw))}),o.once("error",l=>c(l))})}function Cl(t){return Kv("sha256").update(t).digest("hex")}function ed(t){let e=Bp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Bp(t){return t.replace(/:/g,"").toLowerCase()}function Rl(){if(kl)return;kl=!0;let t=Qv(),e=new Jv({connect:Vv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Dp(s,r)})}),n=new Yv;n.dispatch=(s,r)=>{let i=Zv(s.origin);return(i&&Np(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(()=>{})),Gv(n)}function Zv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Np(t){for(let e of Cr.keys())if(Hp(e)?.host===t)return!0;return!1}function Dp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=Cl(e.raw);for(let[s,r]of Cr.entries()){let i=Hp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${ed(n)})`)}function Hp(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 Do(t){return Np(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Dp(e,n)}:{autoSelectFamily:!0}}function eS(){Cr.clear(),kl=!1}var Cr,kl,Ho=K(()=>{"use strict";vl();Cr=new Map,kl=!1});import*as zp from"os";async function Ut(t){let e=await Fo(),n=await ys();if(n&&An(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:xr(r)}}function jp(t,e){let{httpScheme:n,wsScheme:s}=yl(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Jp(t),isLocal:t.isLoopback}}async function Kp(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??wi,r=e.confirmImpl??rS,i=e.tlsHandshakeImpl??tS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await gi();if(b)return sS(t,b)}let c=e.store??await Xa.load();xl(c),Rl();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&No(t.host,t.port,d.pinnedFingerprint),jp(t,d.token);if(!a)throw new Tl(t.host,t.port);let l=Jp(t),{httpScheme:u}=yl(t.host),f;if(u==="https"&&Il(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
9
+ `,{encoding:"utf8",mode:384})}function An(t){try{return process.kill(t,0),!0}catch{return!1}}var bi=K(()=>{"use strict";ye()});var Up={};ul(Up,{_resetForTests:()=>tS,clearPin:()=>Zv,fetchPeerFingerprint:()=>Al,formatFingerprint:()=>ed,getPin:()=>Il,installGlobalTlsTrust:()=>Rl,loadPinsFromStore:()=>xl,setPin:()=>No,sha256Hex:()=>Cl,wsTlsOptions:()=>Do});import{createHash as Jv}from"crypto";import*as Lp from"tls";import{Agent as Yv,Dispatcher as Vv,buildConnector as Qv,getGlobalDispatcher as Gv,setGlobalDispatcher as Xv}from"undici";function No(t,e,n){Cr.set(Ar(t,e),Bp(n))}function Zv(t,e){Cr.delete(Ar(t,e))}function Il(t,e){return Cr.get(Ar(t,e))}function xl(t){Cr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&No(e.host,e.port,e.entry.pinnedFingerprint)}async function Al(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Lp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},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,Cl(l.raw))}),o.once("error",l=>c(l))})}function Cl(t){return Jv("sha256").update(t).digest("hex")}function ed(t){let e=Bp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Bp(t){return t.replace(/:/g,"").toLowerCase()}function Rl(){if(kl)return;kl=!0;let t=Gv(),e=new Yv({connect:Qv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Dp(s,r)})}),n=new Vv;n.dispatch=(s,r)=>{let i=eS(s.origin);return(i&&Np(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(()=>{})),Xv(n)}function eS(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Np(t){for(let e of Cr.keys())if(Hp(e)?.host===t)return!0;return!1}function Dp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=Cl(e.raw);for(let[s,r]of Cr.entries()){let i=Hp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${ed(n)})`)}function Hp(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 Do(t){return Np(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Dp(e,n)}:{autoSelectFamily:!0}}function tS(){Cr.clear(),kl=!1}var Cr,kl,Ho=K(()=>{"use strict";vl();Cr=new Map,kl=!1});import*as zp from"os";async function Ut(t){let e=await Fo(),n=await ys();if(n&&An(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:xr(r)}}function jp(t,e){let{httpScheme:n,wsScheme:s}=yl(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Jp(t),isLocal:t.isLoopback}}async function Kp(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??wi,r=e.confirmImpl??iS,i=e.tlsHandshakeImpl??nS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await gi();if(b)return rS(t,b)}let c=e.store??await Xa.load();xl(c),Rl();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&No(t.host,t.port,d.pinnedFingerprint),jp(t,d.token);if(!a)throw new Tl(t.host,t.port);let l=Jp(t),{httpScheme:u}=yl(t.host),f;if(u==="https"&&Il(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
10
  subject: ${b.subject??"(unknown)"}
11
11
  issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
12
  sha256: ${ed(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);No(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.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=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Wp()})});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:Wp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),jp(t,y.session_token)}async function tS(t,e){let n=await nS(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Al(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function nS(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?qp(p.subject):void 0,issuer:p?.issuer?qp(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function qp(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 sS(t,e){let n=await ys(),r=n&&An(n.pid)?n.loopbackPort:t.port,i=t.port===xn?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 rS(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 Wp(){try{let t=zp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Jp(t){return t.port===xn?t.host:`${t.host}:${t.port}`}var Tl,Rr=K(()=>{"use strict";tt();ms();Lo();vl();Sl();Bo();bi();Ho();Lo();Tl=class extends Error{host;port;constructor(e,n){let s=n===xn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Dn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as iS,renameSync as oS,statSync as aS}from"fs";function Qp(t){Vp=t}function ne(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?$.tuiLogFile():e;if(n.length!==0)try{dS(n);let s=JSON.stringify({t:new Date().toISOString(),...t});iS(n,`${s}
15
- `)}catch{}}function dS(t){try{if(aS(t).size<Vp)return;oS(t,`${t}.0`)}catch{}}var Vp,Tr=K(()=>{"use strict";ye();Vp=5*1024*1024});var W,od=K(()=>{"use strict";W={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 Fe}from"zod";var bh,OS,vh,Sh,kh,Ul=K(()=>{"use strict";bh=Fe.object({protocolVersion:Fe.number().optional(),clientCapabilities:Fe.record(Fe.unknown()).optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional()}),OS=Fe.enum(["full","pending_only","none","after_message"]),vh=Fe.object({cwd:Fe.string(),mcpServers:Fe.array(Fe.unknown()).optional(),_meta:Fe.record(Fe.unknown()).optional()}),Sh=Fe.object({upstreamSessionId:Fe.string(),agentId:Fe.string(),cwd:Fe.string(),title:Fe.string().optional(),agentArgs:Fe.array(Fe.string()).optional()}),kh=Fe.object({sessionId:Fe.string(),historyPolicy:OS.default("full"),afterMessageId:Fe.string().optional(),clientId:Fe.string().optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional(),_meta:Fe.record(Fe.unknown()).optional()})});import{z as de}from"zod";function ad(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 Ah(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Uo(t._meta,ad(t))};return t.title!==void 0&&(e.title=t.title),e}var Ih,xh,jl,aP,LS,dP,ql=K(()=>{"use strict";dd();Ih=de.object({sessionId:de.string()}),xh=de.object({cwd:de.string().optional(),cursor:de.string().optional()}),jl=de.object({used:de.number().optional(),size:de.number().optional(),costAmount:de.number().optional(),costCurrency:de.string().optional()}),aP=de.object({sessionId:de.string(),upstreamSessionId:de.string().optional(),cwd:de.string(),title:de.string().optional(),agentId:de.string().optional(),currentModel:de.string().optional(),currentUsage:jl.optional(),importedFromMachine:de.string().optional(),importedFromUpstreamSessionId:de.string().optional(),parentSessionId:de.string().optional(),forkedFromSessionId:de.string().optional(),forkedFromMessageId:de.string().optional(),originatingClient:de.object({name:de.string(),version:de.string().optional()}).optional(),interactive:de.boolean().optional(),priority:de.number().int().nonnegative().optional(),updatedAt:de.string(),attachedClients:de.number().int().nonnegative(),status:de.enum(["warm","cold"]).default("warm"),busy:de.boolean().default(!1),awaitingInput:de.boolean().default(!1),compactionState:de.any().optional(),forkSynthesisState:de.enum(["running","failed"]).optional(),_meta:de.record(de.unknown()).optional()}),LS=de.object({sessionId:de.string(),cwd:de.string(),title:de.string().optional(),updatedAt:de.string().optional(),_meta:de.record(de.unknown()).optional()}),dP=de.object({sessions:de.array(LS),nextCursor:de.string().optional()})});function BS(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 tn(t){if(!t)return{};let e=t[Lt];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=Sh.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=jl.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=BS(n.env);r!==void 0&&(s.env=r)}return s}function Uo(t,e){return{...t??{},[Lt]:e}}var Lt,dd=K(()=>{"use strict";Ul();ql();Lt="hydra-acp"});import{z as Z}from"zod";var Ch,cd,Rh,hP,mP,gP,Th,yP,Eh,wP,Ph,bP,vP,Mh=K(()=>{"use strict";Ch=Z.object({sessionId:Z.string(),prompt:Z.array(Z.unknown()),_meta:Z.record(Z.unknown()).optional()}),cd=Z.object({sessionId:Z.string()}),Rh=Z.object({clientId:Z.string(),name:Z.string().optional(),version:Z.string().optional()}),hP=Z.object({sessionId:Z.string(),messageId:Z.string(),originator:Rh,prompt:Z.array(Z.unknown()),position:Z.number().int().nonnegative(),queueDepth:Z.number().int().positive(),enqueuedAt:Z.number()}),mP=Z.object({sessionId:Z.string(),messageId:Z.string(),prompt:Z.array(Z.unknown())}),gP=Z.object({sessionId:Z.string(),messageId:Z.string(),reason:Z.enum(["started","cancelled","abandoned"])}),Th=Z.object({sessionId:Z.string(),messageId:Z.string()}),yP=Z.object({cancelled:Z.boolean(),reason:Z.enum(["ok","not_found","already_running"])}),Eh=Z.object({sessionId:Z.string(),messageId:Z.string(),prompt:Z.array(Z.unknown())}),wP=Z.object({updated:Z.boolean(),reason:Z.enum(["ok","not_found","already_running"])}),Ph=Z.object({sessionId:Z.string(),targetMessageId:Z.string(),prompt:Z.array(Z.unknown()),replaceQueue:Z.boolean().optional(),onTargetCompleted:Z.enum(["reject","send_anyway"]).optional()}),bP=Z.object({amended:Z.boolean(),reason:Z.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:Z.string().optional()}),vP=Z.object({sessionId:Z.string(),cancelledMessageId:Z.string(),newMessageId:Z.string(),prompt:Z.array(Z.unknown()),originator:Rh,amendedAt:Z.number()})});import{z as Us}from"zod";var _h,ld,xi,$h=K(()=>{"use strict";_h=Us.object({agentId:Us.string(),version:Us.string(),source:Us.enum(["binary","npm"]),phase:Us.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Us.number().optional(),totalBytes:Us.number().optional(),packageSpec:Us.string().optional()}),ld="hydra-acp/agents/install_progress",xi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Bt=K(()=>{"use strict";od();Ul();dd();ql();Mh();$h()});import{nanoid as NS}from"nanoid";var Wl,Kt,Pr=K(()=>{"use strict";Bt();Wl=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 Wl;let s=NS(),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:W.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??W.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 Ai(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 Ci(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 zl=K(()=>{"use strict"});import*as Lh from"fs/promises";function QS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var qS,WS,Ri,zS,KS,JS,YS,VS,Oh,pd,Bh=K(()=>{"use strict";qS=64*1024*1024,WS=1*1024*1024,Ri=64*1024,zS=6e4,KS=100,JS=1e3,YS=64*1024,VS=256*1024,Oh=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??qS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(WS,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,Ri));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let 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,Ri)),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,Ri)),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,zS));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(QS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??KS,JS)),f=Math.max(1,Math.min(e.maxBytes??YS,VS)),p=Math.max(0,Math.min(e.contextBefore??0,Oh)),h=Math.max(0,Math.min(e.contextAfter??0,Oh)),m=[],y=[],b=[],v=0,S=!1,x=0,T=0,F=(J,q)=>{for(let ee of b)ee.remaining>0&&(ee.match.after===void 0&&(ee.match.after=[]),ee.match.after.push({cursor:J,line:q}),ee.remaining--,v+=q.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(q)!==l&&m.length<u){let ee={cursor:J,line:q};if(p>0&&y.length>0){ee.before=y.slice();for(let ae of ee.before)v+=ae.line.length}v+=q.length,m.push(ee),h>0&&b.push({match:ee,remaining:h})}if(p>0)for(y.push({cursor:J,line:q});y.length>p;)y.shift();let D=m.length>=u&&b.length===0,X=v>=f;return D||X};for(let J=0;J<o.length;J++){if(o[J]!==10)continue;let q=o.subarray(x,J).toString("utf8"),L=r+x;if(x=J+1,T=x,F(L,q)){S=!0;break}}if(!S&&x<o.length&&this.closed){let J=o.subarray(x).toString("utf8"),q=r+x;F(q,J)&&(S=!0),T=o.length}let _=Math.min(r+T,this.writeCursor),N={matches:m,truncated:S,nextCursor:_,scannedBytes:T};return i>0&&(N.gap=i),this.closed&&_>=this.writeCursor&&(N.eof=!0),N}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(()=>Lh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Ti,qP,Nh=K(()=>{"use strict";Ti=[{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."}],qP=new Map(Ti.map(t=>[t.verb,t]))});function Dh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Ei(t,e){return Kl(t,e.map(n=>n.modelId))}function Kl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Dh(t),s=e.filter(i=>Dh(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 hd=K(()=>{"use strict"});function Hh(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=Jl(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 u=n.get(l);u?u.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=Jl(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?XS(r,i.outIndex,GS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?ZS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!ek(f)&&(f=tk(f,s.get(u))),r.push(f);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 Jl(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function GS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function XS(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 ZS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function ek(t){let n=Jl(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function tk(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Uh=K(()=>{"use strict"});function Pi(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=Vl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Ql(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Yl(c))):d==="turn_complete"&&i()}return i(),ok(s.join(`
16
- `),n)}function Yl(t){let e=sk(t),n=rk(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function sk(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function rk(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of nk){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${ik(r,200)}`)}return n}function Vl(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 Ql(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function ik(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function ok(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.`);No(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.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=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Wp()})});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:Wp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),jp(t,y.session_token)}async function nS(t,e){let n=await sS(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Al(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function sS(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?qp(p.subject):void 0,issuer:p?.issuer?qp(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function qp(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 rS(t,e){let n=await ys(),r=n&&An(n.pid)?n.loopbackPort:t.port,i=t.port===xn?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 iS(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 Wp(){try{let t=zp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Jp(t){return t.port===xn?t.host:`${t.host}:${t.port}`}var Tl,Rr=K(()=>{"use strict";tt();ms();Lo();vl();Sl();Bo();bi();Ho();Lo();Tl=class extends Error{host;port;constructor(e,n){let s=n===xn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Dn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as oS,renameSync as aS,statSync as dS}from"fs";function Qp(t){Vp=t}function ne(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?$.tuiLogFile():e;if(n.length!==0)try{cS(n);let s=JSON.stringify({t:new Date().toISOString(),...t});oS(n,`${s}
15
+ `)}catch{}}function cS(t){try{if(dS(t).size<Vp)return;aS(t,`${t}.0`)}catch{}}var Vp,Tr=K(()=>{"use strict";ye();Vp=5*1024*1024});var W,od=K(()=>{"use strict";W={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 Fe}from"zod";var bh,LS,vh,Sh,kh,Ul=K(()=>{"use strict";bh=Fe.object({protocolVersion:Fe.number().optional(),clientCapabilities:Fe.record(Fe.unknown()).optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional()}),LS=Fe.enum(["full","pending_only","none","after_message"]),vh=Fe.object({cwd:Fe.string(),mcpServers:Fe.array(Fe.unknown()).optional(),_meta:Fe.record(Fe.unknown()).optional()}),Sh=Fe.object({upstreamSessionId:Fe.string(),agentId:Fe.string(),cwd:Fe.string(),title:Fe.string().optional(),agentArgs:Fe.array(Fe.string()).optional()}),kh=Fe.object({sessionId:Fe.string(),historyPolicy:LS.default("full"),afterMessageId:Fe.string().optional(),clientId:Fe.string().optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional(),_meta:Fe.record(Fe.unknown()).optional()})});import{z as de}from"zod";function ad(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 Ah(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Uo(t._meta,ad(t))};return t.title!==void 0&&(e.title=t.title),e}var Ih,xh,jl,dP,BS,cP,ql=K(()=>{"use strict";dd();Ih=de.object({sessionId:de.string()}),xh=de.object({cwd:de.string().optional(),cursor:de.string().optional()}),jl=de.object({used:de.number().optional(),size:de.number().optional(),costAmount:de.number().optional(),costCurrency:de.string().optional()}),dP=de.object({sessionId:de.string(),upstreamSessionId:de.string().optional(),cwd:de.string(),title:de.string().optional(),agentId:de.string().optional(),currentModel:de.string().optional(),currentUsage:jl.optional(),importedFromMachine:de.string().optional(),importedFromUpstreamSessionId:de.string().optional(),parentSessionId:de.string().optional(),forkedFromSessionId:de.string().optional(),forkedFromMessageId:de.string().optional(),originatingClient:de.object({name:de.string(),version:de.string().optional()}).optional(),interactive:de.boolean().optional(),priority:de.number().int().nonnegative().optional(),updatedAt:de.string(),attachedClients:de.number().int().nonnegative(),status:de.enum(["warm","cold"]).default("warm"),busy:de.boolean().default(!1),awaitingInput:de.boolean().default(!1),compactionState:de.any().optional(),forkSynthesisState:de.enum(["running","failed"]).optional(),_meta:de.record(de.unknown()).optional()}),BS=de.object({sessionId:de.string(),cwd:de.string(),title:de.string().optional(),updatedAt:de.string().optional(),_meta:de.record(de.unknown()).optional()}),cP=de.object({sessions:de.array(BS),nextCursor:de.string().optional()})});function NS(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 nn(t){if(!t)return{};let e=t[Lt];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=Sh.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=jl.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=NS(n.env);r!==void 0&&(s.env=r)}return s}function Uo(t,e){return{...t??{},[Lt]:e}}var Lt,dd=K(()=>{"use strict";Ul();ql();Lt="hydra-acp"});import{z as Z}from"zod";var Ch,cd,Rh,mP,gP,yP,Th,wP,Eh,bP,Ph,vP,SP,Mh=K(()=>{"use strict";Ch=Z.object({sessionId:Z.string(),prompt:Z.array(Z.unknown()),_meta:Z.record(Z.unknown()).optional()}),cd=Z.object({sessionId:Z.string()}),Rh=Z.object({clientId:Z.string(),name:Z.string().optional(),version:Z.string().optional()}),mP=Z.object({sessionId:Z.string(),messageId:Z.string(),originator:Rh,prompt:Z.array(Z.unknown()),position:Z.number().int().nonnegative(),queueDepth:Z.number().int().positive(),enqueuedAt:Z.number()}),gP=Z.object({sessionId:Z.string(),messageId:Z.string(),prompt:Z.array(Z.unknown())}),yP=Z.object({sessionId:Z.string(),messageId:Z.string(),reason:Z.enum(["started","cancelled","abandoned"])}),Th=Z.object({sessionId:Z.string(),messageId:Z.string()}),wP=Z.object({cancelled:Z.boolean(),reason:Z.enum(["ok","not_found","already_running"])}),Eh=Z.object({sessionId:Z.string(),messageId:Z.string(),prompt:Z.array(Z.unknown())}),bP=Z.object({updated:Z.boolean(),reason:Z.enum(["ok","not_found","already_running"])}),Ph=Z.object({sessionId:Z.string(),targetMessageId:Z.string(),prompt:Z.array(Z.unknown()),replaceQueue:Z.boolean().optional(),onTargetCompleted:Z.enum(["reject","send_anyway"]).optional()}),vP=Z.object({amended:Z.boolean(),reason:Z.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:Z.string().optional()}),SP=Z.object({sessionId:Z.string(),cancelledMessageId:Z.string(),newMessageId:Z.string(),prompt:Z.array(Z.unknown()),originator:Rh,amendedAt:Z.number()})});import{z as Us}from"zod";var _h,ld,xi,$h=K(()=>{"use strict";_h=Us.object({agentId:Us.string(),version:Us.string(),source:Us.enum(["binary","npm"]),phase:Us.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Us.number().optional(),totalBytes:Us.number().optional(),packageSpec:Us.string().optional()}),ld="hydra-acp/agents/install_progress",xi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Bt=K(()=>{"use strict";od();Ul();dd();ql();Mh();$h()});import{nanoid as DS}from"nanoid";var Wl,Jt,Pr=K(()=>{"use strict";Bt();Wl=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Jt=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 Wl;let s=DS(),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:W.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??W.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 Ai(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 Ci(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 zl=K(()=>{"use strict"});import*as Lh from"fs/promises";function GS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WS,zS,Ri,KS,JS,YS,VS,QS,Oh,pd,Bh=K(()=>{"use strict";WS=64*1024*1024,zS=1*1024*1024,Ri=64*1024,KS=6e4,JS=100,YS=1e3,VS=64*1024,QS=256*1024,Oh=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??WS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(zS,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,Ri));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let 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,Ri)),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,Ri)),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,KS));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(GS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??JS,YS)),f=Math.max(1,Math.min(e.maxBytes??VS,QS)),p=Math.max(0,Math.min(e.contextBefore??0,Oh)),h=Math.max(0,Math.min(e.contextAfter??0,Oh)),m=[],y=[],b=[],v=0,S=!1,x=0,T=0,F=(J,q)=>{for(let ee of b)ee.remaining>0&&(ee.match.after===void 0&&(ee.match.after=[]),ee.match.after.push({cursor:J,line:q}),ee.remaining--,v+=q.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(q)!==l&&m.length<u){let ee={cursor:J,line:q};if(p>0&&y.length>0){ee.before=y.slice();for(let ae of ee.before)v+=ae.line.length}v+=q.length,m.push(ee),h>0&&b.push({match:ee,remaining:h})}if(p>0)for(y.push({cursor:J,line:q});y.length>p;)y.shift();let D=m.length>=u&&b.length===0,X=v>=f;return D||X};for(let J=0;J<o.length;J++){if(o[J]!==10)continue;let q=o.subarray(x,J).toString("utf8"),L=r+x;if(x=J+1,T=x,F(L,q)){S=!0;break}}if(!S&&x<o.length&&this.closed){let J=o.subarray(x).toString("utf8"),q=r+x;F(q,J)&&(S=!0),T=o.length}let _=Math.min(r+T,this.writeCursor),N={matches:m,truncated:S,nextCursor:_,scannedBytes:T};return i>0&&(N.gap=i),this.closed&&_>=this.writeCursor&&(N.eof=!0),N}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(()=>Lh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Ti,WP,Nh=K(()=>{"use strict";Ti=[{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."}],WP=new Map(Ti.map(t=>[t.verb,t]))});function Dh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Ei(t,e){return Kl(t,e.map(n=>n.modelId))}function Kl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Dh(t),s=e.filter(i=>Dh(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 hd=K(()=>{"use strict"});function Hh(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=Jl(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 u=n.get(l);u?u.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=Jl(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?ZS(r,i.outIndex,XS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?ek(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!tk(f)&&(f=nk(f,s.get(u))),r.push(f);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 Jl(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function XS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function ZS(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 ek(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function tk(t){let n=Jl(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function nk(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Uh=K(()=>{"use strict"});function Pi(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=Vl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Ql(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Yl(c))):d==="turn_complete"&&i()}return i(),ak(s.join(`
16
+ `),n)}function Yl(t){let e=rk(t),n=ik(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function rk(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function ik(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of sk){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${ok(r,200)}`)}return n}function Vl(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 Ql(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function ok(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function ak(t,e){if(t.length<=e)return t;let n=t.split(`
17
17
  `);for(;n.length>0;){let s=jh+n.join(`
18
- `);if(s.length<=e)return s;n.shift()}return jh}var jh,nk,md=K(()=>{"use strict";jh=`[older history truncated]
19
- `,nk=["file_path","filePath","path","command","pattern","query"]});function Gl(t){let e=[],n=t.synopsis;if(n!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??qh}`),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=jo("Open threads",n.open_threads);o.length>0&&e.push(o);let a=jo("Decisions",n.decisions);a.length>0&&e.push(a);let c=jo("File edit intentions",n.file_edit_intentions);c.length>0&&e.push(c);let d=jo("Unresolved errors",n.unresolved_errors);d.length>0&&e.push(d);let l=jo("Tool state",n.tool_state);l.length>0&&e.push(l);let u=Wh(n.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=Wh(n.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${t.title??qh}`);let{closedText:s,openText:r,keptCount:i}=ak(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(`
18
+ `);if(s.length<=e)return s;n.shift()}return jh}var jh,sk,md=K(()=>{"use strict";jh=`[older history truncated]
19
+ `,sk=["file_path","filePath","path","command","pattern","query"]});function Gl(t){let e=[],n=t.synopsis;if(n!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??qh}`),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=jo("Open threads",n.open_threads);o.length>0&&e.push(o);let a=jo("Decisions",n.decisions);a.length>0&&e.push(a);let c=jo("File edit intentions",n.file_edit_intentions);c.length>0&&e.push(c);let d=jo("Unresolved errors",n.unresolved_errors);d.length>0&&e.push(d);let l=jo("Tool state",n.tool_state);l.length>0&&e.push(l);let u=Wh(n.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=Wh(n.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${t.title??qh}`);let{closedText:s,openText:r,keptCount:i}=dk(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
20
  `)}function jo(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(`
21
- `)}`}function Wh(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 ak(t,e,n,s){if(t.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=dk(t),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=n).length,u=Math.max(l,s),f=Math.min(u,e,r.length);o=f,a=f>0?r.slice(-f):[]}let c=a.length>0?zh(a):"",d=i?zh([i]):"";return{closedText:c,openText:d,keptCount:o}}function zh(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(`
22
- `)}function dk(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:Vl(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&n!==null){let d=Ql(a.content);d.length>0&&(n.agent+=d)}else c==="tool_call"&&n!==null?n.tools.push(Yl(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 qh,Kh=K(()=>{"use strict";md();qh="(untitled)"});import*as jn from"fs/promises";async function qo(t,e){let n=$.queueFile(t);if(e.length===0){await jn.unlink(n).catch(()=>{});return}await jn.mkdir($.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
21
+ `)}`}function Wh(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 dk(t,e,n,s){if(t.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=ck(t),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=n).length,u=Math.max(l,s),f=Math.min(u,e,r.length);o=f,a=f>0?r.slice(-f):[]}let c=a.length>0?zh(a):"",d=i?zh([i]):"";return{closedText:c,openText:d,keptCount:o}}function zh(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(`
22
+ `)}function ck(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:Vl(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&n!==null){let d=Ql(a.content);d.length>0&&(n.agent+=d)}else c==="tool_call"&&n!==null?n.tools.push(Yl(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 qh,Kh=K(()=>{"use strict";md();qh="(untitled)"});import*as jn from"fs/promises";async function qo(t,e){let n=$.queueFile(t);if(e.length===0){await jn.unlink(n).catch(()=>{});return}await jn.mkdir($.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
23
23
  `)+`
24
24
  `;await jn.writeFile(n,s,"utf8")}async function Jh(t){let e=$.queueFile(t),n;try{n=await jn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
25
- `))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 Yh(t){let e=$.queueFile(t);await jn.unlink(e).catch(()=>{})}var Xl=K(()=>{"use strict";ye()});import{customAlphabet as Xh}from"nanoid";import*as tm from"fs/promises";function qs(){return`m_${em()}`}function lt(t){return t.startsWith(gn)?t.slice(gn.length):t}function nn(t,e){return t.code=e,t}function Vh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&hk.has(s)}function mk(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 gk(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 yk(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 _i(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 Wo(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 wk(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 bk(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 vk(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 Sk(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:qs()}}}function tu(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 Qh(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 kk(t){let e=Ik(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=xk(t.resolver),n}function Ik(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 xk(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 Mi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function eu(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Ak(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Gh(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}
25
+ `))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 Yh(t){let e=$.queueFile(t);await jn.unlink(e).catch(()=>{})}var Xl=K(()=>{"use strict";ye()});import{customAlphabet as Xh}from"nanoid";import*as tm from"fs/promises";function qs(){return`m_${em()}`}function lt(t){return t.startsWith(qt)?t.slice(qt.length):t}function sn(t,e){return t.code=e,t}function Vh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&mk.has(s)}function gk(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 yk(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 wk(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 _i(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 Wo(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 bk(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 vk(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 Sk(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 kk(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:qs()}}}function tu(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 Qh(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 Ik(t){let e=xk(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=Ak(t.resolver),n}function xk(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 Ak(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 Mi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function eu(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Ck(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Gh(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}
26
26
  ${s.join(`
27
- `)}`}function nu(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 Zh,em,Zl,ck,lk,uk,gn,fk,gd,pk,$i,hk,qn=K(()=>{"use strict";zl();Bh();Nh();hd();Uh();Kh();Xl();Bt();Zh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",em=Xh(Zh,16),Zl=Xh(Zh,16),ck=20,lk=20,uk=5,gn="hydra_session_";fk=1e3,gd=300*1e3,pk=64,$i=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??`${gn}${em()}`,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??fk,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){bk(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=Qh(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 u=this.transformChain[l];if(n.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Zl()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,b=new Set(n),v=r;await new Promise(S=>{let x=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...b,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},gd);typeof x.unref=="function"&&x.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:x,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:b,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(u.name)}if(r!=="session/update")return;let c=vk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=wk(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,u=this.spawnReplacementAgent;if(!u)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await u({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Ci({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Ai({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(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=Gl({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 T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,b=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=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 T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(F){this.logger?.warn(`swapUpstream: agentChange handler failed: ${F.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...b!==void 0?{previousSummarizedThroughEntry:b}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.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?`
27
+ `)}`}function nu(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 Zh,em,Zl,lk,uk,fk,qt,pk,gd,hk,$i,mk,qn=K(()=>{"use strict";zl();Bh();Nh();hd();Uh();Kh();Xl();Bt();Zh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",em=Xh(Zh,16),Zl=Xh(Zh,16),lk=20,uk=20,fk=5,qt="hydra_session_";pk=1e3,gd=300*1e3,hk=64,$i=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??`${qt}${em()}`,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??pk,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){vk(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=Qh(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 u=this.transformChain[l];if(n.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Zl()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,b=new Set(n),v=r;await new Promise(S=>{let x=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...b,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},gd);typeof x.unref=="function"&&x.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:x,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:b,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(u.name)}if(r!=="session/update")return;let c=Sk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=bk(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,u=this.spawnReplacementAgent;if(!u)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await u({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Ci({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Ai({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(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=Gl({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 T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,b=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=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 T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(F){this.logger?.warn(`swapUpstream: agentChange handler failed: ${F.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...b!==void 0?{previousSummarizedThroughEntry:b}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.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?`
28
28
  Switched to ${r}.
29
29
  `:`
30
30
  Compaction completed.
31
- `,x=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",x).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 Ci({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Ai({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=ck){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 u=c.status;(u==="completed"||u==="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 nn(new Error("session is closed"),W.SessionNotFound);if(this.clients.has(e.clientId))throw nn(new Error(`client ${e.clientId} is already attached`),W.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:Hh(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Vh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?tu(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 nn(new Error("client not attached"),W.SessionNotFound);if(this.closing)throw nn(new Error("session is closing; new prompts cannot be accepted"),W.SessionClosing);let r=qs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(tn((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=Mi(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:qs()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.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>pk;){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 nn(new Error("client not attached"),W.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=qs(),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=qs(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw nn(new Error("client not attached"),W.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_${Zl()}`,u;try{u=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 f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??eu(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=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:eu(e))))},gd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,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_${Zl()}`,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(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??Ak(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let b=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]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},gd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:b,transformerName:c.name,method:m,envelope:p,chainIdx:f,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):gd,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:eu(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=qs(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),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=Mi((e??{}).prompt),r=nu(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=_i(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=_i(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=Wo(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=_i(o.options);if(c.length>0){let d=Wo(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})),u=o.name,f=typeof u=="string"&&u.trim()?u.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:f,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(mk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(gk(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(",")}]`),yk(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 Ti){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}`,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}if(c.length>0&&n.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}}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 Ti)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(Ti.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=W.InternalError,u}}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=Ti.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=W.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 u,f=!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 f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
31
+ `,x=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",x).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 Ci({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Ai({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=lk){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 u=c.status;(u==="completed"||u==="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 sn(new Error("session is closed"),W.SessionNotFound);if(this.clients.has(e.clientId))throw sn(new Error(`client ${e.clientId} is already attached`),W.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:Hh(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Vh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?tu(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 sn(new Error("client not attached"),W.SessionNotFound);if(this.closing)throw sn(new Error("session is closing; new prompts cannot be accepted"),W.SessionClosing);let r=qs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(nn((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=Mi(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:qs()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.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>hk;){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 sn(new Error("client not attached"),W.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=qs(),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=qs(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw sn(new Error("client not attached"),W.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_${Zl()}`,u;try{u=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 f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??eu(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=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:eu(e))))},gd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,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_${Zl()}`,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(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??Ck(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let b=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]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},gd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:b,transformerName:c.name,method:m,envelope:p,chainIdx:f,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):gd,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:eu(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=qs(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),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=Mi((e??{}).prompt),r=nu(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=_i(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=_i(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=Wo(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=_i(o.options);if(c.length>0){let d=Wo(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})),u=o.name,f=typeof u=="string"&&u.trim()?u.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:f,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(gk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(yk(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(",")}]`),wk(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 Ti){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}`,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}if(c.length>0&&n.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}}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 Ti)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(Ti.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=W.InternalError,u}}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=Ti.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=W.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 u,f=!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 f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
32
32
  ${e}
33
33
  `},_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}):
34
34
  ${s.join(`
@@ -49,7 +49,7 @@ ${l}:
49
49
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(d=>d.id===i):!0,c=r.map(d=>{let l=d.id===i?"\u25B6 ":" ",u=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${u}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
50
50
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
51
51
  ${o}
52
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw nn(new Error(`unknown mode: ${n} (known: ${r})`),W.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
52
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw sn(new Error(`unknown mode: ${n} (known: ${r})`),W.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
53
53
  _(no config options advertised yet)_
54
54
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>Gh(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
55
55
  ${u.join(`
@@ -67,10 +67,10 @@ ${p}.
67
67
  ${h}:
68
68
  ${f.join(`
69
69
  `)}
70
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let 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 nn(new Error("/hydra agent requires an agent id"),W.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(n):void 0)??n;if(r===this.agentId)throw nn(new Error(`already on agent ${r}`),W.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 nn(new Error("agent restart not configured for this session"),W.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(`
71
- `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw nn(new Error("session is closing"),W.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 u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Mi(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.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(`
72
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}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=Gl({synopsis:e,title:n,tail:s,tailK:lk,tailFloor:uk,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??Ri,Ri)),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=W.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(()=>Yh(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(()=>tm.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 u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),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=!Vh(e,r),o=i?Sk(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 nn(new Error("no clients attached to handle permission request"),W.PermissionDenied);let s=this.rewriteForClient(e),r=Qh(s),i=qs(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===W.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(x=>{f--,m(()=>{let T=kk({toolCallId:r,result:x,resolver:v});for(let F of u)F.client.clientId!==v.clientId&&F.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??nn(new Error("no client handled permission request"),W.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:qs(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,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(()=>qo(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=Mi(e.prompt).replace(/\s+$/,""),s=!n.includes(`
73
- `)&&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)}};hk=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 Fi}from"zod";var Ck,nm,sm=K(()=>{"use strict";Ck=Fi.object({source:Fi.string(),reason:Fi.string(),raisedAt:Fi.number(),payload:Fi.unknown()}),nm=Fi.array(Ck)});import{z as Oe}from"zod";function om(t){let e=t.trim();if(e.length===0)return;let n=Oi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Oi(e.slice(i,o+1)))}if(n===void 0){let i=dm(e);i!==void 0&&(n=Oi(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,im))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=zo.safeParse(s.synopsis);i.success&&Rk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function am(t){let e=t.trim();if(e.length===0)return;let n=Oi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Oi(e.slice(d,l+1)))}if(n===void 0){let d=dm(e);d!==void 0&&(n=Oi(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,im))}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],u=Oe.array(Oe.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Oi(t){try{return JSON.parse(t)}catch{return}}function dm(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 Rk(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,zo,im,su,ru,yd=K(()=>{"use strict";rm=Oe.object({status:Oe.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Oe.number(),iter:Oe.number().int().nonnegative().optional(),attempts:Oe.number().int().nonnegative().optional(),lastError:Oe.string().optional(),worker:Oe.object({upstreamSessionId:Oe.string(),pid:Oe.number().int().nonnegative()}).optional()}),zo=Oe.object({goal:Oe.string().optional(),outcome:Oe.string().optional(),files_touched:Oe.array(Oe.string()).optional(),tools_used:Oe.array(Oe.string()).optional(),rejected_approaches:Oe.array(Oe.string()).optional(),open_threads:Oe.array(Oe.string()).optional(),decisions:Oe.array(Oe.string()).optional(),file_edit_intentions:Oe.array(Oe.string()).optional(),unresolved_errors:Oe.array(Oe.string()).optional(),tool_state:Oe.array(Oe.string()).optional()}),im=200,su=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
70
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let 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 sn(new Error("/hydra agent requires an agent id"),W.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(n):void 0)??n;if(r===this.agentId)throw sn(new Error(`already on agent ${r}`),W.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 sn(new Error("agent restart not configured for this session"),W.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(`
71
+ `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw sn(new Error("session is closing"),W.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 u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Mi(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.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(`
72
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}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=Gl({synopsis:e,title:n,tail:s,tailK:uk,tailFloor:fk,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??Ri,Ri)),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=W.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(()=>Yh(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(()=>tm.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 u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),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=!Vh(e,r),o=i?kk(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 sn(new Error("no clients attached to handle permission request"),W.PermissionDenied);let s=this.rewriteForClient(e),r=Qh(s),i=qs(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===W.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(x=>{f--,m(()=>{let T=Ik({toolCallId:r,result:x,resolver:v});for(let F of u)F.client.clientId!==v.clientId&&F.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??sn(new Error("no client handled permission request"),W.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:qs(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,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(()=>qo(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=Mi(e.prompt).replace(/\s+$/,""),s=!n.includes(`
73
+ `)&&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)}};mk=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 Fi}from"zod";var Rk,nm,sm=K(()=>{"use strict";Rk=Fi.object({source:Fi.string(),reason:Fi.string(),raisedAt:Fi.number(),payload:Fi.unknown()}),nm=Fi.array(Rk)});import{z as Oe}from"zod";function om(t){let e=t.trim();if(e.length===0)return;let n=Oi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Oi(e.slice(i,o+1)))}if(n===void 0){let i=dm(e);i!==void 0&&(n=Oi(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,im))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=zo.safeParse(s.synopsis);i.success&&Tk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function am(t){let e=t.trim();if(e.length===0)return;let n=Oi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Oi(e.slice(d,l+1)))}if(n===void 0){let d=dm(e);d!==void 0&&(n=Oi(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,im))}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],u=Oe.array(Oe.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Oi(t){try{return JSON.parse(t)}catch{return}}function dm(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 Tk(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,zo,im,su,ru,yd=K(()=>{"use strict";rm=Oe.object({status:Oe.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Oe.number(),iter:Oe.number().int().nonnegative().optional(),attempts:Oe.number().int().nonnegative().optional(),lastError:Oe.string().optional(),worker:Oe.object({upstreamSessionId:Oe.string(),pid:Oe.number().int().nonnegative()}).optional()}),zo=Oe.object({goal:Oe.string().optional(),outcome:Oe.string().optional(),files_touched:Oe.array(Oe.string()).optional(),tools_used:Oe.array(Oe.string()).optional(),rejected_approaches:Oe.array(Oe.string()).optional(),open_threads:Oe.array(Oe.string()).optional(),decisions:Oe.array(Oe.string()).optional(),file_edit_intentions:Oe.array(Oe.string()).optional(),unresolved_errors:Oe.array(Oe.string()).optional(),tool_state:Oe.array(Oe.string()).optional()}),im=200,su=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
74
74
  {
75
75
  "title": "short summary, max 80 chars",
76
76
  "synopsis": {
@@ -92,59 +92,59 @@ Use empty arrays/strings where a field doesn't apply.`;ru=`Reply with ONLY a JSO
92
92
  "unresolved_errors": ["errors left open at session end"],
93
93
  "tool_state": ["runtime state relevant for recall"]
94
94
  }
95
- Use empty arrays/strings where a field doesn't apply.`});import*as Li from"fs/promises";import*as fM from"path";import{customAlphabet as Tk}from"nanoid";import{z as te}from"zod";function Ko(){return`${Mk}${Pk()}`}function Ok(t){if(!iu.test(t))throw new Error(`unsafe session id: ${t}`)}function lu(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??[],createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var Ek,Pk,Mk,ou,au,_k,du,cu,$k,Fk,iu,wd,uu=K(()=>{"use strict";ye();Ir();sm();yd();Ek="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Pk=Tk(Ek,16),Mk="hydra_lineage_";ou=te.object({name:te.string(),description:te.string().optional()}),au=te.object({id:te.string(),name:te.string().optional(),description:te.string().optional()}),_k=te.object({modelId:te.string(),name:te.string().optional(),description:te.string().optional()}),du=te.object({used:te.number().optional(),size:te.number().optional(),costAmount:te.number().optional(),costCurrency:te.string().optional(),cumulativeCost:te.number().optional()}),cu=te.object({name:te.string(),version:te.string().optional()}),$k=te.object({previousUpstreamSessionId:te.string(),previousSummarizedThroughEntry:te.number().int().nonnegative().optional()}),Fk=te.object({version:te.literal(1),sessionId:te.string(),lineageId:te.string().optional(),upstreamSessionId:te.string(),importedFromSessionId:te.string().optional(),importedFromUpstreamSessionId:te.string().optional(),importedFromMachine:te.string().optional(),agentId:te.string(),cwd:te.string(),title:te.string().optional(),synopsis:zo.optional(),compactionState:rm.optional(),rollbackBreadcrumb:$k.optional(),summarizedThroughEntry:te.number().int().nonnegative().optional(),agentArgs:te.array(te.string()).optional(),currentModel:te.string().optional(),currentMode:te.string().optional(),currentUsage:du.optional(),agentCommands:te.array(ou).optional(),agentModes:te.array(au).optional(),agentModels:te.array(_k).optional(),pendingHistorySync:te.boolean().optional(),pendingAgentSwap:te.string().optional(),parentSessionId:te.string().optional(),forkedFromSessionId:te.string().optional(),forkedFromMessageId:te.string().optional(),forkSynthesisState:te.enum(["running","failed"]).optional(),originatingClient:cu.optional(),interactive:te.boolean().optional(),priority:te.number().int().nonnegative().optional(),forwardedEnv:te.record(te.string(),te.string()).optional(),attentionFlags:nm.default([]).optional(),createdAt:te.string(),updatedAt:te.string()}),iu=/^[A-Za-z0-9_-]+$/;wd=class{async write(e){Ok(e.sessionId);let n={version:1,...e};await Zt($.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!iu.test(e))return;let n=await hn($.sessionFile(e));if(n!==void 0)try{return Fk.parse(n)}catch{return}}async delete(e){if(iu.test(e)){try{await Li.unlink($.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Li.rmdir($.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 Li.readdir($.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 Bk}from"url";import*as Jo from"path";import*as vd from"fs";function Nk(){try{let t=Jo.dirname(Bk(import.meta.url));for(let e=0;e<8;e+=1){let n=Jo.join(t,"package.json");if(vd.existsSync(n)){let r=JSON.parse(vd.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=Jo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var me,Mr,sn=K(()=>{"use strict";me=Nk(),Mr="hydra-acp-cat"});function fu(t){let e=new Map;for(let n of wm(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 mm(t){return fu(t).map(e=>e.name)}function pu(t){let e=new Map;for(let n of wm(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 gm(t){return pu(t).map(e=>e.path)}function ym(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function wm(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:pm(i),paths:new Set},e.set(c,d)):d.toolName=pm(i);for(let l of hm(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 hm(i.rawInput,i.locations))a.paths.add(c)}return e}function pm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function hm(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 hu=K(()=>{"use strict"});import{promises as Vo}from"fs";import*as vu from"path";async function Qo(t){let e;try{e=await Vo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Yk(e)}function Yk(t){let e=[];for(let n of t.split(`
95
+ Use empty arrays/strings where a field doesn't apply.`});import*as Li from"fs/promises";import*as pM from"path";import{customAlphabet as Ek}from"nanoid";import{z as te}from"zod";function Ko(){return`${_k}${Mk()}`}function Lk(t){if(!iu.test(t))throw new Error(`unsafe session id: ${t}`)}function lu(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??[],createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var Pk,Mk,_k,ou,au,$k,du,cu,Fk,Ok,iu,wd,uu=K(()=>{"use strict";ye();Ir();sm();yd();Pk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Mk=Ek(Pk,16),_k="hydra_lineage_";ou=te.object({name:te.string(),description:te.string().optional()}),au=te.object({id:te.string(),name:te.string().optional(),description:te.string().optional()}),$k=te.object({modelId:te.string(),name:te.string().optional(),description:te.string().optional()}),du=te.object({used:te.number().optional(),size:te.number().optional(),costAmount:te.number().optional(),costCurrency:te.string().optional(),cumulativeCost:te.number().optional()}),cu=te.object({name:te.string(),version:te.string().optional()}),Fk=te.object({previousUpstreamSessionId:te.string(),previousSummarizedThroughEntry:te.number().int().nonnegative().optional()}),Ok=te.object({version:te.literal(1),sessionId:te.string(),lineageId:te.string().optional(),upstreamSessionId:te.string(),importedFromSessionId:te.string().optional(),importedFromUpstreamSessionId:te.string().optional(),importedFromMachine:te.string().optional(),agentId:te.string(),cwd:te.string(),title:te.string().optional(),synopsis:zo.optional(),compactionState:rm.optional(),rollbackBreadcrumb:Fk.optional(),summarizedThroughEntry:te.number().int().nonnegative().optional(),agentArgs:te.array(te.string()).optional(),currentModel:te.string().optional(),currentMode:te.string().optional(),currentUsage:du.optional(),agentCommands:te.array(ou).optional(),agentModes:te.array(au).optional(),agentModels:te.array($k).optional(),pendingHistorySync:te.boolean().optional(),pendingAgentSwap:te.string().optional(),parentSessionId:te.string().optional(),forkedFromSessionId:te.string().optional(),forkedFromMessageId:te.string().optional(),forkSynthesisState:te.enum(["running","failed"]).optional(),originatingClient:cu.optional(),interactive:te.boolean().optional(),priority:te.number().int().nonnegative().optional(),forwardedEnv:te.record(te.string(),te.string()).optional(),attentionFlags:nm.default([]).optional(),createdAt:te.string(),updatedAt:te.string()}),iu=/^[A-Za-z0-9_-]+$/;wd=class{async write(e){Lk(e.sessionId);let n={version:1,...e};await en($.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!iu.test(e))return;let n=await mn($.sessionFile(e));if(n!==void 0)try{return Ok.parse(n)}catch{return}}async delete(e){if(iu.test(e)){try{await Li.unlink($.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Li.rmdir($.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 Li.readdir($.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 Nk}from"url";import*as Jo from"path";import*as vd from"fs";function Dk(){try{let t=Jo.dirname(Nk(import.meta.url));for(let e=0;e<8;e+=1){let n=Jo.join(t,"package.json");if(vd.existsSync(n)){let r=JSON.parse(vd.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=Jo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var me,Mr,rn=K(()=>{"use strict";me=Dk(),Mr="hydra-acp-cat"});function fu(t){let e=new Map;for(let n of wm(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 mm(t){return fu(t).map(e=>e.name)}function pu(t){let e=new Map;for(let n of wm(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 gm(t){return pu(t).map(e=>e.path)}function ym(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function wm(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:pm(i),paths:new Set},e.set(c,d)):d.toolName=pm(i);for(let l of hm(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 hm(i.rawInput,i.locations))a.paths.add(c)}return e}function pm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function hm(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 hu=K(()=>{"use strict"});import{promises as Vo}from"fs";import*as vu from"path";async function Qo(t){let e;try{e=await Vo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Vk(e)}function Vk(t){let e=[];for(let n of t.split(`
96
96
  `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Go(t,e,n=Em){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 _r(t,e){await Vo.mkdir(vu.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Vo.writeFile(t,n.length>0?n.join(`
97
97
  `)+`
98
98
  `:"")}async function Pm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Vo.mkdir(vu.dirname(t),{recursive:!0}),await Vo.appendFile(t,JSON.stringify(n)+`
99
- `,{encoding:"utf8"}))}function xd(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function Su(t,e,n=Em){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=Go(r,o,n)))}return r}var Em,Ad=K(()=>{"use strict";Em=500});import{z as Pe}from"zod";function Xo(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 Cn(t){return Gk.parse(t)}var Vk,Qk,Gk,$r=K(()=>{"use strict";uu();yd();Vk=Pe.object({method:Pe.string(),params:Pe.unknown(),recordedAt:Pe.number()}),Qk=Pe.object({sessionId:Pe.string(),lineageId:Pe.string(),upstreamSessionId:Pe.string().optional(),agentId:Pe.string(),cwd:Pe.string(),title:Pe.string().optional(),synopsis:zo.optional(),summarizedThroughEntry:Pe.number().int().nonnegative().optional(),currentModel:Pe.string().optional(),currentMode:Pe.string().optional(),currentUsage:du.optional(),agentCommands:Pe.array(ou).optional(),agentModes:Pe.array(au).optional(),interactive:Pe.boolean().optional(),originatingClient:cu.optional(),priority:Pe.number().int().nonnegative().optional(),createdAt:Pe.string(),updatedAt:Pe.string()}),Gk=Pe.object({version:Pe.literal(1),exportedAt:Pe.string(),exportedFrom:Pe.object({hydraVersion:Pe.string(),machine:Pe.string(),hydraHost:Pe.string().optional()}),session:Qk,history:Pe.array(Vk),promptHistory:Pe.array(Pe.string()).optional(),toolBlobs:Pe.record(Pe.string()).optional()})});import{createHash as fI}from"crypto";function Mu(t){if(Array.isArray(t))return t.map(Mu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Mu(t[n]);return e}return t}function zs(t){let{tui:e,...n}=t,s=JSON.stringify(Mu(n));return fI("sha256").update(s).digest("hex").slice(0,16)}var ia=K(()=>{"use strict";tt()});function _u(t){return Math.floor(t/4)}function Ym(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=_u(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 Vm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var $u=K(()=>{"use strict"});function oa(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Qm=K(()=>{"use strict"});import{posix as xI}from"path";import AI from"strip-ansi";function ht(t){return AI(t).replace(CI,"")}function Te(t){return ht(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Kn(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 _I(n);case"agent_thought_chunk":case"agent_thought":return $I(n);case"user_message_chunk":return FI(n);case"prompt_received":return OI(n);case"tool_call":return LI(n,e);case"tool_call_update":return UI(n,e);case"plan":return WI(n);case"current_mode_update":return zI(n);case"current_model_update":return KI(n);case"turn_complete":return JI(n);case"usage_update":return MI(n);case"available_commands_update":return EI(n);case"available_modes_update":return PI(n);case"session_info_update":return TI(n);case"config_option_update":return RI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function RI(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 TI(t){let e=it(t,"title"),n=e!==void 0?Te(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 qd(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:Te(r)};typeof s.description=="string"&&(i.description=Te(s.description)),e.push(i)}return e}function EI(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:qd(e)}:null}function PI(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:Te(r.id)};typeof r.name=="string"&&(i.name=Te(r.name)),typeof r.description=="string"&&(i.description=Te(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function MI(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 _I(t){let e=aa(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:oa(t)}}function $I(t){let e=typeof t.text=="string"?ht(t.text):aa(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:oa(t)}}function FI(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=aa(t.content);return n===null?null:{kind:"user-text",text:n}}function OI(t){let e=YI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Zm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Gm(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 Wd(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=Gm(r.oldText),o=Gm(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 eg(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:ht(n)}function LI(t,e={}){let n=it(t,"toolCallId")??it(t,"id");if(!n)return null;let s=it(t,"title")??it(t,"name")??it(t,"label")??"tool call",r=it(t,"name")??it(t,"title");if(Zm(r)){let h=eg(t);if(h!==null){let m=it(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=sg(Te(s),t,e),o=it(t,"status"),a=it(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Wd(t);d!==null&&(c.editDiff=d);let l=ng(t);l!==void 0&&(c.detail=l);let u=Fu(t);u!==void 0&&(c.detailFull=u);let f=tg(t);f!==void 0&&(c.locations=f);let p=oa(t);return p!==void 0&&(c.workerTaskId=p),c}function tg(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 ng(t){let e=Fu(t);if(e===void 0)return;let n=Te(e),s=t.rawInput;return s&&typeof s.command=="string"?DI(n,Xm):HI(n,Xm)}function Fu(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 ht(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 st(Te(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 st(Te(s))}}}function NI(t){for(let e of BI)if(t.startsWith(e))return!0;return!1}function sg(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return st(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 st(o)}return NI(t)?st(`/${t}`):n.cwd&&n.cwd.length>0?st(xI.resolve(n.cwd,t)):t}function DI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function HI(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 UI(t,e={}){let n=it(t,"toolCallId")??it(t,"id");if(!n)return null;let s=it(t,"title"),r=s!==void 0?sg(Te(s),t,e):void 0,i=it(t,"status"),o=Wd(t),a=ng(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=it(t,"name")??s;if(Zm(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=eg(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 u=Fu(t);u!==void 0&&(l.detailFull=u);let f=tg(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=jI(t);h!==null&&(l.errorText=h),qI(t,h)&&(l.upstreamInterrupted=!0)}let p=oa(t);return p!==void 0&&(l.workerTaskId=p),l}function jI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=aa(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 ht(s)}return null}function qI(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 WI(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"?Te(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 zI(t){let e=it(t,"currentModeId")??it(t,"currentMode")??it(t,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function KI(t){let e=it(t,"currentModel")??it(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:Te(e),...s&&s.length>0?{availableModels:s}:{}}}function JI(t){let e=it(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 aa(t){if(typeof t=="string")return ht(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ht(e.text):null}function YI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=aa(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function it(t,e){let n=t[e];return typeof n=="string"?n:void 0}var CI,Xm,BI,Ks=K(()=>{"use strict";ye();Qm();CI=/[\x00-\x08\x0b-\x1f\x7f]/g;Xm=64;BI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Di(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=QI(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)VI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Hi(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 VI(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 QI(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,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let 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=Wd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var zd=K(()=>{"use strict";Ks()});function Jn(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:W.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 qi=K(()=>{"use strict";Bt()});import{spawn as mA}from"child_process";import{setTimeout as gA}from"timers/promises";async function jg(){let t=await ys();if(t&&An(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function yA(t){let e=await Lr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===zs(t)?"match":"mismatch":"missing"}async function Vs(t){let e=await yA(t);if(e!=="match"){if(e==="mismatch"){let n=Dn();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...
100
- `),oc(),await ac(t)}}async function ic(t){let e=await jg();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Lr(t,e=1e3){let n=await jg();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 oc(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");mA(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function ac(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await ic(t))return;await gA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Br=K(()=>{"use strict";Bo();ia();bi()});import*as qg from"fs";import*as Ki from"fs/promises";async function Ji(t,e,n){let s=bA(e),r;try{r=await Ki.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
101
- `),process.exit(1);return}throw c}let i=await wA(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
102
- `);let o=!1,a=qg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Ki.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Ki.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 wA(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Ki.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
99
+ `,{encoding:"utf8"}))}function xd(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function Su(t,e,n=Em){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=Go(r,o,n)))}return r}var Em,Ad=K(()=>{"use strict";Em=500});import{z as Pe}from"zod";function Xo(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 Cn(t){return Xk.parse(t)}var Qk,Gk,Xk,$r=K(()=>{"use strict";uu();yd();Qk=Pe.object({method:Pe.string(),params:Pe.unknown(),recordedAt:Pe.number()}),Gk=Pe.object({sessionId:Pe.string(),lineageId:Pe.string(),upstreamSessionId:Pe.string().optional(),agentId:Pe.string(),cwd:Pe.string(),title:Pe.string().optional(),synopsis:zo.optional(),summarizedThroughEntry:Pe.number().int().nonnegative().optional(),currentModel:Pe.string().optional(),currentMode:Pe.string().optional(),currentUsage:du.optional(),agentCommands:Pe.array(ou).optional(),agentModes:Pe.array(au).optional(),interactive:Pe.boolean().optional(),originatingClient:cu.optional(),priority:Pe.number().int().nonnegative().optional(),createdAt:Pe.string(),updatedAt:Pe.string()}),Xk=Pe.object({version:Pe.literal(1),exportedAt:Pe.string(),exportedFrom:Pe.object({hydraVersion:Pe.string(),machine:Pe.string(),hydraHost:Pe.string().optional()}),session:Gk,history:Pe.array(Qk),promptHistory:Pe.array(Pe.string()).optional(),toolBlobs:Pe.record(Pe.string()).optional()})});import{createHash as pI}from"crypto";function Mu(t){if(Array.isArray(t))return t.map(Mu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Mu(t[n]);return e}return t}function zs(t){let{tui:e,...n}=t,s=JSON.stringify(Mu(n));return pI("sha256").update(s).digest("hex").slice(0,16)}var ia=K(()=>{"use strict";tt()});function _u(t){return Math.floor(t/4)}function Ym(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=_u(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 Vm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var $u=K(()=>{"use strict"});function oa(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Qm=K(()=>{"use strict"});import{posix as AI}from"path";import CI from"strip-ansi";function ht(t){return CI(t).replace(RI,"")}function Te(t){return ht(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Kn(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 $I(n);case"agent_thought_chunk":case"agent_thought":return FI(n);case"user_message_chunk":return OI(n);case"prompt_received":return LI(n);case"tool_call":return BI(n,e);case"tool_call_update":return jI(n,e);case"plan":return zI(n);case"current_mode_update":return KI(n);case"current_model_update":return JI(n);case"turn_complete":return YI(n);case"usage_update":return _I(n);case"available_commands_update":return PI(n);case"available_modes_update":return MI(n);case"session_info_update":return EI(n);case"config_option_update":return TI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function TI(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 EI(t){let e=it(t,"title"),n=e!==void 0?Te(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 qd(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:Te(r)};typeof s.description=="string"&&(i.description=Te(s.description)),e.push(i)}return e}function PI(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:qd(e)}:null}function MI(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:Te(r.id)};typeof r.name=="string"&&(i.name=Te(r.name)),typeof r.description=="string"&&(i.description=Te(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function _I(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 $I(t){let e=aa(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:oa(t)}}function FI(t){let e=typeof t.text=="string"?ht(t.text):aa(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:oa(t)}}function OI(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=aa(t.content);return n===null?null:{kind:"user-text",text:n}}function LI(t){let e=VI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Zm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Gm(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 Wd(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=Gm(r.oldText),o=Gm(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 eg(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:ht(n)}function BI(t,e={}){let n=it(t,"toolCallId")??it(t,"id");if(!n)return null;let s=it(t,"title")??it(t,"name")??it(t,"label")??"tool call",r=it(t,"name")??it(t,"title");if(Zm(r)){let h=eg(t);if(h!==null){let m=it(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=sg(Te(s),t,e),o=it(t,"status"),a=it(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Wd(t);d!==null&&(c.editDiff=d);let l=ng(t);l!==void 0&&(c.detail=l);let u=Fu(t);u!==void 0&&(c.detailFull=u);let f=tg(t);f!==void 0&&(c.locations=f);let p=oa(t);return p!==void 0&&(c.workerTaskId=p),c}function tg(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 ng(t){let e=Fu(t);if(e===void 0)return;let n=Te(e),s=t.rawInput;return s&&typeof s.command=="string"?HI(n,Xm):UI(n,Xm)}function Fu(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 ht(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 st(Te(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 st(Te(s))}}}function DI(t){for(let e of NI)if(t.startsWith(e))return!0;return!1}function sg(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return st(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 st(o)}return DI(t)?st(`/${t}`):n.cwd&&n.cwd.length>0?st(AI.resolve(n.cwd,t)):t}function HI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function UI(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 jI(t,e={}){let n=it(t,"toolCallId")??it(t,"id");if(!n)return null;let s=it(t,"title"),r=s!==void 0?sg(Te(s),t,e):void 0,i=it(t,"status"),o=Wd(t),a=ng(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=it(t,"name")??s;if(Zm(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=eg(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 u=Fu(t);u!==void 0&&(l.detailFull=u);let f=tg(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=qI(t);h!==null&&(l.errorText=h),WI(t,h)&&(l.upstreamInterrupted=!0)}let p=oa(t);return p!==void 0&&(l.workerTaskId=p),l}function qI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=aa(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 ht(s)}return null}function WI(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 zI(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"?Te(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 KI(t){let e=it(t,"currentModeId")??it(t,"currentMode")??it(t,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function JI(t){let e=it(t,"currentModel")??it(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:Te(e),...s&&s.length>0?{availableModels:s}:{}}}function YI(t){let e=it(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 aa(t){if(typeof t=="string")return ht(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ht(e.text):null}function VI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=aa(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function it(t,e){let n=t[e];return typeof n=="string"?n:void 0}var RI,Xm,NI,Ks=K(()=>{"use strict";ye();Qm();RI=/[\x00-\x08\x0b-\x1f\x7f]/g;Xm=64;NI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Di(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=GI(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)QI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Hi(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 QI(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 GI(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,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let 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=Wd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var zd=K(()=>{"use strict";Ks()});function Jn(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:W.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 qi=K(()=>{"use strict";Bt()});import{spawn as gA}from"child_process";import{setTimeout as yA}from"timers/promises";async function jg(){let t=await ys();if(t&&An(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function wA(t){let e=await Lr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===zs(t)?"match":"mismatch":"missing"}async function Vs(t){let e=await wA(t);if(e!=="match"){if(e==="mismatch"){let n=Dn();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...
100
+ `),oc(),await ac(t)}}async function ic(t){let e=await jg();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Lr(t,e=1e3){let n=await jg();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 oc(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");gA(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function ac(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await ic(t))return;await yA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Br=K(()=>{"use strict";Bo();ia();bi()});import*as qg from"fs";import*as Ki from"fs/promises";async function Ji(t,e,n){let s=vA(e),r;try{r=await Ki.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
101
+ `),process.exit(1);return}throw c}let i=await bA(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
102
+ `);let o=!1,a=qg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Ki.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Ki.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 bA(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Ki.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
103
103
  `).slice(-n-1);process.stdout.write(d.join(`
104
104
  `)),o.endsWith(`
105
105
  `)||process.stdout.write(`
106
- `)}finally{await r.close()}return e}function dc(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 bA(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}
106
+ `)}finally{await r.close()}return e}function dc(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 vA(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}
107
107
  `),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}
108
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var ua=K(()=>{"use strict"});import{WebSocket as kA}from"ws";async function Nr(t,e,n=IA){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=Do(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 kA(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 ju(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var IA,ju,fa=K(()=>{"use strict";Ho();IA=1e4,ju=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 xA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Vi(){let t=await ys();if(t&&An(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await Ie();return Qg(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Qg(t,e,n){return`${n?"https":"http"}://${xA(t)}:${e}`}async function Me(t,e={}){let n=await kr(),s=await Vi(),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(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
108
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var ua=K(()=>{"use strict"});import{WebSocket as IA}from"ws";async function Nr(t,e,n=xA){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=Do(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 IA(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 ju(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var xA,ju,fa=K(()=>{"use strict";Ho();xA=1e4,ju=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 AA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Vi(){let t=await ys();if(t&&An(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await Ie();return Qg(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Qg(t,e,n){return`${n?"https":"http"}://${AA(t)}:${e}`}async function Me(t,e={}){let n=await kr(),s=await Vi(),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(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
109
109
  `),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 u=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(u=p)}let f=e.errorPrefix??"Daemon returned";process.stderr.write(`${f} ${u}
110
110
  `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function Qi(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 lc(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
111
- `),process.exit(2)),s=n?AA(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
111
+ `),process.exit(2)),s=n?CA(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
112
112
  `),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
113
113
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
114
114
  `),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}
115
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function AA(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Gi(){let t=await cc.readFile($.config(),"utf8");return JSON.parse(t)}async function qu(t){await cc.writeFile($.config(),JSON.stringify(t,null,2)+`
116
- `,{encoding:"utf8",mode:384})}var Qs=K(()=>{"use strict";tt();ms();ye();bi();fa()});async function an(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 Wu(t,n):c}finally{clearTimeout(a)}}async function Yn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await an(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 Gg(t,e=fetch){let n=await an(`${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 an(`${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 uc(t,e=fetch){let n=await an(`${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 fc(t,e,n={},s=fetch){let r=await an(`${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 Vn(t,e,n=fetch){let s=await an(`${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 Xg(t,e,n,s=fetch){let r=await an(`${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 Zg(t,e,n,s=fetch){let r=await an(`${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 ey(t,e,n=fetch){let s=await an(`${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 an(`${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 ny(t,e,n=fetch){let s=await an(`${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 pc(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 Wu,pa=K(()=>{"use strict";Wu=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 zu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function sy(t,e){let n=t??"?",s=zu(e);return s?`${n}${CA}${s}`:n}function ry(t){return t??"?"}function iy(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Ku(e,n)}function Ku(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var CA,Ju=K(()=>{"use strict";CA="\u2022"});function oy(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 eo(t,e=Date.now()){return{session:lt(t.sessionId),upstream:EA(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:PA(t.status,t.busy,t.awaitingInput,TA(t.compactionState),t.forkSynthesisState),agent:ry(t.agentId),model:zu(t.currentModel)??"-",age:MA(t.updatedAt,e),title:t.title??"-",cwd:st(t.cwd),cost:iy(t.currentUsage)}}function TA(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 EA(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function PA(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 to(t,e={}){let n=e.columns??Xi,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]=_A(Zi[r],t.map(i=>i[r]));return s}function MA(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 _A(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Gs(t,e,n,s={}){let r=s.columns??Xi,i=s.cwdMaxWidth??RA,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(hc);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Yu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(hc);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Yu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*hc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(x,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,x)=>{if(v==="cwd")return ha(t[v],S).padEnd(S);let T=$A(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>Yu.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(hc);return b.length>n?b.slice(0,n):b}function $A(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function ha(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,Xi,Yu,Zi,hc,RA,gc=K(()=>{"use strict";Ju();ye();qn();mc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Xi=["session","state","age","cwd","title","agent","cost"],Yu=new Set(["cwd","title"]),Zi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},hc=" ",RA=32});import{spawn as qA}from"child_process";import{Writable as WA}from"stream";function yc(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=zA(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??qA,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}
117
- `)});let c=new WA({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
118
- `)});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 zA(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 Vu=K(()=>{"use strict"});import KA from"chalk";import{highlight as JA,supportsLanguage as wc}from"cli-highlight";import vc from"string-width";function Xs(t,e={}){switch(t.kind){case"user-text":{let n=Qu(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 Qu(t.text," ","agent");case"agent-thought":return Qu(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return gC(t,e.maxPlanItems??hC);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 Gu(t,e){return no(t,e).styled}function no(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<t.length;){let f=t[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&t[u+1]==="*"){let p=t.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=t.slice(u+2,p),m=no(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=t.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${n}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=t.slice(u+1,p),y=t.slice(p+2,h),b=no(m,e),v=c,S=y.startsWith("file://"),x=YA.test(y),T=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(y),F=!S&&!x&&!T;S||F?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let _ of b.links)l.push({start:v+_.start,end:v+_.end,url:_.url});c+=b.cleanLength,(S||x||F)&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function VA(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function wy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function by(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
119
- `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",x,T)=>{let F={prefix:S,body:b,bodyStyle:v};r!==void 0&&(F.prefixStyle=r),x&&x.length>0&&(F.links=x),T&&(F.ansi=!0),c.push(F)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=Sy(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let q=x[1].length,L=x[2]??"",D=s?q===1?"heading-1":q===2?"heading-2":"heading-3":n,X=s?wy(D):o;h(Gu(L,X),D,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&QA(T)&&ma(v).length===ma(T).length){let q=ma(v),L=[],D=b+2;for(;D<d.length&&d[D].includes("|");)L.push(ma(d[D])),D++;let X=sC(q,L,a);for(let ee of X)r!==void 0&&(ee.prefixStyle=r),c.push(ee);b=D-1;continue}let F=v.match(/^(\s*)[-*+]\s+(.*)$/);if(F){let q=F[1]??"",L=F[2]??"",D=no(L,o),X=q.length+2,ee=D.links.map(ae=>({start:ae.start+X,end:ae.end+X,url:ae.url}));h(`${q}\u2022 ${D.styled}`,n,m(),ee,D.ansi);continue}let _=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if(_){let q=_[1]??"",L=_[2]??"",D=_[3]??"",X=no(D,o),ee=q.length+L.length+2,ae=X.links.map(G=>({start:G.start+ee,end:G.end+ee,url:G.url}));h(`${q}${L}. ${X.styled}`,n,m(),ae,X.ansi);continue}let N=v.trim()==="",J=no(v,o);h(J.styled,n,N?" ":m(),J.links,J.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Zs(t,e){return by(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function so(t){return by(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function ma(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 QA(t){if(!t.includes("|"))return!1;let e=ma(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function bc(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return vc(e)}function ZA(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:vc(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:bc(r)}),n=i}return e}function eC(t,e){let n=[],s="",r=0;for(let i of t){let o=vc(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 tC(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=eC(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=vc(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 nC(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,vy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function sC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=bc(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=bc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*vy,n-GA-(s-1)*XA);i=nC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=tC(ZA(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],x=bc(v),T=Gu(v,u);y.push(T+" ".repeat(Math.max(0,S-x)))}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 Sy(t,e){if(t.length===0||!wc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=JA(e.join(`
120
- `),{language:t,theme:rC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
121
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function oC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return wc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return wc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=iC[s];return r&&wc(r)?r:""}function Qu(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
122
- `),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 aC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Qn(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 ky(t){if(t.length<=4096&&t.split(`
115
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function CA(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Gi(){let t=await cc.readFile($.config(),"utf8");return JSON.parse(t)}async function qu(t){await cc.writeFile($.config(),JSON.stringify(t,null,2)+`
116
+ `,{encoding:"utf8",mode:384})}var Qs=K(()=>{"use strict";tt();ms();ye();bi();fa()});async function dn(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 Wu(t,n):c}finally{clearTimeout(a)}}async function Yn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await dn(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 Gg(t,e=fetch){let n=await dn(`${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 dn(`${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 uc(t,e=fetch){let n=await dn(`${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 fc(t,e,n={},s=fetch){let r=await dn(`${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 Vn(t,e,n=fetch){let s=await dn(`${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 Xg(t,e,n,s=fetch){let r=await dn(`${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 Zg(t,e,n,s=fetch){let r=await dn(`${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 ey(t,e,n=fetch){let s=await dn(`${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 dn(`${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 ny(t,e,n=fetch){let s=await dn(`${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 pc(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 Wu,pa=K(()=>{"use strict";Wu=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 zu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function sy(t,e){let n=t??"?",s=zu(e);return s?`${n}${RA}${s}`:n}function ry(t){return t??"?"}function iy(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Ku(e,n)}function Ku(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var RA,Ju=K(()=>{"use strict";RA="\u2022"});function oy(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 eo(t,e=Date.now()){return{session:lt(t.sessionId),upstream:PA(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:MA(t.status,t.busy,t.awaitingInput,EA(t.compactionState),t.forkSynthesisState),agent:ry(t.agentId),model:zu(t.currentModel)??"-",age:_A(t.updatedAt,e),title:t.title??"-",cwd:st(t.cwd),cost:iy(t.currentUsage)}}function EA(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 PA(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function MA(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 to(t,e={}){let n=e.columns??Xi,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]=$A(Zi[r],t.map(i=>i[r]));return s}function _A(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 $A(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Gs(t,e,n,s={}){let r=s.columns??Xi,i=s.cwdMaxWidth??TA,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(hc);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Yu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(hc);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Yu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*hc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(x,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,x)=>{if(v==="cwd")return ha(t[v],S).padEnd(S);let T=FA(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>Yu.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(hc);return b.length>n?b.slice(0,n):b}function FA(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function ha(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,Xi,Yu,Zi,hc,TA,gc=K(()=>{"use strict";Ju();ye();qn();mc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Xi=["session","state","age","cwd","title","agent","cost"],Yu=new Set(["cwd","title"]),Zi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},hc=" ",TA=32});import{spawn as WA}from"child_process";import{Writable as zA}from"stream";function yc(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=KA(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??WA,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}
117
+ `)});let c=new zA({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
118
+ `)});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 KA(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 Vu=K(()=>{"use strict"});import JA from"chalk";import{highlight as YA,supportsLanguage as wc}from"cli-highlight";import vc from"string-width";function Xs(t,e={}){switch(t.kind){case"user-text":{let n=Qu(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 Qu(t.text," ","agent");case"agent-thought":return Qu(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return yC(t,e.maxPlanItems??mC);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 Gu(t,e){return no(t,e).styled}function no(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<t.length;){let f=t[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&t[u+1]==="*"){let p=t.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=t.slice(u+2,p),m=no(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=t.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${n}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=t.slice(u+1,p),y=t.slice(p+2,h),b=no(m,e),v=c,S=y.startsWith("file://"),x=VA.test(y),T=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(y),F=!S&&!x&&!T;S||F?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let _ of b.links)l.push({start:v+_.start,end:v+_.end,url:_.url});c+=b.cleanLength,(S||x||F)&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function QA(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function wy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function by(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
119
+ `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",x,T)=>{let F={prefix:S,body:b,bodyStyle:v};r!==void 0&&(F.prefixStyle=r),x&&x.length>0&&(F.links=x),T&&(F.ansi=!0),c.push(F)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=Sy(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let q=x[1].length,L=x[2]??"",D=s?q===1?"heading-1":q===2?"heading-2":"heading-3":n,X=s?wy(D):o;h(Gu(L,X),D,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&GA(T)&&ma(v).length===ma(T).length){let q=ma(v),L=[],D=b+2;for(;D<d.length&&d[D].includes("|");)L.push(ma(d[D])),D++;let X=rC(q,L,a);for(let ee of X)r!==void 0&&(ee.prefixStyle=r),c.push(ee);b=D-1;continue}let F=v.match(/^(\s*)[-*+]\s+(.*)$/);if(F){let q=F[1]??"",L=F[2]??"",D=no(L,o),X=q.length+2,ee=D.links.map(ae=>({start:ae.start+X,end:ae.end+X,url:ae.url}));h(`${q}\u2022 ${D.styled}`,n,m(),ee,D.ansi);continue}let _=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if(_){let q=_[1]??"",L=_[2]??"",D=_[3]??"",X=no(D,o),ee=q.length+L.length+2,ae=X.links.map(G=>({start:G.start+ee,end:G.end+ee,url:G.url}));h(`${q}${L}. ${X.styled}`,n,m(),ae,X.ansi);continue}let N=v.trim()==="",J=no(v,o);h(J.styled,n,N?" ":m(),J.links,J.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Zs(t,e){return by(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function so(t){return by(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function ma(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 GA(t){if(!t.includes("|"))return!1;let e=ma(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function bc(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return vc(e)}function eC(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:vc(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:bc(r)}),n=i}return e}function tC(t,e){let n=[],s="",r=0;for(let i of t){let o=vc(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 nC(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=tC(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=vc(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 sC(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,vy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function rC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=bc(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=bc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*vy,n-XA-(s-1)*ZA);i=sC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=nC(eC(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],x=bc(v),T=Gu(v,u);y.push(T+" ".repeat(Math.max(0,S-x)))}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 Sy(t,e){if(t.length===0||!wc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=YA(e.join(`
120
+ `),{language:t,theme:iC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
121
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function aC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return wc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return wc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=oC[s];return r&&wc(r)?r:""}function Qu(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
122
+ `),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 dC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Qn(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 ky(t){if(t.length<=4096&&t.split(`
123
123
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
124
124
  `);return i.length>40&&(s=i.slice(0,40).join(`
125
- `),r=!0),{text:s,truncated:r}}function ga(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,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(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 ${Qn(l-t.startedAt)}`}let c={prefix:` ${uC(t.status)} `,prefixStyle:fC(t.status),body:o,bodyStyle:yC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Te(t.errorText),bodyStyle:"tool-status-fail"}),d}function Iy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
125
+ `),r=!0),{text:s,truncated:r}}function ga(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,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(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 ${Qn(l-t.startedAt)}`}let c={prefix:` ${fC(t.status)} `,prefixStyle:pC(t.status),body:o,bodyStyle:wC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Te(t.errorText),bodyStyle:"tool-status-fail"}),d}function Iy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
126
126
  `))e.push({prefix:" ",body:Te(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Te(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
127
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=oC(r);if(i.length>0){let o=Sy(i,s.map(a=>Te(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:Te(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Ay(t){xy=t>=0?t:0}function Xu(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=` (~${aC(d)})`}else{let d=cC(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 ${Te(st(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=Zu(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(...Zs(c)),s.length>0&&s.unshift({body:""}),s}function Cy(t){let e=ht(t.oldText).split(`
127
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=aC(r);if(i.length>0){let o=Sy(i,s.map(a=>Te(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:Te(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Ay(t){xy=t>=0?t:0}function Xu(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=` (~${dC(d)})`}else{let d=lC(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 ${Te(st(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=Zu(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(...Zs(c)),s.length>0&&s.unshift({body:""}),s}function Cy(t){let e=ht(t.oldText).split(`
128
128
  `),n=ht(t.newText).split(`
129
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function cC(t){let{oldLines:e,newLines:n}=Cy(t),s=0,r=0;for(let i of Ry(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function yy(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Zu(t,e={}){let n=e.maxLines??dC,s=e.contextLines??xy,{oldLines:r,newLines:i}=Cy(t),o=Ry(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(yy(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(yy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
130
- `)}function Ry(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(...lC(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 lC(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 ef(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function uC(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 fC(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 Ty(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Zs(t.plan));let n=t.status;if(n!==void 0){let s=pC(n);s!==null&&e.push(s)}return e}function pC(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 mC(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 gC(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}=mC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,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"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Gu(v,VA(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function yC(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 YA,vy,GA,XA,ot,rC,iC,dC,xy,hC,ro=K(()=>{"use strict";ye();Ks();YA=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;vy=6,GA=2,XA=3;ot=new KA.Instance({level:3}),rC={keyword:ot.blueBright,built_in:ot.cyan,type:ot.cyanBright,literal:ot.blue,number:ot.greenBright,string:ot.yellow,regexp:ot.red,comment:ot.gray,function:ot.yellow,title:ot.yellow,class:ot.yellowBright,attr:ot.cyan,attribute:ot.cyan,variable:ot.white,params:ot.white,meta:ot.magenta,symbol:ot.magenta,addition:ot.greenBright,deletion:ot.redBright,section:ot.cyan,tag:ot.cyan,name:ot.cyanBright};iC={".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"};dC=40,xy=Number.POSITIVE_INFINITY;hC=5});import{highlight as wC,supportsLanguage as bC}from"cli-highlight";async function Py(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
129
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function lC(t){let{oldLines:e,newLines:n}=Cy(t),s=0,r=0;for(let i of Ry(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function yy(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Zu(t,e={}){let n=e.maxLines??cC,s=e.contextLines??xy,{oldLines:r,newLines:i}=Cy(t),o=Ry(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(yy(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(yy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
130
+ `)}function Ry(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(...uC(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 uC(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 ef(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function fC(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 pC(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 Ty(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Zs(t.plan));let n=t.status;if(n!==void 0){let s=hC(n);s!==null&&e.push(s)}return e}function hC(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 gC(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 yC(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}=gC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,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"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Gu(v,QA(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function wC(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 VA,vy,XA,ZA,ot,iC,oC,cC,xy,mC,ro=K(()=>{"use strict";ye();Ks();VA=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;vy=6,XA=2,ZA=3;ot=new JA.Instance({level:3}),iC={keyword:ot.blueBright,built_in:ot.cyan,type:ot.cyanBright,literal:ot.blue,number:ot.greenBright,string:ot.yellow,regexp:ot.red,comment:ot.gray,function:ot.yellow,title:ot.yellow,class:ot.yellowBright,attr:ot.cyan,attribute:ot.cyan,variable:ot.white,params:ot.white,meta:ot.magenta,symbol:ot.magenta,addition:ot.greenBright,deletion:ot.redBright,section:ot.cyan,tag:ot.cyan,name:ot.cyanBright};oC={".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"};cC=40,xy=Number.POSITIVE_INFINITY;mC=5});import{highlight as bC,supportsLanguage as vC}from"cli-highlight";async function Py(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
131
131
  `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Me(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Me(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=Cn(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
132
132
  `),process.exit(1)}let u=Di(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:Hi(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
133
133
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
134
134
  `);return}let i=yc({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(tf(r,a)),await i.flush()}function tf(t,e){if(t.length===0)return`No file edits found in this session.
135
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=kC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
136
- `:n.join("")}function vC(t){let e=[];for(let n of t.hunks){let s=Zu(n,{maxLines:1/0});SC(s)&&e.push({body:s,oldCount:Ey(n.oldText),newCount:Ey(n.newText)})}return e}function SC(t){if(t.length===0)return!1;for(let e of t.split(`
137
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function kC(t,e){let n=vC(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(`
135
+ `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=IC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
136
+ `:n.join("")}function SC(t){let e=[];for(let n of t.hunks){let s=Zu(n,{maxLines:1/0});kC(s)&&e.push({body:s,oldCount:Ey(n.oldText),newCount:Ey(n.newText)})}return e}function kC(t){if(t.length===0)return!1;for(let e of t.split(`
137
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function IC(t,e){let n=SC(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(`
138
138
  `)+`
139
139
 
140
- `;return!e||!bC("diff")?i:wC(i,{language:"diff"})}function Ey(t){if(t.length===0)return 0;let e=t.split(`
140
+ `;return!e||!vC("diff")?i:bC(i,{language:"diff"})}function Ey(t){if(t.length===0)return 0;let e=t.split(`
141
141
  `);return e[e.length-1]===""&&e.pop(),e.length}var nf=K(()=>{"use strict";Qs();$r();zd();ro();Vu()});async function My(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
142
142
  `),process.exit(2));let n=await Me(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Me(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=Cn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
143
143
  `),process.exit(1)}let a=of(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Di(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:Hi(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
144
144
  `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=yc({disabled:e.noPager===!0});f.stream.write(Sc(a,e.verbose===!0)),f.stream.write(`
145
- `),f.stream.write(tf(d??[],u)),await f.flush();return}process.stdout.write(Sc(a,e.verbose===!0))}function of(t,e){let n=t.session,s=t.history,r=ym(s),i=fu(s),o=pu(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 Sc(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:")}${xC(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,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,sf),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>sf&&n.push(` ... ${t.tools.length-sf} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>IC.has(l.name)),d=c.reduce((l,u)=>l+u.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 u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}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(`
145
+ `),f.stream.write(tf(d??[],u)),await f.flush();return}process.stdout.write(Sc(a,e.verbose===!0))}function of(t,e){let n=t.session,s=t.history,r=ym(s),i=fu(s),o=pu(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 Sc(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:")}${AC(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,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,sf),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>sf&&n.push(` ... ${t.tools.length-sf} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>xC.has(l.name)),d=c.reduce((l,u)=>l+u.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 u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}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(`
146
146
  `)+`
147
- `}function xC(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 sf,rf,IC,af=K(()=>{"use strict";Qs();$r();hu();zd();Vu();nf();sf=10,rf=15,IC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Qy={};ul(Qy,{assertKnownAgent:()=>xc,resolveAgentIdOrExit:()=>lf,runAgentsAdd:()=>gf,runAgentsInstall:()=>uf,runAgentsList:()=>cf,runAgentsLogs:()=>pf,runAgentsPin:()=>mf,runAgentsRefresh:()=>Ac,runAgentsRemove:()=>yf,runAgentsSet:()=>hf,runAgentsSync:()=>ff,runRegistryPin:()=>Cc});async function cf(){let e=(await Me("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
147
+ `}function AC(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 sf,rf,xC,af=K(()=>{"use strict";Qs();$r();hu();zd();Vu();nf();sf=10,rf=15,xC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Qy={};ul(Qy,{assertKnownAgent:()=>xc,resolveAgentIdOrExit:()=>lf,runAgentsAdd:()=>gf,runAgentsInstall:()=>uf,runAgentsList:()=>cf,runAgentsLogs:()=>pf,runAgentsPin:()=>mf,runAgentsRefresh:()=>Ac,runAgentsRemove:()=>yf,runAgentsSet:()=>hf,runAgentsSync:()=>ff,runRegistryPin:()=>Cc});async function cf(){let e=(await Me("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
148
148
  `);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:vs(s.id,n.map(a=>a.id)),name:vs(s.name,n.map(a=>a.name)),version:vs(s.version,n.map(a=>a.version)),source:vs(s.source,n.map(a=>a.source)),distributions:vs(s.distributions,n.map(a=>a.distributions)),installed:vs(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)+`
149
149
  `);for(let a of n)process.stdout.write(i(a)+`
150
150
  `);let o=e.fetchedAt!==void 0?` (synced ${Qi(e.fetchedAt)})`:"";process.stdout.write(`
@@ -180,97 +180,97 @@ Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
180
180
  `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function yf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
181
181
  `),process.exit(2);return}await gl(t,void 0),process.stdout.write(`Removed local agent ${t}.
182
182
  `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Cc(t){await Pp(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.
183
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function vs(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var wf=K(()=>{"use strict";tt();ye();ua();Qs()});var Rc,Ss,oo,ya,Gy,wa,bf,Tc,Ur,Xy,jr,Zy,qr,ew,Wr,ao,co,tw,lo,nw,sw,rw,vf,iw,Ec,Pc,ba,ow,aw,va=K(()=>{"use strict";Rc="\x1B[?2004h",Ss="\x1B[?2004l",oo="\x1B[200~",ya="\x1B[201~",Gy="\x1B[?1049l",wa="\x1B[?7h",bf="\x1B[?7l",Tc="\x1B[?25h",Ur="\x1B[?1l",Xy="\x1B[>1u",jr="\x1B[<u",Zy="\x1B[>4;2m",qr="\x1B[>4;0m",ew="\x1B[>5;1m",Wr="\x1B[>5;0m",ao="\x1B[?1000l",co="\x1B[?1002l",tw="\x1B[?1003l",lo="\x1B[?1006l",nw="\x1B[?1015l",sw="\x1B[?w",rw="\x1B[=24;1w",vf="\x1B[=0;0w",iw="\x1B]22;pointer\x07",Ec="\x1B]22;default\x07",Pc="\x1B[?1004h",ba="\x1B[?1004l",ow="\x1B[?2026h",aw="\x1B[?2026l"});function Rn(){process.stdout.write(jr),process.stdout.write(Ss),process.stdout.write(qr),process.stdout.write(Wr),process.stdout.write(ao),process.stdout.write(co),process.stdout.write(lo),process.stdout.write(Ur),process.stdout.write("\x1B>")}function Jt(t){return t.width??80}function ks(t){return t.height??24}function Tn(t,e){let n=Jt(t),s=ks(t),r=e.contentWidth??CC,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),u=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f=dw.repeat(a-2),p=MC(f,e.title);t.moveTo(l,u),t.dim.noFormat(RC),_C(t,p),t.dim.noFormat(TC);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(cw),t.moveTo(l+a-1,u+h),t.dim.noFormat(cw);return t.moveTo(l,u+d-1),t.dim.noFormat(EC+dw.repeat(a-2)+PC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function MC(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 _C(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 Ge(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Mc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Gn(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(f,p,h)=>{a||s(f,p,h,u)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),ne({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),ne({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",d),e.on("resize",c)})}var CC,dw,cw,RC,TC,EC,PC,zr=K(()=>{"use strict";Tr();va();CC=64,dw="\u2500",cw="\u2502",RC="\u250C",TC="\u2510",EC="\u2514",PC="\u2518"});function lw(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 OC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??$C,footer:FC};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}] ${lw(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 LC(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 BC(t){return typeof t!="object"||t===null?!1:t.code===W.AuthRequired}function uw(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[Lt];if(!(typeof s!="object"||s===null))return s}function NC(t){let e=uw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function DC(t){let e=uw(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 fw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!BC(e))throw e;let n=NC(e)??t.fallbackAgentId??"",s=DC(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 HC(t,e,n){t.grabInput(!1),ne({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Rn(),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+`
183
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function vs(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var wf=K(()=>{"use strict";tt();ye();ua();Qs()});var Rc,Ss,oo,ya,Gy,wa,bf,Tc,Ur,Xy,jr,Zy,qr,ew,Wr,ao,co,tw,lo,nw,sw,rw,vf,iw,Ec,Pc,ba,ow,aw,va=K(()=>{"use strict";Rc="\x1B[?2004h",Ss="\x1B[?2004l",oo="\x1B[200~",ya="\x1B[201~",Gy="\x1B[?1049l",wa="\x1B[?7h",bf="\x1B[?7l",Tc="\x1B[?25h",Ur="\x1B[?1l",Xy="\x1B[>1u",jr="\x1B[<u",Zy="\x1B[>4;2m",qr="\x1B[>4;0m",ew="\x1B[>5;1m",Wr="\x1B[>5;0m",ao="\x1B[?1000l",co="\x1B[?1002l",tw="\x1B[?1003l",lo="\x1B[?1006l",nw="\x1B[?1015l",sw="\x1B[?w",rw="\x1B[=24;1w",vf="\x1B[=0;0w",iw="\x1B]22;pointer\x07",Ec="\x1B]22;default\x07",Pc="\x1B[?1004h",ba="\x1B[?1004l",ow="\x1B[?2026h",aw="\x1B[?2026l"});function Rn(){process.stdout.write(jr),process.stdout.write(Ss),process.stdout.write(qr),process.stdout.write(Wr),process.stdout.write(ao),process.stdout.write(co),process.stdout.write(lo),process.stdout.write(Ur),process.stdout.write("\x1B>")}function Yt(t){return t.width??80}function ks(t){return t.height??24}function Tn(t,e){let n=Yt(t),s=ks(t),r=e.contentWidth??RC,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),u=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f=dw.repeat(a-2),p=_C(f,e.title);t.moveTo(l,u),t.dim.noFormat(TC),$C(t,p),t.dim.noFormat(EC);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(cw),t.moveTo(l+a-1,u+h),t.dim.noFormat(cw);return t.moveTo(l,u+d-1),t.dim.noFormat(PC+dw.repeat(a-2)+MC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function _C(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 $C(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 Ge(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Mc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Gn(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(f,p,h)=>{a||s(f,p,h,u)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),ne({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),ne({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",d),e.on("resize",c)})}var RC,dw,cw,TC,EC,PC,MC,zr=K(()=>{"use strict";Tr();va();RC=64,dw="\u2500",cw="\u2502",TC="\u250C",EC="\u2510",PC="\u2514",MC="\u2518"});function lw(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 LC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??FC,footer:OC};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}] ${lw(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 BC(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 NC(t){return typeof t!="object"||t===null?!1:t.code===W.AuthRequired}function uw(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[Lt];if(!(typeof s!="object"||s===null))return s}function DC(t){let e=uw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function HC(t){let e=uw(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 fw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!NC(e))throw e;let n=DC(e)??t.fallbackAgentId??"",s=HC(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 UC(t,e,n){t.grabInput(!1),ne({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Rn(),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+`
184
184
  `);let r=n?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{t.grabInput({}),ne({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(`
185
185
  failed to spawn ${e.command}: ${c.message}
186
186
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
187
187
  failed to spawn ${e.command}: ${a.message}
188
- `),i({exitCode:-1})}})}function UC(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 Sf(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(UC(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 pw(t,e,n,s,r){Rn();let i=OC(e,n,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=Tn(t,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(t.moveTo(f.contentX,f.contentY+h),t.brightYellow.noFormat(Ge(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(Ge(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(Ge(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(Ge(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(Ge(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(Ge(i.url,p-7)),h++),i.methodLines){t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" "),t.noFormat(Ge(m.label,p-3)),h++}return h++,t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return Gn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=LC(u,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 ${lw(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>HC(t,v));(async()=>{let v=await Sf(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var $C,FC,kf=K(()=>{"use strict";Tr();od();dd();zr();$C="This agent requires authentication before use.",FC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as ww}from"timers/promises";function QC(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var KC,JC,YC,VC,fo,If=K(()=>{"use strict";fa();qi();KC=200,JC=5e3,YC=2,VC=60,fo=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(()=>{}),ww(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=KC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Nr(s,this.opts.subprotocols);this.bindStream(Jn(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>=VC)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 ww(n),this.destroyed)return;n=Math.min(n*YC,JC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(QC(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}
189
- `)}}});function bw(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 Kr(t){return{outcome:{outcome:"selected",optionId:bw(t,["allow_once","allow_always"])}}}function vw(t){return{outcome:{outcome:"selected",optionId:bw(t,["reject_once","reject_always"])}}}function Fc(t){return t&&typeof t=="object"?t:void 0}function Sa(t){return typeof t=="string"&&t.length>0?t:void 0}function Sw(t){let e=Fc(t),n=Fc(e?.toolCall),s={paths:[]};if(!n)return s;let r=Sa(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Sa(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(Fc(d)?.path);let c=Fc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Sa(c.command);d&&(s.command=d);let l=Sa(c.url);l&&(s.url=l);let u=Sa(c.description);u&&(s.description=u)}return s}function kw(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 Oc=K(()=>{"use strict"});function VR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Uw(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 QR(t,e){let n=Uw(t),s=Uw(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 ka(){if(tr!==void 0)return tr;if(VR())return tr=null,tr;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:jw,version:me}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&QR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}tr={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{}tr=null}}catch{tr=null}return tr}function Ia(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${jw}`}var jw,tr,Cf=K(()=>{"use strict";sn();jw="@hydra-acp/cli"});import*as xa from"fs/promises";import*as Rf from"path";async function Aa(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Rf.resolve(rt(e)),s;try{s=await xa.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 qw(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 xa.stat(r)).isDirectory())return r}catch{}return null}async function Ww(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=Rf.resolve(rt(r)),o;try{o=(await xa.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 Tf=K(()=>{"use strict";tt()});var zw,Kw,Jw,Yw=K(()=>{"use strict";zw="hydra-acp/question/list",Kw="hydra-acp/question/answer",Jw="hydra-acp/question/dismiss"});import{EventEmitter as GR}from"events";import{WebSocket as XR}from"ws";function ZR(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=Do(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 XR(t,e,n),o=()=>{i.off("error",a),s(Jn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Vw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??ZR,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Kt(d),u;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)u=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);u=(await fc(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 f=new Ef(l,d,u,t,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),Vn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[Lt]:{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 Ef,Qw=K(()=>{"use strict";Ho();pa();Pr();qi();Bt();Ef=class extends GR{_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(()=>{}),Vn(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 Pf,Hc,Gw=K(()=>{"use strict";ro();Ks();Pf=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())}},Hc=class extends Pf{_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=Kn(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=so(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=so(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=ga(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=ga(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=Xs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Zs(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")}}});import e0 from"path";function Ca(t){return Xw[e0.extname(t).toLowerCase()]??null}function t0(t){return Ca(t)!==null}function Mf(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(!n0.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 s0(t){return Mf(t)!==null}function bn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Zw(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(!s0(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!t0(o))return null;n.push(o)}return n.length>0?n:null}var Xn,Xw,n0,Uc=K(()=>{"use strict";Xn=10*1024*1024,Xw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};n0=new Set(Object.values(Xw))});import{spawn as r0}from"child_process";import _f from"fs/promises";import i0 from"os";import o0 from"path";async function qc(t={}){let e={...$f,...t};return e.platform==="darwin"?l0(e):e.platform==="linux"?u0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function nb(t={}){let e={...$f,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await mo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await mo(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 Ra(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function sb(t,e={}){let{target:n="both",...s}=e,r={...$f,...s},i=await a0(r,t,n);if(i.ok)return i;let o=d0(r,t,n);return o.ok||o.reason!==rb?o:i}async function a0(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await jc(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 mo(t,"wl-copy")?tb(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await mo(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 jc(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await jc(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await jc(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function d0(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>eb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${eb} 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??c0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:rb}}function c0(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 l0(t){let e=o0.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 ib(t.spawn,"osascript",s);let r=await g0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await _f.unlink(e).catch(()=>{})}try{let r=await Ra(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function u0(t){let e=await f0(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await m0(t,e),s=h0(n);if(s)try{let r=await Ra(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Xn?{ok:!1,reason:`clipboard image is ${bn(r.length)}, max ${bn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Ra(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function f0(t){return t.env.WAYLAND_DISPLAY&&await mo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await mo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function h0(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of p0)if(e.has(n))return n;return null}async function m0(t,e){try{return(await Ra(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
188
+ `),i({exitCode:-1})}})}function jC(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 Sf(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(jC(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 pw(t,e,n,s,r){Rn();let i=LC(e,n,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=Tn(t,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(t.moveTo(f.contentX,f.contentY+h),t.brightYellow.noFormat(Ge(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(Ge(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(Ge(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(Ge(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(Ge(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(Ge(i.url,p-7)),h++),i.methodLines){t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" "),t.noFormat(Ge(m.label,p-3)),h++}return h++,t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return Gn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=BC(u,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 ${lw(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>UC(t,v));(async()=>{let v=await Sf(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var FC,OC,kf=K(()=>{"use strict";Tr();od();dd();zr();FC="This agent requires authentication before use.",OC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as ww}from"timers/promises";function GC(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var JC,YC,VC,QC,fo,If=K(()=>{"use strict";fa();qi();JC=200,YC=5e3,VC=2,QC=60,fo=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(()=>{}),ww(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=JC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Nr(s,this.opts.subprotocols);this.bindStream(Jn(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>=QC)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 ww(n),this.destroyed)return;n=Math.min(n*VC,YC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(GC(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}
189
+ `)}}});function bw(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 Kr(t){return{outcome:{outcome:"selected",optionId:bw(t,["allow_once","allow_always"])}}}function vw(t){return{outcome:{outcome:"selected",optionId:bw(t,["reject_once","reject_always"])}}}function Fc(t){return t&&typeof t=="object"?t:void 0}function Sa(t){return typeof t=="string"&&t.length>0?t:void 0}function Sw(t){let e=Fc(t),n=Fc(e?.toolCall),s={paths:[]};if(!n)return s;let r=Sa(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Sa(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(Fc(d)?.path);let c=Fc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Sa(c.command);d&&(s.command=d);let l=Sa(c.url);l&&(s.url=l);let u=Sa(c.description);u&&(s.description=u)}return s}function kw(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 Oc=K(()=>{"use strict"});function QR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Uw(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 GR(t,e){let n=Uw(t),s=Uw(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 ka(){if(tr!==void 0)return tr;if(QR())return tr=null,tr;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:jw,version:me}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&GR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}tr={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{}tr=null}}catch{tr=null}return tr}function Ia(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${jw}`}var jw,tr,Cf=K(()=>{"use strict";rn();jw="@hydra-acp/cli"});import*as xa from"fs/promises";import*as Rf from"path";async function Aa(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Rf.resolve(rt(e)),s;try{s=await xa.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 qw(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 xa.stat(r)).isDirectory())return r}catch{}return null}async function Ww(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=Rf.resolve(rt(r)),o;try{o=(await xa.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 Tf=K(()=>{"use strict";tt()});var zw,Kw,Jw,Yw=K(()=>{"use strict";zw="hydra-acp/question/list",Kw="hydra-acp/question/answer",Jw="hydra-acp/question/dismiss"});import{EventEmitter as XR}from"events";import{WebSocket as ZR}from"ws";function e0(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=Do(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 ZR(t,e,n),o=()=>{i.off("error",a),s(Jn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Vw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??e0,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Jt(d),u;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)u=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);u=(await fc(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 f=new Ef(l,d,u,t,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),Vn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[Lt]:{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 Ef,Qw=K(()=>{"use strict";Ho();pa();Pr();qi();Bt();Ef=class extends XR{_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(()=>{}),Vn(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 Pf,Hc,Gw=K(()=>{"use strict";ro();Ks();Pf=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())}},Hc=class extends Pf{_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=Kn(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=so(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=so(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=ga(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=ga(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=Xs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Zs(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")}}});import t0 from"path";function Ca(t){return Xw[t0.extname(t).toLowerCase()]??null}function n0(t){return Ca(t)!==null}function Mf(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(!s0.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 r0(t){return Mf(t)!==null}function bn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Zw(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(!r0(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!n0(o))return null;n.push(o)}return n.length>0?n:null}var Xn,Xw,s0,Uc=K(()=>{"use strict";Xn=10*1024*1024,Xw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};s0=new Set(Object.values(Xw))});import{spawn as i0}from"child_process";import _f from"fs/promises";import o0 from"os";import a0 from"path";async function qc(t={}){let e={...$f,...t};return e.platform==="darwin"?u0(e):e.platform==="linux"?f0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function nb(t={}){let e={...$f,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await mo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await mo(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 Ra(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function sb(t,e={}){let{target:n="both",...s}=e,r={...$f,...s},i=await d0(r,t,n);if(i.ok)return i;let o=c0(r,t,n);return o.ok||o.reason!==rb?o:i}async function d0(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await jc(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 mo(t,"wl-copy")?tb(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await mo(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 jc(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await jc(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await jc(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function c0(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>eb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${eb} 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??l0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:rb}}function l0(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 u0(t){let e=a0.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 ib(t.spawn,"osascript",s);let r=await y0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await _f.unlink(e).catch(()=>{})}try{let r=await Ra(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function f0(t){let e=await p0(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await g0(t,e),s=m0(n);if(s)try{let r=await Ra(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Xn?{ok:!1,reason:`clipboard image is ${bn(r.length)}, max ${bn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Ra(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ff(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function p0(t){return t.env.WAYLAND_DISPLAY&&await mo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await mo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function m0(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of h0)if(e.has(n))return n;return null}async function g0(t,e){try{return(await Ra(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
190
190
  `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Ff(t){return t.replace(/\r\n?/g,`
191
- `)}async function mo(t,e){try{return await ib(t.spawn,"which",[e]),!0}catch{return!1}}async function g0(t,e){try{let n=await _f.readFile(t);return e&&await _f.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Xn?{ok:!1,reason:`clipboard image is ${bn(n.length)}, max ${bn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ca(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function ib(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 jc(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 Ra(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",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var $f,eb,rb,p0,Wc=K(()=>{"use strict";Uc();$f={platform:process.platform,env:process.env,spawn:r0,tmpdir:i0.tmpdir};eb=74994;rb="no TTY available for OSC 52 clipboard write";p0=["image/png","image/jpeg","image/gif","image/webp"]});function w0(t,e){return`[pasted #${t} +${e} lines]`}var y0,zc,Of,b0,Is,Lf=K(()=>{"use strict";y0=/\[pasted #(\d+) \+\d+ lines\]/g,zc=/\[pasted #(\d+) \+\d+ lines\]$/,Of=/^\[pasted #(\d+) \+\d+ lines\]/;b0=500,Is=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>b0&&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(`
192
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(w0(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"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(`
193
- `)}expandPastes(e){return e.replace(y0,(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(`
191
+ `)}async function mo(t,e){try{return await ib(t.spawn,"which",[e]),!0}catch{return!1}}async function y0(t,e){try{let n=await _f.readFile(t);return e&&await _f.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Xn?{ok:!1,reason:`clipboard image is ${bn(n.length)}, max ${bn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ca(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function ib(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 jc(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 Ra(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",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var $f,eb,rb,h0,Wc=K(()=>{"use strict";Uc();$f={platform:process.platform,env:process.env,spawn:i0,tmpdir:o0.tmpdir};eb=74994;rb="no TTY available for OSC 52 clipboard write";h0=["image/png","image/jpeg","image/gif","image/webp"]});function b0(t,e){return`[pasted #${t} +${e} lines]`}var w0,zc,Of,v0,Is,Lf=K(()=>{"use strict";w0=/\[pasted #(\d+) \+\d+ lines\]/g,zc=/\[pasted #(\d+) \+\d+ lines\]$/,Of=/^\[pasted #(\d+) \+\d+ lines\]/;v0=500,Is=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>v0&&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(`
192
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(b0(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"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(`
193
+ `)}expandPastes(e){return e.replace(w0,(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(`
194
194
  `)){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(`
195
195
  `);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(zc);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(Of);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=`
196
196
  `,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+`
197
197
  `,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=`
198
198
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
199
199
  `+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(zc);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(zc);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(Of);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(zc);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(Of);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(`
200
- `),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 go,Kc,Bf=K(()=>{"use strict";go=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())}},Kc=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 v0 from"string-width";function ob(t,e){if(!t||e<=0)return 0;let n=0;for(let s of S0.segment(t)){let r=v0(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function ab(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 S0,db=K(()=>{"use strict";S0=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function k0(){Ta===0&&process.stdout.write(ow),Ta++}function I0(){Ta!==0&&(Ta--,Ta===0&&process.stdout.write(aw))}function Le(t){k0();try{t()}finally{I0()}}var Ta,Nf=K(()=>{"use strict";va();Ta=0});import{spawn as x0}from"child_process";import{statSync as A0}from"fs";import{homedir as cb}from"os";import{isAbsolute as lb,resolve as C0}from"path";import ze from"string-width";import R0 from"wrap-ansi";function O0(t){let e=t.replace(/\r\n?$|\n$/,"");return F0.test(e)?e:null}function L0(t,e){return!t||typeof t!="object"?!1:t[e]===!0}function B0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function N0(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 es(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 xs(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 mb(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Zn(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Zn(t,e.slice(c),n,o);return}d>c&&Zn(t,e.slice(c,d),n,o);let l=r!==null&&d===r;Zn(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function yo(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function Jf(t){return t.ansi===!0&&!yo(t.bodyStyle)}function Zn(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 D0(t,e){return e<=0?[t]:t.length===0?[""]:R0(t,e,{hard:!0,trim:!1}).split(`
201
- `)}function xb(t){Ib=t}function Ab(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 nr(t){return ze(t,{ambiguousIsNarrow:!Ib})}function U0(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 wo(t,e){if(t.charCodeAt(e)===27){let s=U0(t,e);return s===null?null:{text:s,width:0}}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 H0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Yf(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=wo(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 gb(t){if(!t.includes("^")&&!t.includes("\x1B"))return t;let e="",n=0;for(;n<t.length;){let s=wo(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function j0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=wo(t,n);if(s){s.width===0&&s.text.charCodeAt(0)===94&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function Cb(t){if(!t.includes("^")&&!t.includes("\x1B"))return!1;for(let e=0;e<t.length;e++)if(wo(t,e))return!0;return!1}function yb(t,e){let n=t.indexOf("^",e),s=t.indexOf("\x1B",e);return n===-1?s:s===-1?n:Math.min(n,s)}function*Qf(t){let e=0;for(;e<t.length;){let n=wo(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=yb(t,e);for(;r!==-1&&r<t.length;){if(wo(t,r)){s=r;break}r=yb(t,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Vf.segment(t.slice(e,s)))yield{text:i,width:nr(i)};e=s}}function q0(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 W0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Cb(t);return!s&&!kb.test(t)?z0(t,e):K0(t,e,s)}function z0(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 K0(t,e,n){let s=[],r=n?[...Qf(t)]:J0(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 J0(t){let e=[];for(let{segment:n}of Vf.segment(t))e.push({text:n,width:nr(n)});return e}function Tt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Cb(t);if(!s&&t.length<=e&&!kb.test(t))return t;if(!s)return nr(t)<=e?t:e<=1?wb(t,e):wb(t,e-1)+"\u2026";let r=[...Qf(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?bb(r,e):bb(r,e-1)+"\u2026"}function wb(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Vf.segment(t)){let i=nr(r);if(s+i>e)break;n+=r,s+=i}return n}function bb(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 Y0(t){let e=t.indexOf(`
202
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function vb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Vc(t.used)}/${Vc(t.size)}`):e.push(Vc(t.used)):typeof t.size=="number"&&e.push(`/${Vc(t.size)}`),typeof t.costAmount=="number"&&e.push(Ku(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Vc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Gc(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_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 Yr(){let t=[ao,co,tw,lo,nw,vf,Ss,qr,Wr,jr,Ur,"\x1B>",wa,Tc,Ec,"\x1B]9;4;0\x07",Gy].join("");try{process.stdout.write(t)}catch{}}function Rb(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 Sb(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===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 Df,Jc,Hf,Uf,ub,fb,pb,We,Xe,T0,Ze,jf,qf,E0,P0,M0,Wf,zf,Kf,_0,$0,F0,Qc,kb,Vf,Ib,H0,Yc,Gf=K(()=>{"use strict";Bf();Ju();ye();qn();Uc();ro();db();Wc();Nf();Tr();va();Df=500,Jc=1,Hf=/[A-Za-z0-9_]/,Uf=/[A-Za-z0-9_./\-~+@]/,ub=/\x1b\[[0-9;]*[A-Za-z]/g,fb=/\x1b\]8;[^;]*;[^\x1b\x07]*(?:\x1b\\|\x07)/g,pb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,We=1,Xe=0,T0=1,Ze=1,jf=8,qf=5,E0=12,P0=12,M0=30,Wf=6,zf=4,Kf=2,_0=1e3,$0=1e4,F0=/^(https?|ftp):\/\/\S+$/;Qc=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;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??_0,this.painter=new go(this.term),this.scheduler=new Kc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??$0,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(bf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),ne({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),ne({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Ec),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(wa),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Yr(),this.term.fullscreen(!1),this.term(`
200
+ `),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 go,Kc,Bf=K(()=>{"use strict";go=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())}},Kc=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 S0 from"string-width";function ob(t,e){if(!t||e<=0)return 0;let n=0;for(let s of k0.segment(t)){let r=S0(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function ab(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 k0,db=K(()=>{"use strict";k0=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function I0(){Ta===0&&process.stdout.write(ow),Ta++}function x0(){Ta!==0&&(Ta--,Ta===0&&process.stdout.write(aw))}function Le(t){I0();try{t()}finally{x0()}}var Ta,Nf=K(()=>{"use strict";va();Ta=0});import{spawn as A0}from"child_process";import{statSync as cb}from"fs";import{homedir as lb}from"os";import{isAbsolute as ub,resolve as C0}from"path";import ze from"string-width";import R0 from"wrap-ansi";function L0(t){let e=t.replace(/\r\n?$|\n$/,"");return O0.test(e)?e:null}function B0(t,e){return!t||typeof t!="object"?!1:t[e]===!0}function N0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function D0(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 mb(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 es(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 xs(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 gb(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Zn(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Zn(t,e.slice(c),n,o);return}d>c&&Zn(t,e.slice(c,d),n,o);let l=r!==null&&d===r;Zn(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function yo(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function Jf(t){return t.ansi===!0&&!yo(t.bodyStyle)}function Zn(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 H0(t,e){return e<=0?[t]:t.length===0?[""]:R0(t,e,{hard:!0,trim:!1}).split(`
201
+ `)}function Ab(t){xb=t}function Cb(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 nr(t){return ze(t,{ambiguousIsNarrow:!xb})}function j0(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 wo(t,e){if(t.charCodeAt(e)===27){let s=j0(t,e);return s===null?null:{text:s,width:0}}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 U0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Yf(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=wo(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 yb(t){if(!t.includes("^")&&!t.includes("\x1B"))return t;let e="",n=0;for(;n<t.length;){let s=wo(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function q0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=wo(t,n);if(s){s.width===0&&s.text.charCodeAt(0)===94&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function Rb(t){if(!t.includes("^")&&!t.includes("\x1B"))return!1;for(let e=0;e<t.length;e++)if(wo(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*Qf(t){let e=0;for(;e<t.length;){let n=wo(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(wo(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 Vf.segment(t.slice(e,s)))yield{text:i,width:nr(i)};e=s}}function W0(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 z0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Rb(t);return!s&&!Ib.test(t)?K0(t,e):J0(t,e,s)}function K0(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 J0(t,e,n){let s=[],r=n?[...Qf(t)]:Y0(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 Y0(t){let e=[];for(let{segment:n}of Vf.segment(t))e.push({text:n,width:nr(n)});return e}function Tt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Rb(t);if(!s&&t.length<=e&&!Ib.test(t))return t;if(!s)return nr(t)<=e?t:e<=1?bb(t,e):bb(t,e-1)+"\u2026";let r=[...Qf(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?vb(r,e):vb(r,e-1)+"\u2026"}function bb(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Vf.segment(t)){let i=nr(r);if(s+i>e)break;n+=r,s+=i}return n}function vb(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 V0(t){let e=t.indexOf(`
202
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Sb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Vc(t.used)}/${Vc(t.size)}`):e.push(Vc(t.used)):typeof t.size=="number"&&e.push(`/${Vc(t.size)}`),typeof t.costAmount=="number"&&e.push(Ku(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Vc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Gc(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_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 Yr(){let t=[ao,co,tw,lo,nw,vf,Ss,qr,Wr,jr,Ur,"\x1B>",wa,Tc,Ec,"\x1B]9;4;0\x07",Gy].join("");try{process.stdout.write(t)}catch{}}function Tb(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 kb(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===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 Df,Jc,Hf,Uf,fb,pb,hb,T0,We,Xe,E0,Ze,jf,qf,P0,M0,_0,Wf,zf,Kf,$0,F0,O0,Qc,Ib,Vf,xb,U0,Yc,Gf=K(()=>{"use strict";Bf();Ju();ye();qn();Uc();ro();db();Wc();Nf();Tr();va();Df=500,Jc=1,Hf=/[A-Za-z0-9_]/,Uf=/[A-Za-z0-9_./\-~+@]/,fb=/\x1b\[[0-9;]*[A-Za-z]/g,pb=/\x1b\]8;[^;]*;[^\x1b\x07]*(?:\x1b\\|\x07)/g,hb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,T0=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,We=1,Xe=0,E0=1,Ze=1,jf=8,qf=5,P0=12,M0=12,_0=30,Wf=6,zf=4,Kf=2,$0=1e3,F0=1e4,O0=/^(https?|ftp):\/\/\S+$/;Qc=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;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??$0,this.painter=new go(this.term),this.scheduler=new Kc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??F0,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(bf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),ne({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),ne({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Ec),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(wa),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Yr(),this.term.fullscreen(!1),this.term(`
203
203
  `)))}installBracketedPaste(){process.stdout.write(Rc),process.stdout.write(Zy),process.stdout.write(ew),process.stdout.write(Xy),process.stdout.write(Pc);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(Ss),process.stdout.write(qr),process.stdout.write(Wr),process.stdout.write(jr),process.stdout.write(ba),process.stdout.write(Ur),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(sw),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(vf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Yr(),this.onProcessSignal=e=>{Yr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Yr(),process.stderr.write(`
204
204
  uncaught: ${e.stack??e.message}
205
205
  `),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(rw),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.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(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(oo)){this.handleRawStdinSegment(n);return}if(n.includes(`
206
206
  `)){let s=n.split(`
207
- `);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=Sb(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=Sb(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=oo,s=ya;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,`
208
- `);this.pasteBuffer="";let a=Zw(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=O0(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),u=[];for(let f=0;f<n.length;f++){let p=d[f],h=n[f];p!==void 0&&N0(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=n.length;f<d.length;f++)u.push(d[f]);this.lines.splice(s.start,s.count,...l);for(let f of u)this.forgetLine(f);for(let f of l)this.lineIds.has(f)||this.trackLine(f);if(this.invalidateSelectionIfTouches(u),s.count=n.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==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(`
209
- `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),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 u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}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=Yc(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)),ne({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=(u,f,p,h)=>u!==p?u-p:f-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 a=r.body??"",c;Jf(r)?c=a.replace(ub,"").replace(fb,""):(c=a.slice(o.start,o.end),yo(r.bodyStyle)&&(c=gb(c))),n.push(c)}return n.join(`
210
- `)}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 u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{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=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:Jf(e)?{start:0,end:e.body.length,toEndOfLine:!0}:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}: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,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=c&&u.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(bf),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(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=Gc(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=B0(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 u=this.nearestKeyAboveRow(o.y),f=this.nearestKeyBelowRow(o.y);u!==null&&f!==null&&this.hoveredRunKeys.has(u)&&this.hoveredRunKeys.has(f)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??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)<=Jc&&Math.abs(o.y-d.y)<=Jc&&Date.now()-d.t<=Df||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,L0(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 u=this.btwHeaderSidRegion();if(u!==null&&this.onHydraLinkClick&&o.y===u.row&&o.x>=u.colStart&&o.x<=u.colEnd)this.onHydraLinkClick(u.sessionId);else if(this.onBlockClick){let f=this.keyAtRow(o.y);if(f!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===f;)p-=1;this.schedulePendingBlockClick(f,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!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;if(i!==null&&r-i.t<=Df&&Math.abs(e.x-i.x)<=Jc&&Math.abs(e.y-i.y)<=Jc){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let c=this.keyAtRow(e.y);if(c!==null){let d=e.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;let l=e.y-d;if(this.onBlockDoubleClick(c,l)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let c=this.findLinkUrlAt(s);if(c!==null&&pb.test(c)){let l=c.match(pb)?.[1]??null;if(l&&this.onHydraLinkClick(l)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let a=this.wordBoundsAt(s);a!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:a.start},{sourceLineId:s.sourceLineId,offset:a.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}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(),u=this.scrollOffset>0,f=d<c;if(d===0&&l||f){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&&u){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&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Yf(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),!Hf.test(r[a]))return null;let c=a;for(;c>0&&Hf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Hf.test(r[d]);)d++;let l=s.length,u=s.length;for(let f=0;f<i.length;f++)if(i[f]===c&&l===s.length&&(l=f),i[f]===d&&u===s.length){u=f;break}return{start:l,end:u}}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}=Yf(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,b=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return b&&(m=b[1],y=Number.parseInt(b[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),!Uf.test(r[a]))return null;let c=a;for(;c>0&&Uf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Uf.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}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}=Yf(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==="~"?cb():`${cb()}/${n.slice(2)}`);let s=lb(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=lb(n)?n:C0(this.sessionbar.cwd,n);if(s)return i;try{if(A0(i).isFile())return i}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)}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 u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=x0(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.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)},Df);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&&sb(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"?iw:Ec))}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),u=i-l;return u<0||u>=d.length?null:d[u]?.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),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.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),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=nr(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=yo(p.bodyStyle)?ab(Qf(p.body),y):ob(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+b}}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=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=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()-We-Ze-Xe-T0-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-Xe-Ze-We;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-We),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=sy(this.sessionbar.agent,this.sessionbar.model),i=st(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=ze(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=ze(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=Tt(i,f),m=s?Tt(s,p):"",y=ze(h)+(s?u+ze(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=Yc(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?Qn(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=vb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+ze(o)+ze(u)+f.length+ze(s);for(let T of c)y+=ze(" \xB7 ")+ze(T.text);y+=ze(p);let b=ze(h)+ze(d)+ze(m),v=Math.max(0,n-y-b),S="\u2500".repeat(v),x=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,x,()=>{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),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.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=ze(i)+ze(a)+ze(o),d=Math.max(0,n-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;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 b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+ze(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=ze(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+ze(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Yc(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=vb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+ze(n)+i.length+ze(r)+o.length+ze(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-Xe-Ze-We,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=Yc(this.btwOverlaySessionId),u=1+c.length+ze(a)+" \xB7 ".length,f=u+ze(d)-1;return{row:o,colStart:u,colEnd:f,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(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let f=-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))||(f===-1&&(f=h),p=h)}for(let h=0;h<s;h++){let m=n+h,y=h-d,b=y>=0?c[y]:void 0,v=this.activeMatchCol(b,l),S=b?this.selectionRangeForChunk(b):null,x=b!==void 0&&b.blockKey!==void 0&&(b.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(b.blockKey)),T=b!==void 0&&b.blockKey===void 0&&f!==-1&&y>=f&&y<=p,F=x||T,_=this.terminalFocused&&F&&(this.hoveredSubKey===null||(b.hoverSubKey??null)===this.hoveredSubKey),N=hb("sb",e,b,this.scrollbackHighlight,v,S)+(_?"|H":"");this.paintRow(m,N,()=>{b&&this.writeFormattedLine(b,e,v,u,S,_)})}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(qf,this.queuedTexts.length)}chipRows(){return Math.min(zf,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(Wf,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-We-Ze-Xe,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 u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>Wf,h=this.completions.length-Wf+1,m=f?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?Tt(b,v):"";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-We-Ze-Xe-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>zf,u=this.attachments.length-zf,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${bn(f.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(q0(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-We-Ze-Xe,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,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>qf,p=this.queuedTexts.length-qf,h=u===void 0?"":f?`+ ${p+1} more queued`:Tt(Y0(u),n-4),m=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,n-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}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=es(s.buffer,n),i=xs(r,s,jf),o=this.term.height-i.rendered-Xe-Ze-We+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Kf-Xe-Ze-We+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${Tt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${Tt(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-Xe-Ze-We+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(` ${Tt(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,u=` ${d?"\u276F":" "} ${a+1}. ${Tt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}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-Xe-Ze-We+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 ${Tt(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,u=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${Tt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${Tt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(M0,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-Xe-Ze-We+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} ${Tt(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(` ${Tt(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,f=` ${l?"\u276F":" "} ${c+1}. ${Tt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}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-Xe-Ze-We;this.drawSeparator(s),this.drawBottomSeparator(e-We)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Xe-Ze-We+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Xe-Ze-We+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Kf-Xe-Ze-We+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Xe-Ze-We+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Xe-Ze-We+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=es(s.buffer,n),i=xs(r,s,jf),a=this.term.height-i.rendered-Xe-Ze-We+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Xe-Ze-We;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 Kf;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=es(s.buffer,n);return Math.min(jf,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(E0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(P0,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-Xe-Ze-We+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 ${Tt(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 u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${Tt(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?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()-Xe-Ze-We,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 u=this.wrapBtwTail(n,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=hb(`btw|c${f}`,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 u of this.lines)s(u)||d.push(u);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 u=this.wrapOne(l,e);if(r.push(u),i+=u.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 u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=nr(r),o=Math.max(1,n-i-1),a=yo(e.bodyStyle),c=e.ansi?D0(e.body,o):W0(e.body,o,{stripMarkup:a}),d=[],l=0;for(let u=0;u<c.length;u++){let f=c[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(p.hoverSubKey=e.hoverSubKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let h=e.body.indexOf(f,l),m=h===-1?l:h;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:m}),l=m+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&Zn(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-nr(e.prefix??"")),c=yo(e.bodyStyle),d=e.ansi?e.body:Tt(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;mb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Zn(this.term,u,e.bodyStyle,o)};if(i!==null&&Jf(e)){let u=d.replace(ub,"").replace(fb,"");Zn(this.term,u,"selection-highlight",o)}else if(i!==null){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=yo(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=gb(m)),Zn(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=j0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?mb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Zn(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?ze(d):nr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Zn(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};kb=/[^\x20-\x7e]/,Vf=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ib=!1;H0=/[a-zA-Z+\-:_!#/]/;Yc=lt});function V0(t,e,n=Xc){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 Tb(t,e){Rn();let n=lt(e.sessionId),s=e.importedFromMachine??"another machine",r=st(e.cwd),i=Xc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Xc.length*2+2,d=Tn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(d.contentX,d.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(Ge(p.value,l-p.label.length-2)),f++;return f++,Eb(t,d,f,{intro:"What do you want to do?",choices:Xc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Gn({term:t,render:o,onKey:(a,c,d,l)=>{let u=Q0(a,d);if(!u)return;let f=V0(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function Eb(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(Mc(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 Q0(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 Pb(t,e,n){let s=lt(e.sessionId),r=e.title??st(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=Tn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Ge(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+Ge(r,d-2)),l++,l++,Eb(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},u=p=>{l(),n.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var Xc,Xf=K(()=>{"use strict";ye();qn();zr();Xc=[{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 Pa(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 Mb(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=Pa(e);return o.length<=r.length?null:o+i}var Zc=K(()=>{"use strict"});var bo,Zf=K(()=>{"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)}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"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as _b from"os";async function Qr(t,e,n={}){let s=n.defaultCwd??(e?await qw(e.cwd):void 0)??_b.homedir();Rn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:lt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:st(e.cwd)}]:[],a=new bo(s),c=null,d=!1,l=null,u=()=>{let y=o.length+6;l=Tn(t,{contentHeight:y,title:r});let b=l.contentW,v=0;for(let S of o)t.moveTo(l.contentX,l.contentY+v),t.dim.noFormat(` ${S.label}`),t.noFormat(Ge(S.value,b-S.label.length-2)),v++;v++,t.moveTo(l.contentX,l.contentY+v),t.noFormat(` ${i}`),v+=2,h(v),v+=2,c!==null?(t.moveTo(l.contentX,l.contentY+v),t.red.noFormat(` ${Ge(c,b-2)}`)):(t.moveTo(l.contentX,l.contentY+v),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},f=()=>o.length+3,p=0,h=y=>{if(!l)return;let b=y??f();t.moveTo(l.contentX,l.contentY+b).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+b),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+b),t.bold.noFormat(" cwd: ");let S=Math.max(1,l.contentW-6-2),x=a.text,T=a.cursor;T<p&&(p=T),T-p>=S&&(p=T-S+1),p<0&&(p=0);let F=x.slice(p,p+S);p>0&&F.length>0&&(F="\u2026"+F.slice(1));let _=T-p;if(d){t.noFormat(F);return}_>=F.length?(t.noFormat(F),t.bgWhite(" ")):(t.noFormat(F.slice(0,_)),t.bgWhite.noFormat(F[_]??" "),t.noFormat(F.slice(_+1)))},m=()=>{if(h(),!l)return;let y=f()+2;t.moveTo(l.contentX,l.contentY+y).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+y),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+y),c!==null?t.red.noFormat(` ${Ge(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Gn({term:t,render:u,onKey:(y,b,v,S)=>{if(!d){if(y==="ENTER"||y==="KP_ENTER"){let x=a.text;d=!0,c=null,m(),Aa(x).then(T=>{if(d=!1,T.ok){S({kind:"ok",path:T.path});return}c=T.reason,m()});return}if(y==="ESCAPE"){S({kind:"back"});return}if(y==="CTRL_C"||y==="CTRL_D"){S({kind:"cancel"});return}if(y==="TAB"){d=!0,Ww(a.text).then(x=>{if(d=!1,x.matches.length===0)return;let T;if(x.matches.length===1)T=x.prefix+x.matches[0];else{let F=Pa(x.matches);if(F.length<=x.basePrefix.length)return;T=x.prefix+F}T!==a.text&&(a.setText(T,{recordUndo:!0}),c=null,m())});return}if(a.handleKey(y,v?.isCharacter===!0)){c=null,m();return}}}})}var ep=K(()=>{"use strict";ye();qn();Tf();Zc();zr();Zf()});import*as Fb from"fs";import*as Ob from"os";import*as el from"path";function tl(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 G0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function X0(t){return t.replace(/\\ /g," ")}function $b(t){return t.replace(/ /g,"\\ ")}function Z0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function eT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Ob.homedir()+n.slice(1)),el.isAbsolute(n)?n:el.resolve(e,n)}function tT(t){let e;try{e=Fb.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function nl(t,e,n=tT){if(!G0(t))return null;let s=X0(t),{dirPrefix:r,base:i}=Z0(s),o=eT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:$b(r+p),candidates:l}}let u=Pa(d.map(f=>f.name));return{replacement:$b(r+u),candidates:l}}var tp=K(()=>{"use strict";Zc()});function sp(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function rp(t,e){let n=()=>{process.stdout.write(jr),process.stdout.write(Ss),process.stdout.write(qr),process.stdout.write(Wr),process.stdout.write(ao),process.stdout.write(co),process.stdout.write(lo),process.stdout.write(Ur),process.stdout.write("\x1B>")};n();let s=e.prefs??sp();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(E=>E.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=sl(e.sessions,r),o=R=>{let E=R;return s.filters.cwdOnly&&(E=E.filter(B=>B.cwd===r)),s.filters.includeNonInteractive||(E=E.filter(B=>B.interactive===!0)),E=oT(E,s.filters.hostFilter),E},a=o(i),c={columns:e.config.tui.sessionColumns??Xi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>eo(R,Date.now())),l=to(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(E=>E.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",x=null,T=!1,F="input",_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,D=null,X=!1,ee=null,ae=null,G=null,fe=()=>{if(h){let R=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${R} \xB7 ^c clears`,render:()=>{t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" "),t.dim.noFormat(` ${R} \xB7 ^c clears`)}}}return G!==null?{plain:G,render:()=>{t.dim.noFormat(` ${G}`)}}:null},Ve=!1,Be=new Is({history:[]});if(e.initialPrompt&&Be.setBuffer(e.initialPrompt),e.initialAttachments)for(let R of e.initialAttachments)Be.addAttachment(R);let ns=e.config.tui.promptHistoryMaxEntries;Qo($.globalTuiHistoryFile()).then(R=>{let E=R.length>ns?R.slice(R.length-ns):R;Be.setHistory(E)}).catch(()=>{});let ve=new go(t),Y=ks(t),Se=Jt(t),De=0,Yt="",As=0,dn=[],mt=1,Cs=0,Rs=0,ss=0,Xr="",vo=[],rs=1,Oa=0,So=[],pe=1,Ts=0,La=0,Zr=0,ei=()=>{Y=ks(t),Se=Jt(t);let R=Math.max(10,Se-np-1);As=Math.max(10,Se-Lb);let E=Math.max(10,Se-8),B=Be.state().attachments.length,Q=B>0?` \xB7 \u{1F4CE}\xD7${B}`:"",oe=Math.max(10,E-Q.length);Yt=iT(r,oe)+Q;let re=Be.state();dn=es(re.buffer,As);let Ee=xs(dn,re,Ma);mt=Ee.rendered,Cs=Ee.windowStart,Rs=Ee.cursorVisualRow,ss=Ee.cursorVisualCol;let Qe=6+mt,Ue=Math.max(3,Y-Qe);De=Math.min(a.length,Ue),Xr=Gs(Zi,l,R,c).padEnd(R),vo=d.map(nt=>Gs(nt,l,R,c).padEnd(R))},ti=()=>{d=a.map(R=>eo(R,Date.now())),l=to(d,c),u=1+a.length,ei()},Dt=()=>{let R=o(i);h&&m.length>0?a=R.filter(E=>aT(E,m)):a=R,ti(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+De>a.length&&(p=Math.max(0,a.length-De)),vn()},is=R=>{if(R!==void 0){let E=a.findIndex(B=>B.sessionId===R);if(E>=0){f=E+1,vn();return}}f=a.length>0?1:0,p=0,vn()},vn=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+De?p=R-De+1:p+De>a.length&&(p=Math.max(0,a.length-De))},we=()=>Math.max(2,Se-3),et=!1,Ke=!0,gt=!1,Es=[],ni=()=>{let R=we(),E=`\u2500 ${Yt} `,B=Math.max(1,R-E.length),Q="\u2500".repeat(B);(f===0||et)&&Ke?t.brightBlue.noFormat(`\u256D${E}${Q}\u256E`):t.dim.noFormat(`\u256D${E}${Q}\u256E`)},rr=()=>{let R=we(),E="\u2500".repeat(R);(f===0||et)&&Ke?t.brightBlue.noFormat(`\u2570${E}\u256F`):t.dim.noFormat(`\u2570${E}\u256F`)},si=()=>{let R=fe();if(R===null)return;let E=Math.max(0,Jt(t)-2);if(R.plain.length>E){let B=R.plain.slice(0,Math.max(0,E-1))+"\u2026";t.dim.noFormat(` ${B}`);return}R.render()},ri=R=>{let E=dn[R];return E?(Be.state().buffer[E.bufferIdx]??"").slice(E.startCol,E.endCol):""},ir=R=>{let E=we(),B=ri(R),Q=Math.max(0,E-1-B.length),oe=" ".repeat(Q);(f===0||et)&&Ke?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${B}${oe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${B}${oe}`),t.dim.noFormat("\u2502"))},En=R=>{let E=vo[R]??"",B=a[R],Q=B&&B.priority&&B.priority>0?"* ":" ";f===R+1&&!et&&Ke?t.brightWhite.bgBlue.noFormat(`${Q}${E}`):t.noFormat(`${Q}${E}`)},ii=()=>{let R=p,E=Math.max(0,a.length-p-De),B=[];if(s.filters.cwdOnly&&B.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;B.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&B.push({kind:"plain",text:"+non-interactive"}),R>0&&B.push({kind:"plain",text:`\u2191 ${R} above`}),E>0&&B.push({kind:"plain",text:`\u2193 ${E} below`}),B},Pn=()=>{let R=ii();return R.length===0?"":` ${R.map(E=>E.text).join(" \xB7 ")}`},or=R=>lt(R),ar=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,ee?`${ee.text}${ee.cursor}`:"",ae??"",h?`1|${m}|${a.length}`:"0",Pn(),li?"h1":"h0",ui?"ho1":"ho0"].join("")},He=()=>{Le(()=>{ve.paintRow(Mn(),ar(),()=>{let R=()=>{un=null,fn=null};if(S==="confirm-kill"&&x)R(),t.brightYellow.noFormat(` kill ${or(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="warm"?t.brightRed.noFormat(` kill + delete ${or(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${or(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),t.dim.noFormat(` working on ${or(x.sessionId)}\u2026`);else if(S==="rename"&&x&&ee){R();let E=ee.text,B=ee.cursor;t.brightYellow.noFormat(" title: "),t.brightYellow.noFormat(E.slice(0,B)),B<E.length?(t.bgBrightYellow.noFormat(E[B]??" "),t.brightYellow.noFormat(E.slice(B+1))):t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(ae!==null)R(),t.dim.noFormat(` ${ae}`);else{let E=ii(),B=Pn(),Q="Esc \xB7 Go Back",oe=Q.length,re=5,Ee=B.length,Qe=Math.max(1,Se-Ee-oe-re);if(fn=null,E.length>0){t.dim.noFormat(" ");let Ue=3;for(let nt=0;nt<E.length;nt++){let pt=E[nt];nt>0&&(t.dim.noFormat(" \xB7 "),Ue+=3),pt.kind==="host"?(fn={start:Ue,end:Ue+pt.text.length-1},ui?t.noFormat(pt.text):t.dim.noFormat(pt.text)):t.dim.noFormat(pt.text),Ue+=pt.text.length}}t.dim(" ".repeat(Qe)),li?t.noFormat(Q):t.dim.noFormat(Q),un={start:Se-re-oe+1,end:Se-re}}})})},Et=R=>rs+1+R,Pt=()=>rs+mt+1,Mt=()=>rs+mt+3,_e=R=>Mt()+1+(R-p),Mn=()=>Mt()+1+De,_t=()=>{let R=Rs-Cs;if(R<0||R>=mt)return;let E=3+ss;t.moveTo(E,Et(R))},Ht=()=>Ke?f===0?"f":et?"h":"u":"x",dr=()=>`ct|${Ht()}|${we()}|${Yt}`,cr=()=>`cb|${Ht()}|${we()}`,I=()=>h?`cs|s|${m}|${a.length}`:G!==null?`cs|h|${G}`:"blank",oi=R=>`cbb|${Ht()}|${we()}|${ri(R)}`,Ba=()=>`h|${Xr}`,os=R=>{let E=a[R],B=E&&E.priority&&E.priority>0?"* ":" ",Q=vo[R]??"";return`sr|${f===R+1&&!et&&Ke?"1":"0"}|${B}${Q}`},Je=()=>{Le(()=>{t.hideCursor(),ei(),vn(),rs=1,ve.ensureSize(Se,Y),ve.paintRow(rs,dr(),()=>{ni()});for(let R=0;R<mt;R++){let E=Cs+R;ve.paintRow(Et(R),oi(E),()=>{ir(E)})}ve.paintRow(Pt(),cr(),()=>{rr()}),ve.paintRow(Pt()+1,I(),()=>si()),ve.paintRow(Mt(),Ba(),()=>{t.dim.noFormat(` ${Xr}`)});for(let R=0;R<De;R++){let E=p+R,B=Mt()+1+R;E<a.length?ve.paintRow(B,os(E),()=>{En(E)}):ve.paintRow(B,"blank",()=>{})}He();for(let R=Mn()+1;R<=Y;R++)ve.paintRow(R,"blank",()=>{});f===0&&(_t(),t.hideCursor(!1))})},ko=()=>{ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Je()},lr=()=>{Le(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
207
+ `);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=kb(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=kb(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=oo,s=ya;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,`
208
+ `);this.pasteBuffer="";let a=Zw(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=L0(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),u=[];for(let f=0;f<n.length;f++){let p=d[f],h=n[f];p!==void 0&&D0(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=n.length;f<d.length;f++)u.push(d[f]);this.lines.splice(s.start,s.count,...l);for(let f of u)this.forgetLine(f);for(let f of l)this.lineIds.has(f)||this.trackLine(f);if(this.invalidateSelectionIfTouches(u),s.count=n.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==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(`
209
+ `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),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 u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}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=Yc(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)),ne({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=(u,f,p,h)=>u!==p?u-p:f-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 a=r.body??"",c;Jf(r)?c=a.replace(fb,"").replace(pb,""):(c=a.slice(o.start,o.end),yo(r.bodyStyle)&&(c=yb(c))),n.push(c)}return n.join(`
210
+ `)}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 u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{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=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:Jf(e)?{start:0,end:e.body.length,toEndOfLine:!0}:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}: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,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=c&&u.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(bf),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(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=Gc(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=N0(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 u=this.nearestKeyAboveRow(o.y),f=this.nearestKeyBelowRow(o.y);u!==null&&f!==null&&this.hoveredRunKeys.has(u)&&this.hoveredRunKeys.has(f)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??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)<=Jc&&Math.abs(o.y-d.y)<=Jc&&Date.now()-d.t<=Df||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,B0(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 u=this.btwHeaderSidRegion();if(u!==null&&this.onHydraLinkClick&&o.y===u.row&&o.x>=u.colStart&&o.x<=u.colEnd)this.onHydraLinkClick(u.sessionId);else if(this.onBlockClick){let f=this.keyAtRow(o.y);if(f!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===f;)p-=1;this.schedulePendingBlockClick(f,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!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;if(i!==null&&r-i.t<=Df&&Math.abs(e.x-i.x)<=Jc&&Math.abs(e.y-i.y)<=Jc){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let c=this.keyAtRow(e.y);if(c!==null){let d=e.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;let l=e.y-d;if(this.onBlockDoubleClick(c,l)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let c=this.findLinkUrlAt(s);if(c!==null&&hb.test(c)){let l=c.match(hb)?.[1]??null;if(l&&this.onHydraLinkClick(l)){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 a=this.wordBoundsAt(s);a!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:a.start},{sourceLineId:s.sourceLineId,offset:a.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}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(),u=this.scrollOffset>0,f=d<c;if(d===0&&l||f){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&&u){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&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Yf(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),!Hf.test(r[a]))return null;let c=a;for(;c>0&&Hf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Hf.test(r[d]);)d++;let l=s.length,u=s.length;for(let f=0;f<i.length;f++)if(i[f]===c&&l===s.length&&(l=f),i[f]===d&&u===s.length){u=f;break}return{start:l,end:u}}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}=Yf(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,b=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return b&&(m=b[1],y=Number.parseInt(b[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),!Uf.test(r[a]))return null;let c=a;for(;c>0&&Uf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Uf.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}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}=Yf(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==="~"?lb():`${lb()}/${n.slice(2)}`);let s=ub(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=ub(n)?n:C0(this.sessionbar.cwd,n);if(s)return i;try{if(cb(i).isFile())return i}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(!T0.test(s))return!1;let r=s.startsWith(qt)?[s]:[qt+s,s],i=null;for(let o of r)try{if(cb($.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 u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=A0(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.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)},Df);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&&sb(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"?iw:Ec))}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),u=i-l;return u<0||u>=d.length?null:d[u]?.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),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.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),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=nr(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=yo(p.bodyStyle)?ab(Qf(p.body),y):ob(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+b}}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=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=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()-We-Ze-Xe-E0-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-Xe-Ze-We;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-We),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=sy(this.sessionbar.agent,this.sessionbar.model),i=st(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=ze(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=ze(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=Tt(i,f),m=s?Tt(s,p):"",y=ze(h)+(s?u+ze(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=Yc(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?Qn(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=Sb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+ze(o)+ze(u)+f.length+ze(s);for(let T of c)y+=ze(" \xB7 ")+ze(T.text);y+=ze(p);let b=ze(h)+ze(d)+ze(m),v=Math.max(0,n-y-b),S="\u2500".repeat(v),x=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,x,()=>{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),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.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=ze(i)+ze(a)+ze(o),d=Math.max(0,n-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;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 b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+ze(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=ze(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+ze(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Yc(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Sb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+ze(n)+i.length+ze(r)+o.length+ze(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-Xe-Ze-We,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=Yc(this.btwOverlaySessionId),u=1+c.length+ze(a)+" \xB7 ".length,f=u+ze(d)-1;return{row:o,colStart:u,colEnd:f,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(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let f=-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))||(f===-1&&(f=h),p=h)}for(let h=0;h<s;h++){let m=n+h,y=h-d,b=y>=0?c[y]:void 0,v=this.activeMatchCol(b,l),S=b?this.selectionRangeForChunk(b):null,x=b!==void 0&&b.blockKey!==void 0&&(b.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(b.blockKey)),T=b!==void 0&&b.blockKey===void 0&&f!==-1&&y>=f&&y<=p,F=x||T,_=this.terminalFocused&&F&&(this.hoveredSubKey===null||(b.hoverSubKey??null)===this.hoveredSubKey),N=mb("sb",e,b,this.scrollbackHighlight,v,S)+(_?"|H":"");this.paintRow(m,N,()=>{b&&this.writeFormattedLine(b,e,v,u,S,_)})}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(qf,this.queuedTexts.length)}chipRows(){return Math.min(zf,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(Wf,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-We-Ze-Xe,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 u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>Wf,h=this.completions.length-Wf+1,m=f?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?Tt(b,v):"";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-We-Ze-Xe-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>zf,u=this.attachments.length-zf,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${bn(f.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(W0(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-We-Ze-Xe,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,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>qf,p=this.queuedTexts.length-qf,h=u===void 0?"":f?`+ ${p+1} more queued`:Tt(V0(u),n-4),m=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,n-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}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=es(s.buffer,n),i=xs(r,s,jf),o=this.term.height-i.rendered-Xe-Ze-We+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Kf-Xe-Ze-We+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${Tt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${Tt(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-Xe-Ze-We+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(` ${Tt(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,u=` ${d?"\u276F":" "} ${a+1}. ${Tt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}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-Xe-Ze-We+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 ${Tt(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,u=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${Tt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${Tt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(_0,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-Xe-Ze-We+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} ${Tt(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(` ${Tt(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,f=` ${l?"\u276F":" "} ${c+1}. ${Tt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}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-Xe-Ze-We;this.drawSeparator(s),this.drawBottomSeparator(e-We)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Xe-Ze-We+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Xe-Ze-We+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Kf-Xe-Ze-We+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Xe-Ze-We+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Xe-Ze-We;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Xe-Ze-We+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=es(s.buffer,n),i=xs(r,s,jf),a=this.term.height-i.rendered-Xe-Ze-We+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Xe-Ze-We;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 Kf;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=es(s.buffer,n);return Math.min(jf,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(P0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(M0,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-Xe-Ze-We+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 ${Tt(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 u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${Tt(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?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()-Xe-Ze-We,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 u=this.wrapBtwTail(n,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=mb(`btw|c${f}`,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 u of this.lines)s(u)||d.push(u);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 u=this.wrapOne(l,e);if(r.push(u),i+=u.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 u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=nr(r),o=Math.max(1,n-i-1),a=yo(e.bodyStyle),c=e.ansi?H0(e.body,o):z0(e.body,o,{stripMarkup:a}),d=[],l=0;for(let u=0;u<c.length;u++){let f=c[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(p.hoverSubKey=e.hoverSubKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let h=e.body.indexOf(f,l),m=h===-1?l:h;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:m}),l=m+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&Zn(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-nr(e.prefix??"")),c=yo(e.bodyStyle),d=e.ansi?e.body:Tt(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;gb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Zn(this.term,u,e.bodyStyle,o)};if(i!==null&&Jf(e)){let u=d.replace(fb,"").replace(pb,"");Zn(this.term,u,"selection-highlight",o)}else if(i!==null){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=yo(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=yb(m)),Zn(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=q0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?gb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Zn(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?ze(d):nr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Zn(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Ib=/[^\x20-\x7e]/,Vf=new Intl.Segmenter(void 0,{granularity:"grapheme"}),xb=!1;U0=/[a-zA-Z+\-:_!#/]/;Yc=lt});function Q0(t,e,n=Xc){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 Eb(t,e){Rn();let n=lt(e.sessionId),s=e.importedFromMachine??"another machine",r=st(e.cwd),i=Xc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Xc.length*2+2,d=Tn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(d.contentX,d.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(Ge(p.value,l-p.label.length-2)),f++;return f++,Pb(t,d,f,{intro:"What do you want to do?",choices:Xc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Gn({term:t,render:o,onKey:(a,c,d,l)=>{let u=G0(a,d);if(!u)return;let f=Q0(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function Pb(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(Mc(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 G0(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 Mb(t,e,n){let s=lt(e.sessionId),r=e.title??st(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=Tn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Ge(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+Ge(r,d-2)),l++,l++,Pb(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},u=p=>{l(),n.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var Xc,Xf=K(()=>{"use strict";ye();qn();zr();Xc=[{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 Pa(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 _b(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=Pa(e);return o.length<=r.length?null:o+i}var Zc=K(()=>{"use strict"});var bo,Zf=K(()=>{"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)}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"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as $b from"os";async function Qr(t,e,n={}){let s=n.defaultCwd??(e?await qw(e.cwd):void 0)??$b.homedir();Rn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:lt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:st(e.cwd)}]:[],a=new bo(s),c=null,d=!1,l=null,u=()=>{let y=o.length+6;l=Tn(t,{contentHeight:y,title:r});let b=l.contentW,v=0;for(let S of o)t.moveTo(l.contentX,l.contentY+v),t.dim.noFormat(` ${S.label}`),t.noFormat(Ge(S.value,b-S.label.length-2)),v++;v++,t.moveTo(l.contentX,l.contentY+v),t.noFormat(` ${i}`),v+=2,h(v),v+=2,c!==null?(t.moveTo(l.contentX,l.contentY+v),t.red.noFormat(` ${Ge(c,b-2)}`)):(t.moveTo(l.contentX,l.contentY+v),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},f=()=>o.length+3,p=0,h=y=>{if(!l)return;let b=y??f();t.moveTo(l.contentX,l.contentY+b).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+b),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+b),t.bold.noFormat(" cwd: ");let S=Math.max(1,l.contentW-6-2),x=a.text,T=a.cursor;T<p&&(p=T),T-p>=S&&(p=T-S+1),p<0&&(p=0);let F=x.slice(p,p+S);p>0&&F.length>0&&(F="\u2026"+F.slice(1));let _=T-p;if(d){t.noFormat(F);return}_>=F.length?(t.noFormat(F),t.bgWhite(" ")):(t.noFormat(F.slice(0,_)),t.bgWhite.noFormat(F[_]??" "),t.noFormat(F.slice(_+1)))},m=()=>{if(h(),!l)return;let y=f()+2;t.moveTo(l.contentX,l.contentY+y).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+y),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+y),c!==null?t.red.noFormat(` ${Ge(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Gn({term:t,render:u,onKey:(y,b,v,S)=>{if(!d){if(y==="ENTER"||y==="KP_ENTER"){let x=a.text;d=!0,c=null,m(),Aa(x).then(T=>{if(d=!1,T.ok){S({kind:"ok",path:T.path});return}c=T.reason,m()});return}if(y==="ESCAPE"){S({kind:"back"});return}if(y==="CTRL_C"||y==="CTRL_D"){S({kind:"cancel"});return}if(y==="TAB"){d=!0,Ww(a.text).then(x=>{if(d=!1,x.matches.length===0)return;let T;if(x.matches.length===1)T=x.prefix+x.matches[0];else{let F=Pa(x.matches);if(F.length<=x.basePrefix.length)return;T=x.prefix+F}T!==a.text&&(a.setText(T,{recordUndo:!0}),c=null,m())});return}if(a.handleKey(y,v?.isCharacter===!0)){c=null,m();return}}}})}var ep=K(()=>{"use strict";ye();qn();Tf();Zc();zr();Zf()});import*as Ob from"fs";import*as Lb from"os";import*as el from"path";function tl(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 X0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function Z0(t){return t.replace(/\\ /g," ")}function Fb(t){return t.replace(/ /g,"\\ ")}function eT(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function tT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Lb.homedir()+n.slice(1)),el.isAbsolute(n)?n:el.resolve(e,n)}function nT(t){let e;try{e=Ob.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function nl(t,e,n=nT){if(!X0(t))return null;let s=Z0(t),{dirPrefix:r,base:i}=eT(s),o=tT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:Fb(r+p),candidates:l}}let u=Pa(d.map(f=>f.name));return{replacement:Fb(r+u),candidates:l}}var tp=K(()=>{"use strict";Zc()});function sp(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function rp(t,e){let n=()=>{process.stdout.write(jr),process.stdout.write(Ss),process.stdout.write(qr),process.stdout.write(Wr),process.stdout.write(ao),process.stdout.write(co),process.stdout.write(lo),process.stdout.write(Ur),process.stdout.write("\x1B>")};n();let s=e.prefs??sp();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(E=>E.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=sl(e.sessions,r),o=R=>{let E=R;return s.filters.cwdOnly&&(E=E.filter(B=>B.cwd===r)),s.filters.includeNonInteractive||(E=E.filter(B=>B.interactive===!0)),E=aT(E,s.filters.hostFilter),E},a=o(i),c={columns:e.config.tui.sessionColumns??Xi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>eo(R,Date.now())),l=to(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(E=>E.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",x=null,T=!1,F="input",_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,D=null,X=!1,ee=null,ae=null,G=null,fe=()=>{if(h){let R=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${R} \xB7 ^c clears`,render:()=>{t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" "),t.dim.noFormat(` ${R} \xB7 ^c clears`)}}}return G!==null?{plain:G,render:()=>{t.dim.noFormat(` ${G}`)}}:null},Ve=!1,Be=new Is({history:[]});if(e.initialPrompt&&Be.setBuffer(e.initialPrompt),e.initialAttachments)for(let R of e.initialAttachments)Be.addAttachment(R);let ns=e.config.tui.promptHistoryMaxEntries;Qo($.globalTuiHistoryFile()).then(R=>{let E=R.length>ns?R.slice(R.length-ns):R;Be.setHistory(E)}).catch(()=>{});let ve=new go(t),Y=ks(t),Se=Yt(t),De=0,Vt="",As=0,cn=[],mt=1,Cs=0,Rs=0,ss=0,Xr="",vo=[],rs=1,Oa=0,So=[],pe=1,Ts=0,La=0,Zr=0,ei=()=>{Y=ks(t),Se=Yt(t);let R=Math.max(10,Se-np-1);As=Math.max(10,Se-Bb);let E=Math.max(10,Se-8),B=Be.state().attachments.length,Q=B>0?` \xB7 \u{1F4CE}\xD7${B}`:"",oe=Math.max(10,E-Q.length);Vt=oT(r,oe)+Q;let re=Be.state();cn=es(re.buffer,As);let Ee=xs(cn,re,Ma);mt=Ee.rendered,Cs=Ee.windowStart,Rs=Ee.cursorVisualRow,ss=Ee.cursorVisualCol;let Qe=6+mt,Ue=Math.max(3,Y-Qe);De=Math.min(a.length,Ue),Xr=Gs(Zi,l,R,c).padEnd(R),vo=d.map(nt=>Gs(nt,l,R,c).padEnd(R))},ti=()=>{d=a.map(R=>eo(R,Date.now())),l=to(d,c),u=1+a.length,ei()},Dt=()=>{let R=o(i);h&&m.length>0?a=R.filter(E=>dT(E,m)):a=R,ti(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+De>a.length&&(p=Math.max(0,a.length-De)),vn()},is=R=>{if(R!==void 0){let E=a.findIndex(B=>B.sessionId===R);if(E>=0){f=E+1,vn();return}}f=a.length>0?1:0,p=0,vn()},vn=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+De?p=R-De+1:p+De>a.length&&(p=Math.max(0,a.length-De))},we=()=>Math.max(2,Se-3),et=!1,Ke=!0,gt=!1,Es=[],ni=()=>{let R=we(),E=`\u2500 ${Vt} `,B=Math.max(1,R-E.length),Q="\u2500".repeat(B);(f===0||et)&&Ke?t.brightBlue.noFormat(`\u256D${E}${Q}\u256E`):t.dim.noFormat(`\u256D${E}${Q}\u256E`)},rr=()=>{let R=we(),E="\u2500".repeat(R);(f===0||et)&&Ke?t.brightBlue.noFormat(`\u2570${E}\u256F`):t.dim.noFormat(`\u2570${E}\u256F`)},si=()=>{let R=fe();if(R===null)return;let E=Math.max(0,Yt(t)-2);if(R.plain.length>E){let B=R.plain.slice(0,Math.max(0,E-1))+"\u2026";t.dim.noFormat(` ${B}`);return}R.render()},ri=R=>{let E=cn[R];return E?(Be.state().buffer[E.bufferIdx]??"").slice(E.startCol,E.endCol):""},ir=R=>{let E=we(),B=ri(R),Q=Math.max(0,E-1-B.length),oe=" ".repeat(Q);(f===0||et)&&Ke?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${B}${oe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${B}${oe}`),t.dim.noFormat("\u2502"))},En=R=>{let E=vo[R]??"",B=a[R],Q=B&&B.priority&&B.priority>0?"* ":" ";f===R+1&&!et&&Ke?t.brightWhite.bgBlue.noFormat(`${Q}${E}`):t.noFormat(`${Q}${E}`)},ii=()=>{let R=p,E=Math.max(0,a.length-p-De),B=[];if(s.filters.cwdOnly&&B.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;B.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&B.push({kind:"plain",text:"+non-interactive"}),R>0&&B.push({kind:"plain",text:`\u2191 ${R} above`}),E>0&&B.push({kind:"plain",text:`\u2193 ${E} below`}),B},Pn=()=>{let R=ii();return R.length===0?"":` ${R.map(E=>E.text).join(" \xB7 ")}`},or=R=>lt(R),ar=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,ee?`${ee.text}${ee.cursor}`:"",ae??"",h?`1|${m}|${a.length}`:"0",Pn(),li?"h1":"h0",ui?"ho1":"ho0"].join("")},He=()=>{Le(()=>{ve.paintRow(Mn(),ar(),()=>{let R=()=>{fn=null,pn=null};if(S==="confirm-kill"&&x)R(),t.brightYellow.noFormat(` kill ${or(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="warm"?t.brightRed.noFormat(` kill + delete ${or(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${or(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),t.dim.noFormat(` working on ${or(x.sessionId)}\u2026`);else if(S==="rename"&&x&&ee){R();let E=ee.text,B=ee.cursor;t.brightYellow.noFormat(" title: "),t.brightYellow.noFormat(E.slice(0,B)),B<E.length?(t.bgBrightYellow.noFormat(E[B]??" "),t.brightYellow.noFormat(E.slice(B+1))):t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(ae!==null)R(),t.dim.noFormat(` ${ae}`);else{let E=ii(),B=Pn(),Q="Esc \xB7 Go Back",oe=Q.length,re=5,Ee=B.length,Qe=Math.max(1,Se-Ee-oe-re);if(pn=null,E.length>0){t.dim.noFormat(" ");let Ue=3;for(let nt=0;nt<E.length;nt++){let pt=E[nt];nt>0&&(t.dim.noFormat(" \xB7 "),Ue+=3),pt.kind==="host"?(pn={start:Ue,end:Ue+pt.text.length-1},ui?t.noFormat(pt.text):t.dim.noFormat(pt.text)):t.dim.noFormat(pt.text),Ue+=pt.text.length}}t.dim(" ".repeat(Qe)),li?t.noFormat(Q):t.dim.noFormat(Q),fn={start:Se-re-oe+1,end:Se-re}}})})},Et=R=>rs+1+R,Pt=()=>rs+mt+1,Mt=()=>rs+mt+3,_e=R=>Mt()+1+(R-p),Mn=()=>Mt()+1+De,_t=()=>{let R=Rs-Cs;if(R<0||R>=mt)return;let E=3+ss;t.moveTo(E,Et(R))},Ht=()=>Ke?f===0?"f":et?"h":"u":"x",dr=()=>`ct|${Ht()}|${we()}|${Vt}`,cr=()=>`cb|${Ht()}|${we()}`,I=()=>h?`cs|s|${m}|${a.length}`:G!==null?`cs|h|${G}`:"blank",oi=R=>`cbb|${Ht()}|${we()}|${ri(R)}`,Ba=()=>`h|${Xr}`,os=R=>{let E=a[R],B=E&&E.priority&&E.priority>0?"* ":" ",Q=vo[R]??"";return`sr|${f===R+1&&!et&&Ke?"1":"0"}|${B}${Q}`},Je=()=>{Le(()=>{t.hideCursor(),ei(),vn(),rs=1,ve.ensureSize(Se,Y),ve.paintRow(rs,dr(),()=>{ni()});for(let R=0;R<mt;R++){let E=Cs+R;ve.paintRow(Et(R),oi(E),()=>{ir(E)})}ve.paintRow(Pt(),cr(),()=>{rr()}),ve.paintRow(Pt()+1,I(),()=>si()),ve.paintRow(Mt(),Ba(),()=>{t.dim.noFormat(` ${Xr}`)});for(let R=0;R<De;R++){let E=p+R,B=Mt()+1+R;E<a.length?ve.paintRow(B,os(E),()=>{En(E)}):ve.paintRow(B,"blank",()=>{})}He();for(let R=Mn()+1;R<=Y;R++)ve.paintRow(R,"blank",()=>{});f===0&&(_t(),t.hideCursor(!1))})},ko=()=>{ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Je()},lr=()=>{Le(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
211
211
 
212
- `);for(let R of rT){if(R===null){t(`
213
- `);continue}let[E,B]=R;t.brightCyan.noFormat(` ${E.padEnd(sT)}`),t.noFormat(B)(`
212
+ `);for(let R of iT){if(R===null){t(`
213
+ `);continue}let[E,B]=R;t.brightCyan.noFormat(` ${E.padEnd(rT)}`),t.noFormat(B)(`
214
214
  `)}t(`
215
215
  `),t.dim.noFormat(" press any key to dismiss")(`
216
- `)})},yt=()=>pe+4,Na=2,wt=0,as=()=>{Y=ks(t);let R=Math.max(2,Y-(pe+3)-Na);return Math.max(1,Math.floor(R/2))},Io=()=>{let R=as();q<wt?wt=q:q>=wt+R&&(wt=q-R+1),wt+R>N.length&&(wt=Math.max(0,N.length-R)),wt<0&&(wt=0)},ds=R=>{Se=Jt(t);let E=Math.max(2,Se-3),B="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,E-B.length));R?t.brightBlue.noFormat(`\u256D${B}${Q}\u256E`):t.dim.noFormat(`\u256D${B}${Q}\u256E`),t.styleReset()},Ps=()=>{Se=Jt(t),Oa=Math.max(10,Se-Lb);let R=_.state();So=es(R.buffer,Oa);let E=xs(So,R,nT);pe=E.rendered,Ts=E.windowStart,La=E.cursorVisualRow,Zr=E.cursorVisualCol},xo=(R,E)=>{Se=Jt(t);let B=Math.max(2,Se-3),Q=So[R],oe="";Q&&(oe=(_.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let re=Math.max(0,B-1-oe.length),Ee=" ".repeat(re);E?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${oe}${Ee}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${oe}${Ee}`),t.dim.noFormat("\u2502")),t.styleReset()},Da=R=>{Se=Jt(t);let E=Math.max(2,Se-3),B="\u2500".repeat(E);R?t.brightBlue.noFormat(`\u2570${B}\u256F`):t.dim.noFormat(`\u2570${B}\u256F`),t.styleReset()},ur=()=>3+Zr,fr=()=>2+(La-Ts),Ao=()=>{let R=F==="input";Le(()=>{R&&t.hideCursor(),t.moveTo(1,1),ds(R);for(let E=0;E<pe;E++)t.moveTo(1,2+E),xo(Ts+E,R);t.moveTo(1,2+pe),Da(R),R&&(t.moveTo(ur(),fr()),t.hideCursor(!1))})},Ha=()=>{Le(()=>{t.hideCursor();for(let R=0;R<pe;R++)t.moveTo(1,2+R),xo(Ts+R,!0);t.moveTo(ur(),fr()),t.hideCursor(!1)})},cn={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},bt=(R,E)=>{let B=N[R];if(!B)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=Jt(t),oe=Math.max(20,Q-np),re=lt(B.sessionId),Ee=B.title??st(B.cwd),Qe=E&&B.snippets.length>1?` [${L+1}/${B.snippets.length}]`:E&&B.totalMatches>B.snippets.length?` [${B.snippets.length} of ${B.totalMatches}]`:"",Ue=`${re} ${B.status==="warm"?"warm":"cold"}`,nt=Math.max(5,oe-Ue.length-Qe.length-2),pt=ha(Ee,nt),On=`${Ue} ${pt}${Qe}`.padEnd(oe),at=B.snippets[E?L:0],dt=at?cn[at.kind]??at.kind:"",Os=at?.toolName?`${dt} \xB7 ${at.toolName}`:dt,gr=Math.max(10,oe-Os.length-6),Ln=at?ha(at.text,gr):"",yr=at?` ${Os} ${Ln}`:" (no snippet)";return{rowBudget:oe,line1:On,line2:yr.padEnd(oe+np),focusedRow:E}},Co=(R,E)=>{let{line1:B,focusedRow:Q}=bt(R,E);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${B}`):t.noFormat(` ${B}`),t.styleReset()},ai=(R,E)=>{let{line2:B}=bt(R,E);t.dim.noFormat(B),t.styleReset()},Ms=()=>{if(X)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(D!==null)t.brightRed.noFormat(` ${D}`),t.styleReset(),t.eraseLineAfter();else if(F==="input")N.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 R=N.length,E=J?" \xB7 truncated":"",B=R>0?` ${R} ${R===1?"session":"sessions"} match${E} \xB7 `:" ";t.dim.noFormat(`${B}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},Vt=()=>{Ps();let R=F==="input",E=_.state().buffer.join(`
216
+ `)})},yt=()=>pe+4,Na=2,wt=0,as=()=>{Y=ks(t);let R=Math.max(2,Y-(pe+3)-Na);return Math.max(1,Math.floor(R/2))},Io=()=>{let R=as();q<wt?wt=q:q>=wt+R&&(wt=q-R+1),wt+R>N.length&&(wt=Math.max(0,N.length-R)),wt<0&&(wt=0)},ds=R=>{Se=Yt(t);let E=Math.max(2,Se-3),B="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,E-B.length));R?t.brightBlue.noFormat(`\u256D${B}${Q}\u256E`):t.dim.noFormat(`\u256D${B}${Q}\u256E`),t.styleReset()},Ps=()=>{Se=Yt(t),Oa=Math.max(10,Se-Bb);let R=_.state();So=es(R.buffer,Oa);let E=xs(So,R,sT);pe=E.rendered,Ts=E.windowStart,La=E.cursorVisualRow,Zr=E.cursorVisualCol},xo=(R,E)=>{Se=Yt(t);let B=Math.max(2,Se-3),Q=So[R],oe="";Q&&(oe=(_.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let re=Math.max(0,B-1-oe.length),Ee=" ".repeat(re);E?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${oe}${Ee}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${oe}${Ee}`),t.dim.noFormat("\u2502")),t.styleReset()},Da=R=>{Se=Yt(t);let E=Math.max(2,Se-3),B="\u2500".repeat(E);R?t.brightBlue.noFormat(`\u2570${B}\u256F`):t.dim.noFormat(`\u2570${B}\u256F`),t.styleReset()},ur=()=>3+Zr,fr=()=>2+(La-Ts),Ao=()=>{let R=F==="input";Le(()=>{R&&t.hideCursor(),t.moveTo(1,1),ds(R);for(let E=0;E<pe;E++)t.moveTo(1,2+E),xo(Ts+E,R);t.moveTo(1,2+pe),Da(R),R&&(t.moveTo(ur(),fr()),t.hideCursor(!1))})},Ha=()=>{Le(()=>{t.hideCursor();for(let R=0;R<pe;R++)t.moveTo(1,2+R),xo(Ts+R,!0);t.moveTo(ur(),fr()),t.hideCursor(!1)})},ln={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},bt=(R,E)=>{let B=N[R];if(!B)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=Yt(t),oe=Math.max(20,Q-np),re=lt(B.sessionId),Ee=B.title??st(B.cwd),Qe=E&&B.snippets.length>1?` [${L+1}/${B.snippets.length}]`:E&&B.totalMatches>B.snippets.length?` [${B.snippets.length} of ${B.totalMatches}]`:"",Ue=`${re} ${B.status==="warm"?"warm":"cold"}`,nt=Math.max(5,oe-Ue.length-Qe.length-2),pt=ha(Ee,nt),On=`${Ue} ${pt}${Qe}`.padEnd(oe),at=B.snippets[E?L:0],dt=at?ln[at.kind]??at.kind:"",Os=at?.toolName?`${dt} \xB7 ${at.toolName}`:dt,gr=Math.max(10,oe-Os.length-6),Ln=at?ha(at.text,gr):"",yr=at?` ${Os} ${Ln}`:" (no snippet)";return{rowBudget:oe,line1:On,line2:yr.padEnd(oe+np),focusedRow:E}},Co=(R,E)=>{let{line1:B,focusedRow:Q}=bt(R,E);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${B}`):t.noFormat(` ${B}`),t.styleReset()},ai=(R,E)=>{let{line2:B}=bt(R,E);t.dim.noFormat(B),t.styleReset()},Ms=()=>{if(X)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(D!==null)t.brightRed.noFormat(` ${D}`),t.styleReset(),t.eraseLineAfter();else if(F==="input")N.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 R=N.length,E=J?" \xB7 truncated":"",B=R>0?` ${R} ${R===1?"session":"sessions"} match${E} \xB7 `:" ";t.dim.noFormat(`${B}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},Qt=()=>{Ps();let R=F==="input",E=_.state().buffer.join(`
217
217
  `);Le(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),ds(R);for(let Q=0;Q<pe;Q++)t.moveTo(1,2+Q),xo(Ts+Q,R);t.moveTo(1,2+pe),Da(R);let B=N.length;if(B===0)t.moveTo(1,yt()),X||(D===null&&E.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):D===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,yt()+1),Ms();else{Io();let Q=as(),oe=F!=="input";for(let re=0;re<Q;re++){let Ee=wt+re;t.moveTo(1,yt()+re*2),Ee<B?Co(Ee,oe&&Ee===q):t.eraseLineAfter(),t.moveTo(1,yt()+re*2+1),Ee<B?ai(Ee,oe&&Ee===q):t.eraseLineAfter()}t.moveTo(1,yt()+Q*2),Ms()}R&&(t.moveTo(ur(),fr()),t.hideCursor(!1))})},_n=(R,E)=>{let B=R-wt;B<0||B>=as()||Le(()=>{t.moveTo(1,yt()+B*2),Co(R,E),t.moveTo(1,yt()+B*2+1),ai(R,E)})},di=()=>{Le(()=>{t.moveTo(1,yt()+as()*2),Ms()})},Ua=()=>{Le(()=>{let R=as(),E=N.length,B=F!=="input";for(let Q=0;Q<R;Q++){let oe=wt+Q;t.moveTo(1,yt()+Q*2),oe<E?Co(oe,B&&oe===q):t.eraseLineAfter(),t.moveTo(1,yt()+Q*2+1),oe<E?ai(oe,B&&oe===q):t.eraseLineAfter()}t.moveTo(1,yt()+R*2),Ms()})},Ro=()=>_.state().buffer.join(`
218
- `),To=R=>{let E=pe;_.feed({type:"paste",text:R}),Ps(),pe!==E?Vt():Ha()},ja=async()=>{let R=Ro().trim();if(R.length!==0){if(a.length===0){D="no sessions in view to search",Vt();return}X=!0,D=null,Vt();try{let E=await ty(e.target,R,{sessionIds:a.map(B=>B.sessionId)});N=E.results,J=E.truncated,q=0,L=0,wt=0,F=E.results.length>0?"results":"input",Ps()}catch(E){D=`search failed: ${E.message}`}finally{X=!1,Vt()}}},Eo=()=>{},ci=()=>{Le(()=>{let R=f===0;R&&t.hideCursor(),ve.paintRow(rs,dr(),()=>{ni()}),ve.paintRow(Pt(),cr(),()=>{rr()});for(let E=0;E<mt;E++){let B=Cs+E;ve.paintRow(Et(E),oi(B),()=>{ir(B)})}R&&(_t(),t.hideCursor(!1))})},_s=()=>{Le(()=>{ve.paintRow(Pt()+1,I(),()=>si())})},ln=()=>{G!==null&&(G=null,_s())},Wt=()=>{Le(()=>{let R=Be.state();dn=es(R.buffer,As);let E=xs(dn,R,Ma);Cs=E.windowStart,Rs=E.cursorVisualRow,ss=E.cursorVisualCol;let B=f===0;B&&t.hideCursor();for(let Q=0;Q<mt;Q++){let oe=Cs+Q;ve.paintRow(Et(Q),oi(oe),()=>{ir(oe)})}B&&(_t(),t.hideCursor(!1))})},$s=async()=>{let R=await qc();if(!R.ok){ae=R.reason,He();return}if(R.kind!=="image"){let E=Be.state(),B=[...E.buffer],Q=E.row,oe=E.col;Be.feed({type:"paste",text:R.text});let re=Be.state();if(B.length!==re.buffer.length||Q!==re.row||oe!==re.col||!B.every((Qe,Ue)=>Qe===re.buffer[Ue])){let Qe=es(re.buffer,As);xs(Qe,re,Ma).rendered!==mt?Je():Wt()}return}Be.addAttachment(R.attachment),ae=`attached ${R.attachment.name??"image"}`,Je()},pr=R=>{R<p||R>=p+De||Le(()=>{ve.paintRow(_e(R),os(R),()=>{En(R)})})},At=()=>{Le(()=>{for(let R=0;R<De;R++){let E=Mt()+1+R,B=p+R;B<a.length?ve.paintRow(E,os(B),()=>{En(B)}):ve.paintRow(E,"blank",()=>{})}He()})},hr=()=>{Le(()=>{ve.paintRow(Mt(),Ba(),()=>{t.dim.noFormat(` ${Xr}`)});for(let R=0;R<De;R++){let E=Mt()+1+R,B=p+R;B<a.length?ve.paintRow(E,os(B),()=>{En(B)}):ve.paintRow(E,"blank",()=>{})}He(),f===0&&(_t(),t.hideCursor(!1))})},$n=!1,Fn="",Po=0,Mo=200,mr=null,cs=!1,un=null,li=!1,fn=null,ui=!1,Qt=null,_o=null,qa=null,Fs=R=>{let E=R.toString("binary");if(E.includes("\x1B[I")||E.includes("\x1B[O")){for(;;){let Q=E.indexOf("\x1B[I"),oe=E.indexOf("\x1B[O"),re=Q===-1?oe:oe===-1?Q:Math.min(Q,oe);if(re===-1)break;let Ee=Ke;Ke=re===Q,Ke&&(Po=Date.now()),Ee!==Ke&&!gt&&Es.length<=1&&Le(()=>{ci(),At()}),E=E.slice(0,re)+E.slice(re+"\x1B[I".length)}if(E.length===0)return}if(!$n&&E===""&&_o){_o();return}if(!$n&&(E===""||E==="\x1B_"||E==="\x1B")){qa?.(E);return}if($n){let Q=E.indexOf(ya);if(Q===-1){Fn+=E;return}Fn+=E.slice(0,Q),$n=!1;let oe=Buffer.from(Fn,"binary").toString("utf-8").replace(/\r\n?/g,`
219
- `);Fn="";let re=E.slice(Q+ya.length);if(T)F==="input"&&!X&&To(oe);else if(f===0&&!h){let Ee=Be.feed({type:"paste",text:oe});for(let pt of Ee)pt.type==="attachment-request"&&$s();let Qe=Be.state(),Ue=es(Qe.buffer,As);xs(Ue,Qe,Ma).rendered!==mt?Je():Wt()}re.length>0&&Qt&&Qt(Buffer.from(re,"binary"));return}let B=E.indexOf(oo);if(B===-1){Qt?.(R);return}B>0&&Qt?.(Buffer.from(E.slice(0,B),"binary")),E=E.slice(B+oo.length),$n=!0,E.length>0&&Fs(Buffer.from(E,"binary"))};return Je(),await new Promise(R=>{let E=null,B=!1,Q=null,oe=!1,re=Es,Ee=M=>{re.push(M)},Qe=()=>{re.pop(),gt||re[re.length-1]?.onResize()},Ue={push:Ee,pop:Qe},nt=()=>{let M={kind:"new",cwd:r},U=Be.state().attachments;return U.length>0&&(M.attachments=[...U]),M},pt=async()=>{ft(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ee({onKey:()=>{},onResize:()=>{}});let U;try{U=await Qr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Qe(),ps()}U.kind==="ok"&&U.path!==r&&(r=U.path,i=sl(i,r),Dt()),gt||Je()};Eo=()=>{_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,wt=0,D=null,X=!1,F="input",T=!1,Qe()};let On=(M,U,ie)=>{gr(),re[re.length-1]?.onKey(M,U,ie)},at=()=>{gt||re[re.length-1]?.onResize()};qa=M=>{gt||re[re.length-1]?.onKey(M,null,{})};let dt=()=>{if(gt)return;gt=!0,re.length=0,E&&(clearInterval(E),E=null),Q&&(Q.abort(),Q=null,B=!1),t.off("key",On),t.off("mouse",Bn),t.off("resize",at),process.stdout.write(Ss),process.stdout.write(ba);let M=t;M.stdin&&Qt&&(M.stdin.removeListener("data",Fs),M.stdin.on("data",Qt),Qt=null),$n=!1,Fn="",t.grabInput(!1),ne({src:"grab",site:"picker.cleanup",on:!1}),t.hideCursor(!1),t.moveTo(1,Mn()+1),t(`
218
+ `),To=R=>{let E=pe;_.feed({type:"paste",text:R}),Ps(),pe!==E?Qt():Ha()},ja=async()=>{let R=Ro().trim();if(R.length!==0){if(a.length===0){D="no sessions in view to search",Qt();return}X=!0,D=null,Qt();try{let E=await ty(e.target,R,{sessionIds:a.map(B=>B.sessionId)});N=E.results,J=E.truncated,q=0,L=0,wt=0,F=E.results.length>0?"results":"input",Ps()}catch(E){D=`search failed: ${E.message}`}finally{X=!1,Qt()}}},Eo=()=>{},ci=()=>{Le(()=>{let R=f===0;R&&t.hideCursor(),ve.paintRow(rs,dr(),()=>{ni()}),ve.paintRow(Pt(),cr(),()=>{rr()});for(let E=0;E<mt;E++){let B=Cs+E;ve.paintRow(Et(E),oi(B),()=>{ir(B)})}R&&(_t(),t.hideCursor(!1))})},_s=()=>{Le(()=>{ve.paintRow(Pt()+1,I(),()=>si())})},un=()=>{G!==null&&(G=null,_s())},zt=()=>{Le(()=>{let R=Be.state();cn=es(R.buffer,As);let E=xs(cn,R,Ma);Cs=E.windowStart,Rs=E.cursorVisualRow,ss=E.cursorVisualCol;let B=f===0;B&&t.hideCursor();for(let Q=0;Q<mt;Q++){let oe=Cs+Q;ve.paintRow(Et(Q),oi(oe),()=>{ir(oe)})}B&&(_t(),t.hideCursor(!1))})},$s=async()=>{let R=await qc();if(!R.ok){ae=R.reason,He();return}if(R.kind!=="image"){let E=Be.state(),B=[...E.buffer],Q=E.row,oe=E.col;Be.feed({type:"paste",text:R.text});let re=Be.state();if(B.length!==re.buffer.length||Q!==re.row||oe!==re.col||!B.every((Qe,Ue)=>Qe===re.buffer[Ue])){let Qe=es(re.buffer,As);xs(Qe,re,Ma).rendered!==mt?Je():zt()}return}Be.addAttachment(R.attachment),ae=`attached ${R.attachment.name??"image"}`,Je()},pr=R=>{R<p||R>=p+De||Le(()=>{ve.paintRow(_e(R),os(R),()=>{En(R)})})},At=()=>{Le(()=>{for(let R=0;R<De;R++){let E=Mt()+1+R,B=p+R;B<a.length?ve.paintRow(E,os(B),()=>{En(B)}):ve.paintRow(E,"blank",()=>{})}He()})},hr=()=>{Le(()=>{ve.paintRow(Mt(),Ba(),()=>{t.dim.noFormat(` ${Xr}`)});for(let R=0;R<De;R++){let E=Mt()+1+R,B=p+R;B<a.length?ve.paintRow(E,os(B),()=>{En(B)}):ve.paintRow(E,"blank",()=>{})}He(),f===0&&(_t(),t.hideCursor(!1))})},$n=!1,Fn="",Po=0,Mo=200,mr=null,cs=!1,fn=null,li=!1,pn=null,ui=!1,Gt=null,_o=null,qa=null,Fs=R=>{let E=R.toString("binary");if(E.includes("\x1B[I")||E.includes("\x1B[O")){for(;;){let Q=E.indexOf("\x1B[I"),oe=E.indexOf("\x1B[O"),re=Q===-1?oe:oe===-1?Q:Math.min(Q,oe);if(re===-1)break;let Ee=Ke;Ke=re===Q,Ke&&(Po=Date.now()),Ee!==Ke&&!gt&&Es.length<=1&&Le(()=>{ci(),At()}),E=E.slice(0,re)+E.slice(re+"\x1B[I".length)}if(E.length===0)return}if(!$n&&E===""&&_o){_o();return}if(!$n&&(E===""||E==="\x1B_"||E==="\x1B")){qa?.(E);return}if($n){let Q=E.indexOf(ya);if(Q===-1){Fn+=E;return}Fn+=E.slice(0,Q),$n=!1;let oe=Buffer.from(Fn,"binary").toString("utf-8").replace(/\r\n?/g,`
219
+ `);Fn="";let re=E.slice(Q+ya.length);if(T)F==="input"&&!X&&To(oe);else if(f===0&&!h){let Ee=Be.feed({type:"paste",text:oe});for(let pt of Ee)pt.type==="attachment-request"&&$s();let Qe=Be.state(),Ue=es(Qe.buffer,As);xs(Ue,Qe,Ma).rendered!==mt?Je():zt()}re.length>0&&Gt&&Gt(Buffer.from(re,"binary"));return}let B=E.indexOf(oo);if(B===-1){Gt?.(R);return}B>0&&Gt?.(Buffer.from(E.slice(0,B),"binary")),E=E.slice(B+oo.length),$n=!0,E.length>0&&Fs(Buffer.from(E,"binary"))};return Je(),await new Promise(R=>{let E=null,B=!1,Q=null,oe=!1,re=Es,Ee=M=>{re.push(M)},Qe=()=>{re.pop(),gt||re[re.length-1]?.onResize()},Ue={push:Ee,pop:Qe},nt=()=>{let M={kind:"new",cwd:r},U=Be.state().attachments;return U.length>0&&(M.attachments=[...U]),M},pt=async()=>{ft(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ee({onKey:()=>{},onResize:()=>{}});let U;try{U=await Qr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Qe(),ps()}U.kind==="ok"&&U.path!==r&&(r=U.path,i=sl(i,r),Dt()),gt||Je()};Eo=()=>{_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,wt=0,D=null,X=!1,F="input",T=!1,Qe()};let On=(M,U,ie)=>{gr(),re[re.length-1]?.onKey(M,U,ie)},at=()=>{gt||re[re.length-1]?.onResize()};qa=M=>{gt||re[re.length-1]?.onKey(M,null,{})};let dt=()=>{if(gt)return;gt=!0,re.length=0,E&&(clearInterval(E),E=null),Q&&(Q.abort(),Q=null,B=!1),t.off("key",On),t.off("mouse",Bn),t.off("resize",at),process.stdout.write(Ss),process.stdout.write(ba);let M=t;M.stdin&&Gt&&(M.stdin.removeListener("data",Fs),M.stdin.on("data",Gt),Gt=null),$n=!1,Fn="",t.grabInput(!1),ne({src:"grab",site:"picker.cleanup",on:!1}),t.hideCursor(!1),t.moveTo(1,Mn()+1),t(`
220
220
  `)},Os=()=>{if(gt||re.length>1||S!=="normal"||h||oe)return;B&&Q&&(Q.abort(),Q=null,B=!1);let M=f>0?a[f-1]?.sessionId:void 0;B=!0;let U=new AbortController;Q=U,Ls(M,{silent:!0,signal:U.signal}).finally(()=>{Q===U&&(Q=null),B=!1})},gr=()=>{gt||(E&&clearInterval(E),E=setInterval(Os,3e3))},Ln=()=>(dt(),R({kind:Ve?"exit":"abort"}),!0),yr=()=>{let M=d.map(U=>`${U.session}|${U.upstream}|${U.host}|${U.state}|${U.agent}|${U.model}|${U.age}|${U.title}|${U.cwd}|${U.cost}`).join(`
221
221
  `);return`${f}:${p}:${ae??""}
222
- ${M}`},Ls=async(M,U={})=>{try{let ie=U.silent?yr():"",z=u,ue=await Yn(e.target,{includeNonInteractive:!0,signal:U.signal}),le=M??(f>0?a[f-1]?.sessionId:void 0);if(i=sl(ue,r),Dt(),le!==void 0){let je=a.findIndex(Ne=>Ne.sessionId===le);je>=0?f=je+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+De>a.length&&(p=Math.max(0,a.length-De)),vn(),U.silent&&yr()===ie)return;u===z?hr():Je()}catch(ie){if(U.silent)return;ae=`refresh failed: ${ie.message}`,Je()}},$o=async M=>{if(!x)return;let U=x;S="busy",He();try{await Xg(e.target,U.sessionId,M),S="normal",x=null,ee=null,await Ls(U.sessionId)}catch(ie){S="normal",x=null,ee=null,ae=`rename failed: ${ie.message}`,He()}},vt=async M=>{try{await ey(e.target,M.sessionId),ae="title regen queued (press r to refresh)",He()}catch(U){ae=`regen failed: ${U.message}`,He()}},ls=async M=>{let ie=(M.priority&&M.priority>0?M.priority:0)>0?null:1,z=ie??0;for(let le of i)le.sessionId===M.sessionId&&(le.priority=z>0?z:void 0);let ue=M.sessionId;i=sl(i,r),Dt(),is(ue),Je(),ae=z>0?"priority: high":"priority: normal",He();try{await Zg(e.target,M.sessionId,ie)}catch(le){ae=`priority failed: ${le.message}`,He()}},us=async()=>{if(oe)return;oe=!0;let M=f>0?a[f-1]?.sessionId:void 0;ae="syncing agents\u2026",He();try{let{synced:U,skipped:ie,agents:z}=await Gg(e.target);await Ls(M),ae=`synced ${U} new (${ie} known) from ${z} agent${z===1?"":"s"}`,He()}catch(U){ae=`sync failed: ${U.message}`,He()}finally{oe=!1}},Bs=async M=>{if(!x)return;let U=x;S="busy",He();try{M==="kill"?await Vn(e.target,U.sessionId):await ny(e.target,U.sessionId),S="normal",x=null,U.sessionId===e.currentSessionId&&(Ve=!0);let ie;if(M==="kill")ie=U.sessionId;else{let z=a.findIndex(ue=>ue.sessionId===U.sessionId);z>=0&&(ie=a[z+1]?.sessionId??a[z-1]?.sessionId)}await Ls(ie)}catch(ie){S="normal",x=null,ae=`${M} failed: ${ie.message}`,He()}},pn=(M,U)=>{M===0!=(U===0)&&(ci(),U===0?(t.hideCursor(!1),_t()):t.hideCursor())},Ct=M=>{let U=Math.min(u-1,Math.max(0,f+M));if(U===f)return;let ie=f;f=U,vn(),Le(()=>{At(),pn(ie,f)})},Sn=()=>ae===null?!1:(ae=null,He(),!0),fs=()=>{lr(),Ee({onKey:M=>{if(M==="CTRL_C"){dt(),R({kind:"abort"});return}Qe()},onResize:()=>lr()})},wr=M=>{let U=null,ie=null,z=!0,ue=()=>{Le(()=>{if(t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${lt(M.sessionId)}`)(`
222
+ ${M}`},Ls=async(M,U={})=>{try{let ie=U.silent?yr():"",z=u,ue=await Yn(e.target,{includeNonInteractive:!0,signal:U.signal}),le=M??(f>0?a[f-1]?.sessionId:void 0);if(i=sl(ue,r),Dt(),le!==void 0){let je=a.findIndex(Ne=>Ne.sessionId===le);je>=0?f=je+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+De>a.length&&(p=Math.max(0,a.length-De)),vn(),U.silent&&yr()===ie)return;u===z?hr():Je()}catch(ie){if(U.silent)return;ae=`refresh failed: ${ie.message}`,Je()}},$o=async M=>{if(!x)return;let U=x;S="busy",He();try{await Xg(e.target,U.sessionId,M),S="normal",x=null,ee=null,await Ls(U.sessionId)}catch(ie){S="normal",x=null,ee=null,ae=`rename failed: ${ie.message}`,He()}},vt=async M=>{try{await ey(e.target,M.sessionId),ae="title regen queued (press r to refresh)",He()}catch(U){ae=`regen failed: ${U.message}`,He()}},ls=async M=>{let ie=(M.priority&&M.priority>0?M.priority:0)>0?null:1,z=ie??0;for(let le of i)le.sessionId===M.sessionId&&(le.priority=z>0?z:void 0);let ue=M.sessionId;i=sl(i,r),Dt(),is(ue),Je(),ae=z>0?"priority: high":"priority: normal",He();try{await Zg(e.target,M.sessionId,ie)}catch(le){ae=`priority failed: ${le.message}`,He()}},us=async()=>{if(oe)return;oe=!0;let M=f>0?a[f-1]?.sessionId:void 0;ae="syncing agents\u2026",He();try{let{synced:U,skipped:ie,agents:z}=await Gg(e.target);await Ls(M),ae=`synced ${U} new (${ie} known) from ${z} agent${z===1?"":"s"}`,He()}catch(U){ae=`sync failed: ${U.message}`,He()}finally{oe=!1}},Bs=async M=>{if(!x)return;let U=x;S="busy",He();try{M==="kill"?await Vn(e.target,U.sessionId):await ny(e.target,U.sessionId),S="normal",x=null,U.sessionId===e.currentSessionId&&(Ve=!0);let ie;if(M==="kill")ie=U.sessionId;else{let z=a.findIndex(ue=>ue.sessionId===U.sessionId);z>=0&&(ie=a[z+1]?.sessionId??a[z-1]?.sessionId)}await Ls(ie)}catch(ie){S="normal",x=null,ae=`${M} failed: ${ie.message}`,He()}},hn=(M,U)=>{M===0!=(U===0)&&(ci(),U===0?(t.hideCursor(!1),_t()):t.hideCursor())},Ct=M=>{let U=Math.min(u-1,Math.max(0,f+M));if(U===f)return;let ie=f;f=U,vn(),Le(()=>{At(),hn(ie,f)})},Sn=()=>ae===null?!1:(ae=null,He(),!0),fs=()=>{lr(),Ee({onKey:M=>{if(M==="CTRL_C"){dt(),R({kind:"abort"});return}Qe()},onResize:()=>lr()})},wr=M=>{let U=null,ie=null,z=!0,ue=()=>{Le(()=>{if(t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${lt(M.sessionId)}`)(`
223
223
 
224
224
  `),z)t.dim.noFormat(" loading\u2026")(`
225
225
  `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
226
226
  `);else if(U!==null)for(let Ne of U)t.noFormat(` ${Ne}`)(`
227
227
  `);t(`
228
228
  `),t.dim.noFormat(" Esc / ^C to return")(`
229
- `)})};ue();let le=new AbortController,je={onKey:Ne=>{if(Ne==="ESCAPE"||Ne==="CTRL_C"){le.abort(),Qe();return}},onResize:()=>ue()};Ee(je),(async()=>{try{let Ne=await an(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(M.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:le.signal});if(!Ne.ok)throw new Error(`daemon returned HTTP ${Ne.status}`);let $e=await Ne.json(),qe=Cn($e),Gt=of(qe,M.status);U=Sc(Gt,!1).replace(/\n$/,"").split(`
230
- `)}catch(Ne){if(le.signal.aborted)return;ie=`failed to load info: ${Ne.message}`}finally{z=!1,!gt&&re[re.length-1]===je&&ue()}})()},fi=()=>{if(a.length===0){ae="no sessions to search",He();return}_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,wt=0,D=null,X=!1,F="input",T=!0,Ps(),Vt(),Ee({onKey:(U,ie,z)=>{if(F==="input"){if(X)return;if(U==="ESCAPE"||U==="CTRL_C"){Eo();return}if(U==="ENTER"||U==="KP_ENTER"){if(Ro().trim().length===0)return;ja();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&N.length>0){F="results",q=0,L=0,Le(()=>{Ao(),_n(0,!0),di(),t.hideCursor()});return}let ue=_.state(),le=[...ue.buffer],je=ue.row,Ne=ue.col,$e=null;if(U==="")$e={type:"key",name:"ctrl-underscore"};else if(U==="\x1B_"||U==="\x1B")$e={type:"key",name:"alt-underscore"};else if(z?.isCharacter)$e={type:"char",ch:U};else{let St=Gc(U);St!==null&&($e={type:"key",name:St})}if($e===null){t.moveTo(ur(),fr());return}_.feed($e);let qe=_.state();if(le.length===qe.buffer.length&&le.every((St,xe)=>St===qe.buffer[xe])&&je===qe.row&&Ne===qe.col){t.moveTo(ur(),fr());return}let Nn=pe;Ps(),pe!==Nn?Vt():Ha();return}if(F==="results"){if(U==="ESCAPE"||U==="CTRL_C"){Eo();return}if(U==="CTRL_F"){F="input",Ua(),di(),Ao();return}if(U==="ENTER"||U==="KP_ENTER"){let le=N[q];if(!le)return;let je=a.find($e=>$e.sessionId===le.sessionId);if(!!je?.importedFromMachine&&!je.upstreamSessionId){dt();let $e={kind:"attach",sessionId:le.sessionId};je.agentId!==void 0&&($e.agentId=je.agentId),R($e);return}(async()=>{let $e=await Pb(t,{sessionId:le.sessionId,title:le.title,cwd:le.cwd},Ue);if($e==="cancel"){dt(),R({kind:"abort"});return}if($e==="back")return;dt();let qe={kind:"attach",sessionId:le.sessionId,readonly:$e==="view"};je?.agentId!==void 0&&(qe.agentId=je.agentId),R(qe)})();return}if(z?.isCharacter&&(U==="n"||U==="N")){let le=N[q];if(!le||le.snippets.length<=1)return;L=(L+1)%le.snippets.length,_n(q,!0);return}if(z?.isCharacter&&(U==="p"||U==="P")){let le=N[q];if(!le||le.snippets.length<=1)return;L=(L-1+le.snippets.length)%le.snippets.length,_n(q,!0);return}let ue=le=>{if(le<0&&q===0){F="input",Le(()=>{_n(0,!1),di(),Ao()});return}let je=Math.min(N.length-1,Math.max(0,q+le));if(je===q)return;let Ne=q,$e=wt;q=je,L=0,Io(),wt!==$e?Ua():(Le(()=>{_n(Ne,!1),_n(q,!0)}),di())};switch(U){case"UP":case"SHIFT_TAB":case"CTRL_P":ue(-1);return;case"DOWN":case"TAB":case"CTRL_N":ue(1);return;case"PAGE_UP":ue(-as());return;case"PAGE_DOWN":ue(as());return;case"HOME":ue(-q);return;case"END":ue(N.length);return}return}},onResize:()=>Vt()})},br=(M,U,ie)=>{if(S!=="busy"){if(M==="CTRL_O"){pt();return}if(M==="CTRL_L"){ko();return}if(S==="rename"&&ee){if(M==="ENTER"||M==="KP_ENTER"){let z=ee.text.trim();if(z.length===0){S="normal",x=null,ee=null,He();return}$o(z);return}if(M==="ESCAPE"||M==="CTRL_C"){S="normal",x=null,ee=null,He();return}if(ee.handleKey(M,ie?.isCharacter===!0)){He();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(M==="y"||M==="Y")){Bs(S==="confirm-kill"?"kill":"delete");return}if(M==="ESCAPE"||M==="CTRL_C"||M==="ENTER"||M==="KP_ENTER"||ie?.isCharacter&&(M==="n"||M==="N")){S="normal",x=null,He();return}return}if(Sn(),M==="CTRL_F"&&f!==0){fi();return}if(f===0&&!h){if(M==="ESCAPE"){Ln();return}if(M==="ENTER"||M==="KP_ENTER"){dt();let xe=Be.expandedText(),ct=nt();xe.trim().length>0&&(ct.prompt=xe),R(ct);return}if(M==="UP"&&b){let xe=Date.now(),ct=xe-v;if(v=xe,ct<y){_t();return}b=!1}if(M==="DOWN"){let xe=Be.state(),ct=xe.historyIndex!==-1||xe.queueIndex!==-1,$t=dn.length===0||Rs===dn.length-1;if(!ct&&$t&&a.length>0){Ct(1);return}}if(M==="PAGE_DOWN"&&(dn.length===0||Rs===dn.length-1)&&a.length>0){Ct(1);return}if(M==="CTRL_P"){a.length>0&&Ct(1);return}if(b=!1,M==="TAB"){let xe=Be.state(),ct=xe.buffer[xe.row]??"",$t=tl(ct,xe.col);if($t!==null){let zt=nl($t.token,r);if(zt!==null){if(zt.replacement!==$t.token&&(Be.replaceRangeOnCurrentLine($t.start,xe.col,zt.replacement),Wt()),zt.candidates.length>1){let Ns=zt.candidates.join(" ");G=`${zt.candidates.length} matches: ${Ns}`,_s()}else ln();_t();return}}}ln();let z=Be.state(),ue=[...z.buffer],le=z.row,je=z.col,Ne=null;if(M==="")Ne={type:"key",name:"ctrl-underscore"};else if(M==="\x1B_"||M==="\x1B")Ne={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)Ne={type:"char",ch:M};else{let xe=Gc(M);xe!==null&&(Ne={type:"key",name:xe})}if(Ne===null){_t();return}let $e=Be.feed(Ne),qe=Be.state(),Gt=ue.length===qe.buffer.length&&ue.every((xe,ct)=>xe===qe.buffer[ct])&&le===qe.row&&je===qe.col;if($e.some(xe=>xe.type==="exit")){Ln();return}for(let xe of $e)xe.type==="attachment-request"&&$s();if(Gt){_t();return}let Nn=es(qe.buffer,As);if(xs(Nn,qe,Ma).rendered!==mt){Je();return}Wt();return}if(!h&&ie?.isCharacter&&M==="?"){fs();return}if(h){if(ie?.isCharacter){m+=M,Dt(),Je();return}if(M==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Dt(),Je()):(h=!1,Dt(),Je());return}if(M==="ESCAPE"||M==="CTRL_C"){h=!1,m="",Dt(),Je();return}}if(ie?.isCharacter){if(M==="/"){h=!0,m="",Dt(),Je();return}if(M==="n"||M==="N"){Ct(1);return}if(M==="p"||M==="P"){Ct(-1);return}if(M==="c"||M==="C"){let z=f>0?a[f-1]:void 0,ue=nt();z?.cwd&&(ue.cwd=z.cwd),dt(),R(ue);return}if(M==="q"||M==="Q"){Ln();return}if(M==="o"||M==="O"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Dt(),is(z),Je();return}if(M==="h"||M==="H"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Bb(s.filters.hostFilter,i),Dt(),is(z),Je();return}if(M==="i"&&f>0){let z=a[f-1];if(!z)return;wr(z);return}if(M==="I"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Dt(),is(z),Je();return}if(M==="r"||M==="R"){let z=f>0?a[f-1]?.sessionId:void 0;Ls(z);return}if(M==="s"||M==="S"){us();return}if((M==="v"||M==="V")&&f>0){let z=a[f-1];if(!z)return;dt();let ue={kind:"attach",sessionId:z.sessionId,readonly:!0};z.agentId!==void 0&&(ue.agentId=z.agentId),R(ue);return}if((M==="f"||M==="F")&&f>0){let z=a[f-1];if(!z)return;dt();let ue={kind:"fork",sourceSessionId:z.sessionId,sourceCwd:z.cwd};z.agentId!==void 0&&(ue.sourceAgentId=z.agentId),z.importedFromMachine!==void 0&&(ue.sourceImportedFromMachine=z.importedFromMachine),z.upstreamSessionId!==void 0&&(ue.sourceUpstreamSessionId=z.upstreamSessionId),R(ue);return}if((M==="k"||M==="K")&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},S="confirm-kill",He();return}if(M==="t"&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},ee=new bo(z.title??""),S="rename",He();return}if(M==="T"&&f>0){let z=a[f-1];if(!z)return;vt({sessionId:z.sessionId});return}if(M==="*"&&f>0){let z=a[f-1];if(!z)return;ls(z);return}if((M==="d"||M==="D")&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},S="confirm-delete",He();return}et=!1,f=0,Be.feed({type:"char",ch:M}),Je();return}switch(M){case"UP":case"SHIFT_TAB":case"CTRL_P":M==="UP"&&(f===1&&(b=!0),v=Date.now()),Ct(-1);return;case"DOWN":case"TAB":case"CTRL_N":Ct(1);return;case"PAGE_UP":Ct(-De);return;case"PAGE_DOWN":Ct(De);return;case"HOME":Ct(1-f);return;case"END":Ct(u);return;case"RIGHT":if(et||f===0)break;case"ENTER":case"KP_ENTER":{if(et){dt();let le=Be.expandedText(),je=nt();le.trim().length>0&&(je.prompt=le),R(je);return}if(dt(),f===0){R(nt());return}let z=a[f-1];if(!z){R({kind:"abort"});return}let ue={kind:"attach",sessionId:z.sessionId};z.agentId!==void 0&&(ue.agentId=z.agentId),R(ue);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Ln();return}}};Ee({onKey:(M,U,ie)=>br(M,U,ie),onResize:()=>{gt||Je()}});let Bn=(M,U)=>{if(gt||re.length!==1||S!=="normal")return;let ie=M==="MOUSE_MOTION",z=M==="MOUSE_LEFT_BUTTON_PRESSED",ue=M==="MOUSE_LEFT_BUTTON_RELEASED",le=M==="MOUSE_WHEEL_UP",je=M==="MOUSE_WHEEL_DOWN",Ne=Ke&&Date.now()-Po<Mo,$e=!Ke||Ne;if(z){mr={x:U?.x??-1,y:U?.y??-1},cs=$e;return}if(ie&&$e)return;let qe=ue&&mr!==null&&U?.x===mr.x&&U?.y===mr.y,Gt=qe&&!cs,Nn=qe&&cs;if(ue&&(mr=null,cs=!1,!qe))return;if(le||je){if(a.length===0)return;let Ye=le?-3:3,hs=Math.max(0,a.length-De),Rt=Math.min(hs,Math.max(0,p+Ye));if(Rt===p)return;if(p=Rt,f>0){let Sr=f-1;Sr<p?f=p+1:Sr>=p+De&&(f=p+De)}At();return}if(!ie&&!Gt)return;let St=U?.y;if(typeof St!="number")return;{let Ye=U?.x,hs=un!==null&&St===Mn()&&typeof Ye=="number"&&Ye>=un.start&&Ye<=un.end,Rt=fn!==null&&St===Mn()&&typeof Ye=="number"&&Ye>=fn.start&&Ye<=fn.end;(hs!==li||Rt!==ui)&&(li=hs,ui=Rt,He(),f===0?(_t(),t.hideCursor(!1)):t.hideCursor(!0))}if(Gt&&un!==null&&St===Mn()){let Ye=U?.x;if(typeof Ye=="number"&&Ye>=un.start&&Ye<=un.end){Ln();return}}if(Gt&&fn!==null&&St===Mn()){let Ye=U?.x;if(typeof Ye=="number"&&Ye>=fn.start&&Ye<=fn.end){let hs=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Bb(s.filters.hostFilter,i),Dt(),is(hs),Je();return}}if(St>=rs&&St<=Pt()){if((Gt||Nn)&&f!==0){et=!1;let Ye=f;f=0,Le(()=>{At(),pn(Ye,f)});return}ie&&!et&&f!==0&&(et=!0,Le(()=>{ci(),At()}));return}et&&(et=!1,Le(()=>{ci(),At()}));let ct=Mt()+1,$t=ct+De-1;if(St<ct||St>$t)return;let zt=p+(St-ct);if(zt<0||zt>=a.length)return;let Ns=a[zt];if(!Ns)return;let vr=zt+1;if(ie&&f===0)return;let al=f===0,dl=f===vr;if(Nn&&f!==vr){let Ye=f;f=vr,vn(),Le(()=>{At(),pn(Ye,f)});return}if(Nn)return;if(f!==vr){let Ye=f;f=vr,vn(),Le(()=>{At(),pn(Ye,f)})}if(!Gt||al||!dl)return;dt();let kn={kind:"attach",sessionId:Ns.sessionId};Ns.agentId!==void 0&&(kn.agentId=Ns.agentId),R(kn)},ps=()=>{t.grabInput({mouse:"motion"}),ne({src:"grab",site:"picker.installGrab",on:!0});let M=t;M.stdin&&typeof M.onStdin=="function"&&(Qt=M.onStdin,M.stdin.removeListener("data",M.onStdin),M.stdin.on("data",Fs),process.stdout.write(Rc),process.stdout.write(Pc)),t.on("key",On),t.on("mouse",Bn),t.on("resize",at)},ft=()=>{process.stdout.write(Ss),process.stdout.write(ba);let M=t;M.stdin&&Qt&&(M.stdin.removeListener("data",Fs),M.stdin.on("data",Qt),Qt=null),$n=!1,Fn="",t.off("key",On),t.off("mouse",Bn),t.off("resize",at),t.grabInput(!1),ne({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if(ps(),process.platform!=="win32"){let M=!1,U=()=>{M&&(M=!1,t.fullscreen(!0),n(),t.hideCursor(),ps(),gt||ko())};_o=()=>{M||gt||(M=!0,ft(),t.fullscreen(!1),process.stdout.write(`${wa}${Tc}
231
- `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}E=setInterval(Os,3e3)})}function iT(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+ha(st(t),s)}function sl(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 oT(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Bb(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 aT(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[lt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,st(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var np,Ma,nT,Lb,sT,rT,Nb=K(()=>{"use strict";gc();ye();qn();pa();Ad();Wc();Lf();Gf();Xf();ep();Zf();tp();zr();Bf();Nf();va();$r();af();Tr();np=2,Ma=4,nT=4,Lb=4,sT=20,rT=[["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)"]]});function uT(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function ip(t,e,n,s){Rn();let r=uT(e,n??dT),i=0,o=()=>{let u=ks(t)-8;return Math.max(1,Math.min(cT,e.length,u))},a=()=>{let u=o();r<i?i=r:r>=i+u&&(i=r-u+1);let f=Math.max(0,e.length-u);i>f&&(i=f),i<0&&(i=0)},c=()=>{a();let u=o(),f=u+4,p=Math.min(lT,Math.max(40,Jt(t)-8)),h=Tn(t,{contentHeight:f,contentWidth:p,title:s?.title??"Select agent"}),m=h.contentW,y=0;t.moveTo(h.contentX,h.contentY+y),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`),y+=2;let b=Math.min(e.length,i+u);for(let S=i;S<b;S++){let x=e[S];if(!x)continue;let T=S===r?"\u276F":" ",F=x.description??x.name,_=` ${T} ${x.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let N=`${_} ${F}`;t.brightWhite.bgBlue.noFormat(Mc(Ge(N,m),m))}else{t.noFormat(_);let N=m-_.length-2;N>1&&t.dim.noFormat(` ${Ge(F,N)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let v=e.length>u?` (${r+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${v}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return Gn({term:t,render:c,onKey:(u,f,p,h)=>{if(u==="CTRL_C"||u==="CTRL_D"){h({kind:"cancel"});return}if(u==="ESCAPE"){h({kind:"back"});return}if(u==="ENTER"||u==="KP_ENTER"){let m=e[r];m&&h({kind:"select",agentId:m.id,persist:!1});return}if(u==="UP"||u==="SHIFT_TAB"){l();return}if(u==="DOWN"||u==="TAB"){d();return}if(p?.isCharacter){let m=u.toLowerCase();if(m==="s"){let y=e[r];y&&h({kind:"select",agentId:y.id,persist:!0});return}if(m==="j"){d();return}if(m==="k"){l();return}}}})}var dT,cT,lT,Db=K(()=>{"use strict";zr();dT="opencode",cT=20,lT=88});import fT from"wrap-ansi";async function Hb(t,e,n,s){Rn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
232
- `).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=ks(t),u=Math.min(pT,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>fT(T,f,{hard:!0,trim:!1}).split(`
233
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,b=y.length+(m?1:0)+4,v=Tn(t,{contentHeight:b,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,x=0;t.moveTo(v.contentX,v.contentY+x),t.brightWhite.bold.noFormat(Ge(` ${i}`,S)),x+=2;for(let T of y)t.moveTo(v.contentX,v.contentY+x),t.brightRed.noFormat(Ge(` ${T}`,S)),x++;return m&&(t.moveTo(v.contentX,v.contentY+x),t.dim.noFormat(Ge(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),x++),x++,t.moveTo(v.contentX,v.contentY+x),t.dim.noFormat(Ge(` ${a}`,S)),v};return Gn({term:t,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var pT,Ub=K(()=>{"use strict";zr();pT=100});function jb(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 qb(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Wb(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 zb=K(()=>{"use strict"});import{readFileSync as hT}from"fs";import{nanoid as Kb}from"nanoid";import mT from"terminal-kit";import op from"fs/promises";import Gr from"path";function gT(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function yT(t){let e=rl(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function wT(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 rl(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 bT(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function vT(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=rl(o.representative),d=e[a]??0,l=n[a]?dp:c[d]??c[0]??"";return{label:bT(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 ST(t,e,n){return t===dp?{type:"dismiss",method:Jw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Kw,params:{sessionId:n,questionId:e.id,answer:t}}}function kT(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]?dp:rl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=ST(c,l,r);u!==null&&i.push(u)}}return i}function IT(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 u=rl(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.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:kT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Jb(t){if(!Array.isArray(t))return;let e=Kn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function ap(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 CT(t,e){e.has(t)?e.delete(t):e.add(t)}function RT(){if(Yb)return;Yb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{ne({src:"uncaughtException",stack:t(e)}),Yr(),process.stderr.write(`
229
+ `)})};ue();let le=new AbortController,je={onKey:Ne=>{if(Ne==="ESCAPE"||Ne==="CTRL_C"){le.abort(),Qe();return}},onResize:()=>ue()};Ee(je),(async()=>{try{let Ne=await dn(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(M.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:le.signal});if(!Ne.ok)throw new Error(`daemon returned HTTP ${Ne.status}`);let $e=await Ne.json(),qe=Cn($e),Xt=of(qe,M.status);U=Sc(Xt,!1).replace(/\n$/,"").split(`
230
+ `)}catch(Ne){if(le.signal.aborted)return;ie=`failed to load info: ${Ne.message}`}finally{z=!1,!gt&&re[re.length-1]===je&&ue()}})()},fi=()=>{if(a.length===0){ae="no sessions to search",He();return}_=new Is({history:[],collapsePastes:!1}),N=[],J=!1,q=0,L=0,wt=0,D=null,X=!1,F="input",T=!0,Ps(),Qt(),Ee({onKey:(U,ie,z)=>{if(F==="input"){if(X)return;if(U==="ESCAPE"||U==="CTRL_C"){Eo();return}if(U==="ENTER"||U==="KP_ENTER"){if(Ro().trim().length===0)return;ja();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&N.length>0){F="results",q=0,L=0,Le(()=>{Ao(),_n(0,!0),di(),t.hideCursor()});return}let ue=_.state(),le=[...ue.buffer],je=ue.row,Ne=ue.col,$e=null;if(U==="")$e={type:"key",name:"ctrl-underscore"};else if(U==="\x1B_"||U==="\x1B")$e={type:"key",name:"alt-underscore"};else if(z?.isCharacter)$e={type:"char",ch:U};else{let St=Gc(U);St!==null&&($e={type:"key",name:St})}if($e===null){t.moveTo(ur(),fr());return}_.feed($e);let qe=_.state();if(le.length===qe.buffer.length&&le.every((St,xe)=>St===qe.buffer[xe])&&je===qe.row&&Ne===qe.col){t.moveTo(ur(),fr());return}let Nn=pe;Ps(),pe!==Nn?Qt():Ha();return}if(F==="results"){if(U==="ESCAPE"||U==="CTRL_C"){Eo();return}if(U==="CTRL_F"){F="input",Ua(),di(),Ao();return}if(U==="ENTER"||U==="KP_ENTER"){let le=N[q];if(!le)return;let je=a.find($e=>$e.sessionId===le.sessionId);if(!!je?.importedFromMachine&&!je.upstreamSessionId){dt();let $e={kind:"attach",sessionId:le.sessionId};je.agentId!==void 0&&($e.agentId=je.agentId),R($e);return}(async()=>{let $e=await Mb(t,{sessionId:le.sessionId,title:le.title,cwd:le.cwd},Ue);if($e==="cancel"){dt(),R({kind:"abort"});return}if($e==="back")return;dt();let qe={kind:"attach",sessionId:le.sessionId,readonly:$e==="view"};je?.agentId!==void 0&&(qe.agentId=je.agentId),R(qe)})();return}if(z?.isCharacter&&(U==="n"||U==="N")){let le=N[q];if(!le||le.snippets.length<=1)return;L=(L+1)%le.snippets.length,_n(q,!0);return}if(z?.isCharacter&&(U==="p"||U==="P")){let le=N[q];if(!le||le.snippets.length<=1)return;L=(L-1+le.snippets.length)%le.snippets.length,_n(q,!0);return}let ue=le=>{if(le<0&&q===0){F="input",Le(()=>{_n(0,!1),di(),Ao()});return}let je=Math.min(N.length-1,Math.max(0,q+le));if(je===q)return;let Ne=q,$e=wt;q=je,L=0,Io(),wt!==$e?Ua():(Le(()=>{_n(Ne,!1),_n(q,!0)}),di())};switch(U){case"UP":case"SHIFT_TAB":case"CTRL_P":ue(-1);return;case"DOWN":case"TAB":case"CTRL_N":ue(1);return;case"PAGE_UP":ue(-as());return;case"PAGE_DOWN":ue(as());return;case"HOME":ue(-q);return;case"END":ue(N.length);return}return}},onResize:()=>Qt()})},br=(M,U,ie)=>{if(S!=="busy"){if(M==="CTRL_O"){pt();return}if(M==="CTRL_L"){ko();return}if(S==="rename"&&ee){if(M==="ENTER"||M==="KP_ENTER"){let z=ee.text.trim();if(z.length===0){S="normal",x=null,ee=null,He();return}$o(z);return}if(M==="ESCAPE"||M==="CTRL_C"){S="normal",x=null,ee=null,He();return}if(ee.handleKey(M,ie?.isCharacter===!0)){He();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(M==="y"||M==="Y")){Bs(S==="confirm-kill"?"kill":"delete");return}if(M==="ESCAPE"||M==="CTRL_C"||M==="ENTER"||M==="KP_ENTER"||ie?.isCharacter&&(M==="n"||M==="N")){S="normal",x=null,He();return}return}if(Sn(),M==="CTRL_F"&&f!==0){fi();return}if(f===0&&!h){if(M==="ESCAPE"){Ln();return}if(M==="ENTER"||M==="KP_ENTER"){dt();let xe=Be.expandedText(),ct=nt();xe.trim().length>0&&(ct.prompt=xe),R(ct);return}if(M==="UP"&&b){let xe=Date.now(),ct=xe-v;if(v=xe,ct<y){_t();return}b=!1}if(M==="DOWN"){let xe=Be.state(),ct=xe.historyIndex!==-1||xe.queueIndex!==-1,$t=cn.length===0||Rs===cn.length-1;if(!ct&&$t&&a.length>0){Ct(1);return}}if(M==="PAGE_DOWN"&&(cn.length===0||Rs===cn.length-1)&&a.length>0){Ct(1);return}if(M==="CTRL_P"){a.length>0&&Ct(1);return}if(b=!1,M==="TAB"){let xe=Be.state(),ct=xe.buffer[xe.row]??"",$t=tl(ct,xe.col);if($t!==null){let Kt=nl($t.token,r);if(Kt!==null){if(Kt.replacement!==$t.token&&(Be.replaceRangeOnCurrentLine($t.start,xe.col,Kt.replacement),zt()),Kt.candidates.length>1){let Ns=Kt.candidates.join(" ");G=`${Kt.candidates.length} matches: ${Ns}`,_s()}else un();_t();return}}}un();let z=Be.state(),ue=[...z.buffer],le=z.row,je=z.col,Ne=null;if(M==="")Ne={type:"key",name:"ctrl-underscore"};else if(M==="\x1B_"||M==="\x1B")Ne={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)Ne={type:"char",ch:M};else{let xe=Gc(M);xe!==null&&(Ne={type:"key",name:xe})}if(Ne===null){_t();return}let $e=Be.feed(Ne),qe=Be.state(),Xt=ue.length===qe.buffer.length&&ue.every((xe,ct)=>xe===qe.buffer[ct])&&le===qe.row&&je===qe.col;if($e.some(xe=>xe.type==="exit")){Ln();return}for(let xe of $e)xe.type==="attachment-request"&&$s();if(Xt){_t();return}let Nn=es(qe.buffer,As);if(xs(Nn,qe,Ma).rendered!==mt){Je();return}zt();return}if(!h&&ie?.isCharacter&&M==="?"){fs();return}if(h){if(ie?.isCharacter){m+=M,Dt(),Je();return}if(M==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Dt(),Je()):(h=!1,Dt(),Je());return}if(M==="ESCAPE"||M==="CTRL_C"){h=!1,m="",Dt(),Je();return}}if(ie?.isCharacter){if(M==="/"){h=!0,m="",Dt(),Je();return}if(M==="n"||M==="N"){Ct(1);return}if(M==="p"||M==="P"){Ct(-1);return}if(M==="c"||M==="C"){let z=f>0?a[f-1]:void 0,ue=nt();z?.cwd&&(ue.cwd=z.cwd),dt(),R(ue);return}if(M==="q"||M==="Q"){Ln();return}if(M==="o"||M==="O"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Dt(),is(z),Je();return}if(M==="h"||M==="H"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Nb(s.filters.hostFilter,i),Dt(),is(z),Je();return}if(M==="i"&&f>0){let z=a[f-1];if(!z)return;wr(z);return}if(M==="I"){let z=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Dt(),is(z),Je();return}if(M==="r"||M==="R"){let z=f>0?a[f-1]?.sessionId:void 0;Ls(z);return}if(M==="s"||M==="S"){us();return}if((M==="v"||M==="V")&&f>0){let z=a[f-1];if(!z)return;dt();let ue={kind:"attach",sessionId:z.sessionId,readonly:!0};z.agentId!==void 0&&(ue.agentId=z.agentId),R(ue);return}if((M==="f"||M==="F")&&f>0){let z=a[f-1];if(!z)return;dt();let ue={kind:"fork",sourceSessionId:z.sessionId,sourceCwd:z.cwd};z.agentId!==void 0&&(ue.sourceAgentId=z.agentId),z.importedFromMachine!==void 0&&(ue.sourceImportedFromMachine=z.importedFromMachine),z.upstreamSessionId!==void 0&&(ue.sourceUpstreamSessionId=z.upstreamSessionId),R(ue);return}if((M==="k"||M==="K")&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},S="confirm-kill",He();return}if(M==="t"&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},ee=new bo(z.title??""),S="rename",He();return}if(M==="T"&&f>0){let z=a[f-1];if(!z)return;vt({sessionId:z.sessionId});return}if(M==="*"&&f>0){let z=a[f-1];if(!z)return;ls(z);return}if((M==="d"||M==="D")&&f>0){let z=a[f-1];if(!z)return;x={sessionId:z.sessionId,cwd:z.cwd,status:z.status},S="confirm-delete",He();return}et=!1,f=0,Be.feed({type:"char",ch:M}),Je();return}switch(M){case"UP":case"SHIFT_TAB":case"CTRL_P":M==="UP"&&(f===1&&(b=!0),v=Date.now()),Ct(-1);return;case"DOWN":case"TAB":case"CTRL_N":Ct(1);return;case"PAGE_UP":Ct(-De);return;case"PAGE_DOWN":Ct(De);return;case"HOME":Ct(1-f);return;case"END":Ct(u);return;case"RIGHT":if(et||f===0)break;case"ENTER":case"KP_ENTER":{if(et){dt();let le=Be.expandedText(),je=nt();le.trim().length>0&&(je.prompt=le),R(je);return}if(dt(),f===0){R(nt());return}let z=a[f-1];if(!z){R({kind:"abort"});return}let ue={kind:"attach",sessionId:z.sessionId};z.agentId!==void 0&&(ue.agentId=z.agentId),R(ue);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Ln();return}}};Ee({onKey:(M,U,ie)=>br(M,U,ie),onResize:()=>{gt||Je()}});let Bn=(M,U)=>{if(gt||re.length!==1||S!=="normal")return;let ie=M==="MOUSE_MOTION",z=M==="MOUSE_LEFT_BUTTON_PRESSED",ue=M==="MOUSE_LEFT_BUTTON_RELEASED",le=M==="MOUSE_WHEEL_UP",je=M==="MOUSE_WHEEL_DOWN",Ne=Ke&&Date.now()-Po<Mo,$e=!Ke||Ne;if(z){mr={x:U?.x??-1,y:U?.y??-1},cs=$e;return}if(ie&&$e)return;let qe=ue&&mr!==null&&U?.x===mr.x&&U?.y===mr.y,Xt=qe&&!cs,Nn=qe&&cs;if(ue&&(mr=null,cs=!1,!qe))return;if(le||je){if(a.length===0)return;let Ye=le?-3:3,hs=Math.max(0,a.length-De),Rt=Math.min(hs,Math.max(0,p+Ye));if(Rt===p)return;if(p=Rt,f>0){let Sr=f-1;Sr<p?f=p+1:Sr>=p+De&&(f=p+De)}At();return}if(!ie&&!Xt)return;let St=U?.y;if(typeof St!="number")return;{let Ye=U?.x,hs=fn!==null&&St===Mn()&&typeof Ye=="number"&&Ye>=fn.start&&Ye<=fn.end,Rt=pn!==null&&St===Mn()&&typeof Ye=="number"&&Ye>=pn.start&&Ye<=pn.end;(hs!==li||Rt!==ui)&&(li=hs,ui=Rt,He(),f===0?(_t(),t.hideCursor(!1)):t.hideCursor(!0))}if(Xt&&fn!==null&&St===Mn()){let Ye=U?.x;if(typeof Ye=="number"&&Ye>=fn.start&&Ye<=fn.end){Ln();return}}if(Xt&&pn!==null&&St===Mn()){let Ye=U?.x;if(typeof Ye=="number"&&Ye>=pn.start&&Ye<=pn.end){let hs=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Nb(s.filters.hostFilter,i),Dt(),is(hs),Je();return}}if(St>=rs&&St<=Pt()){if((Xt||Nn)&&f!==0){et=!1;let Ye=f;f=0,Le(()=>{At(),hn(Ye,f)});return}ie&&!et&&f!==0&&(et=!0,Le(()=>{ci(),At()}));return}et&&(et=!1,Le(()=>{ci(),At()}));let ct=Mt()+1,$t=ct+De-1;if(St<ct||St>$t)return;let Kt=p+(St-ct);if(Kt<0||Kt>=a.length)return;let Ns=a[Kt];if(!Ns)return;let vr=Kt+1;if(ie&&f===0)return;let al=f===0,dl=f===vr;if(Nn&&f!==vr){let Ye=f;f=vr,vn(),Le(()=>{At(),hn(Ye,f)});return}if(Nn)return;if(f!==vr){let Ye=f;f=vr,vn(),Le(()=>{At(),hn(Ye,f)})}if(!Xt||al||!dl)return;dt();let kn={kind:"attach",sessionId:Ns.sessionId};Ns.agentId!==void 0&&(kn.agentId=Ns.agentId),R(kn)},ps=()=>{t.grabInput({mouse:"motion"}),ne({src:"grab",site:"picker.installGrab",on:!0});let M=t;M.stdin&&typeof M.onStdin=="function"&&(Gt=M.onStdin,M.stdin.removeListener("data",M.onStdin),M.stdin.on("data",Fs),process.stdout.write(Rc),process.stdout.write(Pc)),t.on("key",On),t.on("mouse",Bn),t.on("resize",at)},ft=()=>{process.stdout.write(Ss),process.stdout.write(ba);let M=t;M.stdin&&Gt&&(M.stdin.removeListener("data",Fs),M.stdin.on("data",Gt),Gt=null),$n=!1,Fn="",t.off("key",On),t.off("mouse",Bn),t.off("resize",at),t.grabInput(!1),ne({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if(ps(),process.platform!=="win32"){let M=!1,U=()=>{M&&(M=!1,t.fullscreen(!0),n(),t.hideCursor(),ps(),gt||ko())};_o=()=>{M||gt||(M=!0,ft(),t.fullscreen(!1),process.stdout.write(`${wa}${Tc}
231
+ `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}E=setInterval(Os,3e3)})}function oT(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+ha(st(t),s)}function sl(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 aT(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Nb(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 dT(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[lt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,st(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var np,Ma,sT,Bb,rT,iT,Db=K(()=>{"use strict";gc();ye();qn();pa();Ad();Wc();Lf();Gf();Xf();ep();Zf();tp();zr();Bf();Nf();va();$r();af();Tr();np=2,Ma=4,sT=4,Bb=4,rT=20,iT=[["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)"]]});function fT(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function ip(t,e,n,s){Rn();let r=fT(e,n??cT),i=0,o=()=>{let u=ks(t)-8;return Math.max(1,Math.min(lT,e.length,u))},a=()=>{let u=o();r<i?i=r:r>=i+u&&(i=r-u+1);let f=Math.max(0,e.length-u);i>f&&(i=f),i<0&&(i=0)},c=()=>{a();let u=o(),f=u+4,p=Math.min(uT,Math.max(40,Yt(t)-8)),h=Tn(t,{contentHeight:f,contentWidth:p,title:s?.title??"Select agent"}),m=h.contentW,y=0;t.moveTo(h.contentX,h.contentY+y),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`),y+=2;let b=Math.min(e.length,i+u);for(let S=i;S<b;S++){let x=e[S];if(!x)continue;let T=S===r?"\u276F":" ",F=x.description??x.name,_=` ${T} ${x.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let N=`${_} ${F}`;t.brightWhite.bgBlue.noFormat(Mc(Ge(N,m),m))}else{t.noFormat(_);let N=m-_.length-2;N>1&&t.dim.noFormat(` ${Ge(F,N)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let v=e.length>u?` (${r+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${v}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return Gn({term:t,render:c,onKey:(u,f,p,h)=>{if(u==="CTRL_C"||u==="CTRL_D"){h({kind:"cancel"});return}if(u==="ESCAPE"){h({kind:"back"});return}if(u==="ENTER"||u==="KP_ENTER"){let m=e[r];m&&h({kind:"select",agentId:m.id,persist:!1});return}if(u==="UP"||u==="SHIFT_TAB"){l();return}if(u==="DOWN"||u==="TAB"){d();return}if(p?.isCharacter){let m=u.toLowerCase();if(m==="s"){let y=e[r];y&&h({kind:"select",agentId:y.id,persist:!0});return}if(m==="j"){d();return}if(m==="k"){l();return}}}})}var cT,lT,uT,Hb=K(()=>{"use strict";zr();cT="opencode",lT=20,uT=88});import pT from"wrap-ansi";async function Ub(t,e,n,s){Rn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
232
+ `).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=Yt(t),l=ks(t),u=Math.min(hT,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>pT(T,f,{hard:!0,trim:!1}).split(`
233
+ `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,b=y.length+(m?1:0)+4,v=Tn(t,{contentHeight:b,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,x=0;t.moveTo(v.contentX,v.contentY+x),t.brightWhite.bold.noFormat(Ge(` ${i}`,S)),x+=2;for(let T of y)t.moveTo(v.contentX,v.contentY+x),t.brightRed.noFormat(Ge(` ${T}`,S)),x++;return m&&(t.moveTo(v.contentX,v.contentY+x),t.dim.noFormat(Ge(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),x++),x++,t.moveTo(v.contentX,v.contentY+x),t.dim.noFormat(Ge(` ${a}`,S)),v};return Gn({term:t,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var hT,jb=K(()=>{"use strict";zr();hT=100});function qb(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 Wb(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function zb(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 Kb=K(()=>{"use strict"});import{readFileSync as mT}from"fs";import{nanoid as Jb}from"nanoid";import gT from"terminal-kit";import op from"fs/promises";import Gr from"path";function yT(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function wT(t){let e=rl(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function bT(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 rl(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 vT(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function ST(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=rl(o.representative),d=e[a]??0,l=n[a]?dp:c[d]??c[0]??"";return{label:vT(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 kT(t,e,n){return t===dp?{type:"dismiss",method:Jw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Kw,params:{sessionId:n,questionId:e.id,answer:t}}}function IT(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]?dp:rl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=kT(c,l,r);u!==null&&i.push(u)}}return i}function xT(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 u=rl(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.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:IT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Yb(t){if(!Array.isArray(t))return;let e=Kn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function ap(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 RT(t,e){e.has(t)?e.delete(t):e.add(t)}function TT(){if(Vb)return;Vb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{ne({src:"uncaughtException",stack:t(e)}),Yr(),process.stderr.write(`
234
234
  uncaught: ${t(e)}
235
235
  `),process.exit(1)}),process.on("unhandledRejection",e=>{ne({src:"unhandledRejection",stack:t(e)}),Yr(),process.stderr.write(`
236
236
  unhandled rejection: ${t(e)}
237
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&ne({src:"process-exit",code:e})})}async function Gb(t){RT();let e=await Ie(),n=t.target??await Ut(e);Qp(e.tui.logMaxBytes),n.isLocal&&!t.target&&await Vs(e);let s=mT.terminal;Rb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Ap(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=sp(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
238
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await ET(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await ka();if(f&&process.stderr.write(`\u2728 ${Ia(f)}
237
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&ne({src:"process-exit",code:e})})}async function Xb(t){TT();let e=await Ie(),n=t.target??await Ut(e);Qp(e.tui.logMaxBytes),n.isLocal&&!t.target&&await Vs(e);let s=gT.terminal;Tb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Ap(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=sp(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
238
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await PT(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await ka();if(f&&process.stderr.write(`\u2728 ${Ia(f)}
239
239
  `),process.stdout.isTTY){let p=await Lr(e);if(p?.version!==void 0){let h=p.version!==me,m=zs(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let b=h?`daemon ${p.version} \u2260 cli ${me}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Dn()} daemon restart\` to apply.`)+`
240
240
  `)}}}if(r.sessionId&&process.stdout.isTTY){let p=lt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Dn()} --session ${p}${h}
241
- `)}}function TT(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 J=Math.max(0,c-a),q=e.slice(J),L=[];for(let D=0;D<J;D++){let X=e[D];if(X===void 0)continue;let ee=n.get(X);ee&&!ef(ee.status)&&L.push(X)}l=[...L,...q]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",b=y?`amended \xB7 ${Qn(h)}`:`stopped (${m}) \xB7 ${Qn(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${Qn(h)}`:`thought \xB7 ${Qn(h)}`;else{let J=c===1?"tool":"tools",q=m!==null?b:f?Qn(h):`took ${Qn(h)}`,L=[`${c} ${J}`,q];f&&d&&u>0&&L.push(`${u} hidden`),v=L.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",_=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?x:"dim"}],N=[null];for(let J of l){let q=n.get(J);if(q){let L=ga(q,p);for(let D of L)D.hoverSubKey=J;if(_.push(...L),N.push(...L.map(()=>J)),o?.has(J)){let D=Iy(q);for(let X of D)X.hoverSubKey=J;_.push(...D),N.push(...D.map(()=>J))}}}return{lines:_,rowOwners:N}}async function ET(t,e,n,s,r,i,o){let a=await PT(t,e,n,s,o,i);if(!a)return t.grabInput(!1),ne({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=_T(t,c);d.write(c);let l=n.isLocal?async()=>(await Ut(await Ie())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new fo({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>ne({src:"resilient-ws",line:g})}),m=new Kt(h);await h.start(),m.onNotification(ld,g=>{let w=_h.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,x=(g,w)=>{g&&(b?b(g,w):y.push({event:g,rawUpdate:w}))},T,F=g=>{g!==T&&(T=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},_=null,N=null,J=!1,q=0,L=0,D=!1,X=!1,ee,ae=null,G=null,fe=null,Ve=null,Be=()=>setInterval(()=>{if(ae===null||Y===null)return;let g=Ve===null?0:Date.now()-Ve;Y.setBanner({elapsedMs:Date.now()-ae,stalled:g>=xT}),Rt()},1e3),ns=!1,ve=g=>{let w=L;L=Math.max(0,L+g);let k=typeof Y<"u"&&Y!==null;w===0&&L>0?(X=!1,ae=Date.now(),Ve=Date.now(),Se?.setTurnRunning(!0),k&&Y.setBanner({status:"busy",elapsedMs:0,stalled:!1}),G===null&&k&&(G=Be())):w>0&&L===0?(X=!1,ae=null,Ve=null,Se?.setTurnRunning(!1),G!==null&&(clearInterval(G),G=null),k&&Y.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&X&&(X=!1,k&&Y.setBanner({status:"busy",stalled:!1}))},Y=null,Se=null,De,Yt=null,As=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"]),dn=g=>{let{update:w}=g??{},k=Kn(w,{cwd:Ke});MT(w,k),Ve=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!As.has(C)){let A=w??{};typeof A.messageId=="string"&&(De=A.messageId)}if(C==="prompt_received"?ve(1):k?.kind==="turn-complete"&&(ve(-1),J=!0),C==="permission_resolved"){So(w);return}if(C==="hydra_compaction"){vo(w);return}if(C==="clarifier_question_asked"){let A=w,P=typeof A.question?.question=="string"?A.question.question:"",H=P.length>50?P.slice(0,49)+"\u2026":P;I.notify(H?`new question: ${H} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(x(k,w),La(w))};m.onNotification("session/update",g=>{if(!v){if(Yt!==null){Yt.push(g);return}dn(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&ve(-L),typeof Y<"u"&&Y!==null&&Y.setBanner({status:"cold",elapsedMs:void 0})});let mt=new Map,Cs=200,Rs=0,ss=!1,Xr=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,P=setTimeout(()=>{v||(mt.delete(C),Ue.set(C,Qe(C,A)),Y&&Se&&dt())},Cs);mt.set(C,P)}else Ue.set(w.messageId,Qe(w.messageId,w.prompt)),Y&&Se&&dt();if(Es!==void 0&&w.originator?.clientId===Es){let C=nt.shift();C&&(C.messageId=w.messageId,pt.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!Ue.has(w.messageId))return;Ue.set(w.messageId,Qe(w.messageId,w.prompt));let k=pt.get(w.messageId);if(k){let C=Array.isArray(w.prompt)?w.prompt:[],A="",P=[];for(let H of C){if(!H||typeof H!="object")continue;let O=H;O.type==="text"&&typeof O.text=="string"?A+=O.text:O.type==="image"&&typeof O.data=="string"&&typeof O.mimeType=="string"&&P.push({data:O.data,mimeType:O.mimeType,sizeBytes:Math.floor(O.data.length*3/4)})}k.text=A,k.attachments=P}Y&&Se&&dt()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(ee=w.messageId);let k=mt.get(w.messageId);k!==void 0&&(clearTimeout(k),mt.delete(w.messageId)),Ue.delete(w.messageId)&&Y&&Se&&dt();let A=pt.get(w.messageId);A&&(pt.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),at=A))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let w=g??{};if(!(typeof Y<"u"&&Y!==null))return;Rs=Date.now(),ss=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),m.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let k=w.cancelledMessageId;On.add(k),at!==null&&at.messageId!==void 0&&at.messageId===k&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),at=null,On.delete(k))});let vo=g=>{let w=g??{},k=typeof w.phase=="string"?w.phase:void 0;if(k==="started")I.setCompactionIndicator("compacting...");else if(k==="iteration")I.setCompactionIndicator("compacting...");else if(k==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(k==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(k==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(k==="failed"){I.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},rs=()=>{fe===null&&(fe=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(we)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),fe!==null&&(clearInterval(fe),fe=null)):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),fe!==null&&(clearInterval(fe),fe=null))}catch{}},5e3))},Oa=()=>{fe!==null&&(clearInterval(fe),fe=null)},So=g=>{let w=g??{},k=typeof w.toolCallId=="string"?w.toolCallId:void 0,C;w.outcome&&typeof w.outcome=="object"?C=w.outcome:typeof w.chosenOptionId=="string"&&(C={kind:"selected",optionId:w.chosenOptionId}),Ts(k,C?{outcome:C}:void 0)},pe=null,Ts=(g,w)=>{if(!pe||pe.toolCallId&&g&&pe.toolCallId!==g)return;let k=pe.resolve;pe=null,I.setPermissionPrompt(null),k(w??{outcome:{outcome:"cancelled"}})},La=g=>{if(!pe?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===pe.toolCallId&&(!w.status||w.status==="pending"||Ts(w.toolCallId,void 0))},Zr=()=>{if(!pe){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:pe.title,detail:pe.detail,options:pe.options.map(g=>({label:g.name})),selectedIndex:pe.selectedIndex})},ei=g=>{if(!pe)return;let{options:w,resolve:k}=pe;if(pe=null,I.setPermissionPrompt(null),g===null){k({outcome:{outcome:"cancelled"}});return}k({outcome:{outcome:"selected",optionId:g}})};m.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Kr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(V=>({optionId:V.optionId,name:Te(V.name??""),...V.kind!==void 0?{kind:V.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",P=Te(A),H=Te(kw(Sw(g))),O=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${P} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(V=>{pe={title:P,detail:H,options:C,selectedIndex:0,resolve:V,toolCallId:O},Zr()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let ti,Dt,is=!0,vn=!1;try{let g=await m.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:me}});Dt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(is=!1),vn=tn(g?._meta??void 0).prompt?.amending===!0}catch{}let we=a.sessionId,et=a.agentId,Ke=a.cwd,gt,Es,ni,rr,si,ri,ir,En,ii,Pn,or=!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 w={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Lt]:g}}:{}},k;try{k=await fw({request:()=>m.request("session/new",w),showBanner:(P,H,O)=>pw(t,P,H,O,{authenticate:V=>m.request("authenticate",{methodId:V})}),resolveOnboarding:async P=>{if(P)try{return(await uc(n)).find(V=>V.id===P)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(P){t.grabInput(!1),ne({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let H=P instanceof Error?P.message:String(P);ne({src:"session-new-failed",agentId:s.agentId??null,message:H});let O=await Hb(t,s.agentId,H,{canGoBack:!s.forceNew});if(O==="cancel")return null;let V={...s};return delete V.sessionId,delete V.resume,O==="retry"?V.forceNew=!0:(delete V.forceNew,delete V.agentId),V}if(k.kind==="cancel")return t.grabInput(!1),ne({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(k.kind==="back"){t.grabInput(!1),ne({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let P={...s};return delete P.sessionId,delete P.forceNew,delete P.resume,delete P.agentId,P}let C=k.result;d.write(c),we=C.sessionId,r.sessionId=we,r.readonly=!1;let A=tn(C._meta??void 0);A.clientId&&(Es=A.clientId),ti=A.upstreamSessionId,A.agentId&&(et=A.agentId),A.cwd&&(Ke=A.cwd),A.title&&(gt=A.title),ni=A.currentModel,rr=A.currentMode,ii=A.currentUsage,Pn=A.turnStartedAt,A.availableCommands&&(si=qd(A.availableCommands)),A.availableModes&&(ri=A.availableModes),ir=Jb(C.configOptions),En=A.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 w=await m.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:me},...Object.keys(g).length>0?{_meta:{[Lt]:g}}:{}});we=w.sessionId,w.clientId&&(Es=w.clientId),r.sessionId=we,r.readonly=s.readonly===!0;let k=tn(w._meta??void 0);or=k.resurrected===!0,ti=k.upstreamSessionId,k.agentId&&(et=k.agentId),k.cwd&&(Ke=k.cwd),k.title&&(gt=k.title),ni=k.currentModel,rr=k.currentMode,ii=k.currentUsage,Pn=k.turnStartedAt,k.availableCommands&&(si=qd(k.availableCommands)),k.availableModes&&(ri=k.availableModes),ir=Jb(w.configOptions),En=k.queue}let ar=$.tuiHistoryFile(we),He=$.globalTuiHistoryFile(),Et=await Qo(ar).catch(()=>[]),Pt=await Qo(He).catch(()=>[]);Pt.length>e.tui.promptHistoryMaxEntries&&(Pt=Pt.slice(Pt.length-e.tui.promptHistoryMaxEntries));let Mt=[...Et],_e=new Is({history:xd(Pt,Mt)});Se=_e;let Mn=!1,_t=(g,w)=>{let k=g.replace(/\n+$/,"");if(k.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Go(Et,k),P=A!==Et;Et=A,Mt=Go(Mt,C);let H=Go(Pt,k,e.tui.promptHistoryMaxEntries),O=H!==Pt;Pt=H,_e.setHistory(xd(Pt,Mt)),P&&_r(ar,Et).catch(()=>{}),O&&Pm(He,k).catch(()=>{})};L>0&&_e.setTurnRunning(!0);let Ht=null,dr=null;xb(Ab(e.tui.ambiguousWidth,process.env)),Ay(e.tui.diffContextLines);let cr=!1,I,oi=()=>{cr&&(cr=!1,I.start())},Ba=()=>{cr||(cr=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",oi);let os=null,Je=null;I=new Qc({term:t,dispatcher:_e,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"?Ba:void 0,onBlockClick:(g,w)=>{wv(g,w)},onBlockDoubleClick:(g,w)=>yv(g,w),onHydraLinkClick:g=>(B(g),!0),onBlockVisible:g=>{hv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=ps.get(g);if(w!==void 0&&w.length>0)return new Set(w);let k=I.contiguousRun(g,new Set(Bn.keys()));return k.length>0?new Set(k):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){os=I.bannerHitAt(g.x,g.y),Je=os?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let k=Je,C=os;if(Je=null,os=null,C!==null&&k!==null&&k.x===g.x&&k.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){yr(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&ap(A))return;Q(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&ap(w)||Q(w)},onKey:g=>{for(let w of g){if(D&&Eo(w)){w.type==="key"&&ne({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(pe&&Ao(w)){w.type==="key"&&ne({src:"key-swallowed",site:"permission",name:w.name});continue}if(ci(w)){w.type==="key"&&ne({src:"key-swallowed",site:"help",name:w.name});continue}if(_o(w)){w.type==="key"&&ne({src:"key-swallowed",site:"questions",name:w.name});continue}if(Qt(w)){w.type==="key"&&ne({src:"key-swallowed",site:"options",name:w.name});continue}if(fr(w)){w.type==="key"&&ne({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(xo(w)){w.type==="key"&&ne({src:"key-swallowed",site:"completion",name:w.name});continue}if(ur(w)){w.type==="key"&&ne({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){oe(w.paths);continue}let k=_e.feed(w);for(let C of k)s.readonly===!0&&ap(C)||Q(C)}Ps(),I.setBannerSearchIndicator(_e.state().historySearchQuery),I.setAttachments(_e.state().attachments),I.refreshPrompt()}}),Y=I,I.setStickyBottomKey("plan");let ko=[{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]"}],lr=si??[],yt=ri??[],Na=ir??[],wt=()=>Na.find(g=>g.id==="agent"),as=()=>{let g=new Set,w=[];for(let k of[...ko,...lr])g.has(k.name)||(g.add(k.name),w.push(k));return w},Io=()=>{let g=_e.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let k=w.indexOf(" "),C=k===-1?w:w.slice(0,k);if(C.lastIndexOf("/")>0)return[];let A=as().filter(P=>P.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},ds=[],Ps=()=>{let g=Io();if(g.length>0){ds=[],I.setCompletions(g);return}I.setCompletions(ds)},xo=g=>{if(g.type!=="key"||g.name!=="tab")return ds.length>0&&(ds=[]),!1;let w=Io();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){ds=[];let k=_e.state().buffer[0]??"",C=Mb({matches:w.map(A=>A.name),firstLine:k});return C===null||_e.replaceFirstLine(C),!0}return Da()},Da=()=>{let g=_e.state(),w=g.buffer[g.row]??"",k=tl(w,g.col);if(k===null)return!1;let C=nl(k.token,Ke);return C===null?!1:(C.replacement!==k.token&&_e.replaceRangeOnCurrentLine(k.start,g.col,C.replacement),ds=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},ur=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay(),!0),fr=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let w=I.scrollbackSearchTerm();return w.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Ao=g=>{if(!pe)return!1;let w=pe.options;if(g.type==="key")switch(g.name){case"up":return pe.selectedIndex=Math.max(0,pe.selectedIndex-1),Zr(),!0;case"down":return pe.selectedIndex=Math.min(w.length-1,pe.selectedIndex+1),Zr(),!0;case"enter":{let k=w[pe.selectedIndex];return k&&ei(k.optionId),!0}case"escape":case"ctrl-c":return ei(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let k=parseInt(g.ch,10)-1,C=w[k];return C&&ei(C.optionId),!0}return!0},Ha=et||Dt||"?",cn={...ii??{}};d.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:Ha,cwd:Ke,sessionId:we,title:gt,model:ni,usage:{...cn}}),rr&&I.setBanner({currentMode:rr}),ka().then(g=>{g&&I.notify(`\u2728 ${Ia(g)}`,3e4)}).catch(()=>{});let bt=null,Co=new Promise(g=>{bt=g}),ai=()=>{m.notify("session/cancel",{sessionId:we}).catch(()=>{})},Ms=()=>{Y!==null&&L===1&&(X=!0,Y.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Vt=()=>{if(Ht){Ht.cancel(),Ms();return}if(L>0){ai(),Ms();return}_n()},_n=()=>{Fs(0)},di=()=>{let g="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",w]],...AT]},Ua=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:di(),hint:"any key dismisses \xB7 /help lists commands"})},Ro=()=>{D=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=we;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},To=()=>{D=!1,I.setCompactionPrompt(null)},ja=g=>{let w=I.compactionPromptSpec();if(!w)return;let k=w.options.length;if(k===0)return;let C=((w.selectedIndex+g)%k+k)%k;C!==w.selectedIndex&&I.setCompactionPrompt({...w,selectedIndex:C})},Eo=g=>{if(!D)return!1;if(g.type==="key"){if(g.name==="escape")return To(),!0;if(g.name==="up")return ja(-1),!0;if(g.name==="down")return ja(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?Ro():To(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return Ro(),!0;if(w==="n"||w==="2")return To(),!0}return!0},ci=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,_s=["tools","plan","thoughts","diffs","mouse","enter"],ln=0,Wt=null,$s=[],pr=[],At=[],hr=0,$n=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}},Fn=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"}},Po=()=>({title:"Session options",options:_s.map(g=>({label:Fn(g),value:$n(g)})),selectedIndex:ln}),Mo=()=>{I.isOptionsPromptActive()&&Wt===null&&I.setOptionsPrompt(Po())},mr=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}ln=0,I.setOptionsPrompt(Po())},cs=()=>{if(Wt===null)return;let g=vT(Wt,$s,At,hr);I.setOptionsPrompt(g)},un=()=>{Wt=null,$s=[],pr=[],At=[],hr=0,I.setOptionsPrompt(null)},li=async()=>{if(Wt!==null){un();return}try{let w=await m.request(zw,{sessionId:we}),k=gT(w.questions??[]);if(k.length===0){I.notify("no open questions");return}let C=wT(k);Wt=C,hr=0,$s=C.map(A=>yT(A.representative)),pr=C.map(()=>!1),At=C.map(()=>!1),cs()}catch(g){I.notify("clarifier unavailable"),ne({src:"questions",step:"list_failed",error:g.message})}},fn=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,wr.clear(),fi.clear(),lv();break;case"plan":i.planExpanded=!i.planExpanded,z=null,Ne();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",us.clear(),mv();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Mo()},ui=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${Fn(g)} is session-only \u2014 not saved`);return;case"thoughts":await Oo("showThoughts",i.showThoughts);break;case"diffs":await Oo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Oo("mouse",i.mouseEnabled);break;case"enter":await Oo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${Fn(g)} ${$n(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Qt=g=>{if(Wt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return ln=Math.max(0,ln-1),Mo(),!0;case"down":return ln=Math.min(_s.length-1,ln+1),Mo(),!0;case"enter":{let w=_s[ln];return w&&fn(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,k=_s[w];return k&&(ln=w,fn(k)),!0}if(g.ch==="s"||g.ch==="S"){let w=_s[ln];return w&&ui(w),!0}}return!0},_o=g=>{if(Wt===null)return!1;let w=IT(g,!0,Wt,$s,pr,At,hr,we);switch(w.type){case"noop":return!0;case"row":return hr=w.selectedRow,cs(),!0;case"cycle":return $s[w.selectedRow]=w.newValueIndex,pr[w.selectedRow]=!0,At[w.selectedRow]=!1,cs(),!0;case"dismiss-toggle":{let k=w.selectedRow;return At[k]?(At[k]=!1,pr[k]=!1):(At[k]=!0,pr[k]=!0),cs(),!0}case"discard":return un(),!0;case"save":{let k=w.dispatches;return un(),k.length===0||(async()=>{let C=0,A=0,P=0;for(let O of k)try{await m.request(O.method,O.params),O.type==="dismiss"?A++:C++}catch(V){P++,ne({src:"questions",step:"dispatch_failed",method:O.method,error:V.message})}let H=[];C>0&&H.push(`${C} answered`),A>0&&H.push(`${A} dismissed`),P>0&&H.push(`${P} failed`),H.length>0&&I.notify(`clarifier: ${H.join(", ")}`)})(),!0}}return!1},qa=()=>{v=!0,_?(_.cancel(),_=null,N=null):N!==null&&(Vn(n,N).catch(()=>{}),N=null),process.off("SIGINT",Vt),process.platform!=="win32"&&process.off("SIGCONT",oi),G!==null&&(clearInterval(G),G=null),fe!==null&&(clearInterval(fe),fe=null);for(let g of mt.values())clearTimeout(g);mt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),_r(ar,Et).catch(()=>{}),h.close().catch(()=>{})},Fs=(g=0)=>{qa(),bt&&(bt(null),bt=null),g!==0&&process.exit(g)},R=async()=>{if(ne({src:"switch-session",step:"entered",finishSessionNull:bt===null}),!bt)return;_?(_.cancel(),_=null,N=null):N!==null&&(Vn(n,N).catch(()=>{}),N=null),Oa(),I.setSynthesisIndicator(null);let g=_e.state().buffer.join(`
242
- `);g.replace(/\s+$/,"").length>0&&_t(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),_r(ar,Et).catch(()=>{});let w=!1;try{let k=null,C=null;for(;k===null;){let O=await Yn(n,{includeNonInteractive:!0}),V=await rp(t,{cwd:Ke,sessions:O,config:e,target:n,currentSessionId:we,prefs:o});if(V.kind==="abort")return;if(V.kind==="exit"){w=!0,Fs(0);return}if(V.kind==="new"){k={choice:V,sessions:O};break}if(V.kind==="fork"){let Ce=await ev(t,n,V,O);if(Ce.kind==="cancel")return;if(Ce.kind==="back")continue;k={choice:{kind:"attach",sessionId:Ce.ctx.sessionId,...Ce.ctx.agentId?{agentId:Ce.ctx.agentId}:{}},sessions:O},C={readonly:!1,cwd:Ce.ctx.cwd},Ce.ctx.resumeHint!==void 0&&(C.resumeHint=Ce.ctx.resumeHint);break}let he=O.find(Ce=>Ce.sessionId===V.sessionId);if(!(he!==void 0&&!!he.importedFromMachine&&!he.upstreamSessionId&&V.readonly!==!0)){if(n.isLocal&&he&&!he.importedFromMachine&&V.readonly!==!0&&!(await Aa(he.cwd)).ok){let Xt=await Qr(t,he,{defaultCwd:rt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Xt.kind==="cancel")return;if(Xt.kind==="back")continue;k={choice:V,sessions:O},C={readonly:!1,cwd:Xt.path,resumeHint:{agentId:V.agentId??he.agentId??"",cwd:Xt.path,upstreamSessionId:""}};break}k={choice:V,sessions:O};break}let ge={...s,readonly:!1},ke=await Xb(t,n,he,V,ge);if(ke.kind==="cancel")return;ke.kind!=="back"&&(k={choice:V,sessions:O},C={readonly:ge.readonly===!0,cwd:ke.ctx.cwd},ke.ctx.resumeHint!==void 0&&(C.resumeHint=ke.ctx.resumeHint))}let{choice:A}=k,P=bt;if(bt=null,process.off("SIGINT",Vt),h.close().catch(()=>{}),w=!0,A.kind==="new"){let{sessionId:O,agentId:V,...he}=s,Re={...he,cwd:A.cwd??Ke,forceNew:!0,readonly:!1};A.prompt!==void 0&&(Re.initialPrompt=A.prompt),A.attachments&&A.attachments.length>0&&(Re.initialAttachments=A.attachments),P(Re);return}if(A.kind!=="attach")return;let H={...s,sessionId:A.sessionId,cwd:C?.cwd??Ke,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(H.agentId=A.agentId),C?.resumeHint!==void 0?H.resumeHint=C.resumeHint:delete H.resumeHint,P(H)}finally{!w&&bt&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},E=async(g="next")=>{if(!bt)return;let k=(await Yn(n)).filter(Re=>Re.status==="warm");if(k.length<=1)return;let C=k.findIndex(Re=>Re.sessionId===we),H=((C===-1?0:C)+(g==="prev"?-1:1)+k.length)%k.length,O=k[H],V=bt;bt=null,process.off("SIGINT",Vt),h.close().catch(()=>{});let he={...s,sessionId:O.sessionId,cwd:Ke,readonly:!1};O.agentId!==void 0&&(he.agentId=O.agentId),V(he)},B=async g=>{if(!bt)return;let w=await Yn(n,{includeNonInteractive:!0}),k=g.trim();if(!k){I.notify("usage: /session <id|next|prev>");return}let C=k.startsWith(gn)?[k]:[k,gn+k],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(V=>C.some(he=>V.sessionId.startsWith(he)));if(O.length===1)A=O[0];else if(O.length>1){I.notify(`ambiguous session id: ${k} (${O.length} matches)`);return}}if(!A){I.notify(`no session matches: ${k}`);return}if(A.sessionId===we){I.notify("already on that session");return}let P=bt;bt=null,process.off("SIGINT",Vt),h.close().catch(()=>{});let H={...s,sessionId:A.sessionId,cwd:A.cwd??Ke,readonly:A.status!=="warm"};A.agentId!==void 0&&(H.agentId=A.agentId),delete H.resumeHint,P(H)},Q=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ln(g.text,g.attachments,g.displayText):gr(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?gr(g.text,g.attachments,g.displayText):Ln(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=Os(g.index);if(!w)return;let k=[];g.text.length>0&&k.push({type:"text",text:g.text});for(let C of g.attachments)k.push({type:"image",data:C.data,mimeType:C.mimeType});m.request("hydra-acp/prompt/update",{sessionId:we,messageId:w,prompt:k}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=Os(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:we,messageId:w}).then(k=>{let C=k;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(k=>{I.notify(`queue cancel failed: ${k.message}`)});return}case"cancel":{if(I.isOverlayOpen()){_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay();return}if(g.prefill&&Ht){let w=Ue.size===0,k=_e.state().buffer.every(C=>C==="");w&&k&&(dr={text:Ht.text,attachments:Ht.attachments})}Ht?Ht.cancel():L>0&&ai(),Ms();return}case"exit":_n();return;case"plan-toggle":yr(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":R().catch(w=>{ne({src:"switch-session-failed",stack:w instanceof Error?w.stack??w.message:String(w)})});return;case"next-live-session":E().catch(()=>{});return;case"toggle-options":mr();return;case"toggle-questions":li();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w,I.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Ua();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":re(g.source);return}},oe=async g=>{if(!is){I.notify("agent does not accept image attachments");return}let w=0;for(let k of g){if(k.startsWith("data:")){let A=Mf(k);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>Xn){I.notify(`image too large (${bn(A.sizeBytes)}, max ${bn(Xn)})`);continue}_e.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=Ca(k);if(!C){I.notify(`unsupported image type: ${Gr.basename(k)}`);continue}try{let A=await op.readFile(k);if(A.length>Xn){I.notify(`image too large (${bn(A.length)}, max ${bn(Xn)})`);continue}_e.addAttachment({mimeType:C,data:A.toString("base64"),name:Gr.basename(k),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${Gr.basename(k)}: ${A.message}`)}}w>0&&(I.setAttachments(_e.state().attachments),I.refreshPrompt())},re=async(g="clipboard")=>{let w=g==="primary"?await nb():await qc();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!is){I.notify("agent does not accept image attachments");return}_e.addAttachment(w.attachment),I.setAttachments(_e.state().attachments),I.refreshPrompt();return}let k=_e.feed({type:"paste",text:w.text});for(let C of k)Q(C);I.refreshPrompt()},Ee=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Qe=(g,w)=>{let k=Array.isArray(w)?w:[],C="",A=0;for(let P of k){if(!P||typeof P!="object")continue;let H=P;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&(A+=1)}return{messageId:g,text:Te(C),attachmentCount:A}},Ue=new Map,nt=[],pt=new Map,On=new Set,at=null,dt=()=>{let g=[...Ue.values()],w=g.map(Ee);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),_e.setQueue(g.map(k=>k.text))},Os=g=>[...Ue.values()][g]?.messageId;if(En&&En.length>0){for(let g of En){if(g.position===0){ee=g.messageId;continue}Ue.set(g.messageId,Qe(g.messageId,g.prompt))}Ue.size>0&&dt()}let gr=(g,w,k)=>{I.scrollToBottom(),!Ls(g)&&(_t(g,k),$o(g,w,k))},Ln=(g,w,k)=>{if(I.scrollToBottom(),Ls(g))return;if(_t(g,k),!vn||ee===void 0){$o(g,w,k);return}let C=ee,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of w)A.push({type:"image",data:O.data,mimeType:O.mimeType});let P={text:g,displayText:k??g,attachments:w,flushed:!1};nt.push(P);let H=()=>{let O=nt.indexOf(P);O>=0&&nt.splice(O,1),P.messageId!==void 0&&pt.delete(P.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:we,targetMessageId:C,prompt:A}).then(O=>{let V=O;if(V.amended&&V.reason==="ok"){ve(1);return}if(H(),V.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),_e.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),_e.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),_e.setBuffer(g,w),I.refreshPrompt();return}}).catch(O=>{H(),I.notify(`amend failed: ${O.message}`),_e.setBuffer(g,w),I.refreshPrompt()})},yr=async g=>{if(yt.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),k=yt.findIndex(P=>P.id===w),C=k===-1?0:(k+1)%yt.length,A=yt[C]?.id;if(A){I.setBanner({currentMode:A});try{await m.request("session/set_mode",{sessionId:we,modeId:A})}catch(P){I.notify(`set_mode failed: ${P.message}`)}}},Ls=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
243
- `))return!1;let k=w.indexOf(" ");switch(k===-1?w:w.slice(0,k)){case"/quit":case"/exit":return _n(),!0;case"/clear":return vt.clear(),Bs.clear(),pn.length=0,ft=null,M=null,U=null,ls.clear(),us.clear(),fs.clear(),wr.clear(),Bn.clear(),ps.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let P of ko)A.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"});if(lr.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let P of lr)A.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=k===-1?"":w.slice(k+1).trim(),P=wt();if(!P)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let O=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let V of P.options){let he=V.value===P.currentValue?"* ":" ";O.push({prefix:" ",body:`${he}${V.value.padEnd(16)} ${V.name}`,bodyStyle:"info"})}return I.appendLines(O),!0}let H=P.options.find(O=>O.value===A)?.value;if(!H){let O=A.toLowerCase(),V=P.options.filter(he=>he.value.toLowerCase().startsWith(O));V.length===1&&(H=V[0].value)}return H?H===P.currentValue?(I.notify(`already on agent ${H}`),!0):(I.notify(`switching to ${H}\u2026`),m.request("session/set_config_option",{sessionId:we,configId:"agent",value:H}).catch(O=>{I.notify(`set_config_option failed: ${O.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return R().catch(A=>{ne({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=k===-1?"":w.slice(k+1).trim();return A?A==="next"||A==="prev"?(E(A).catch(P=>{I.notify(`session ${A} failed: ${P.message}`)}),!0):(B(A).catch(P=>{I.notify(`session switch failed: ${P.message}`)}),!0):(R().catch(P=>{ne({src:"switch-session-failed",stack:P instanceof Error?P.stack??P.message:String(P)})}),!0)}case"/rename":{let A=k===-1?"":w.slice(k+1).trim(),P=A.length>0?`/hydra title ${A}`:"/hydra title";return _t(w,w),$o(P,[],w),!0}case"/btw":{let A=k===-1?"":w.slice(k+1).trim();if(!A)return I.isOverlayOpen()?(_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(we==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;q+=1;let P=q;_&&(_.cancel(),_=null);let H=null;N!==null&&!J?H=N:N!==null&&(Vn(n,N).catch(()=>{}),N=null),J=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new Hc({getMaxWidth:()=>{let ge=I.width();return ge>0?ge:void 0}});O.on("changed",()=>{I.setBtwOverlayContent(O.getLines())});let V={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let he=ge=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ge}})},Re={};return H!==null&&(Re.reuseSessionId=H),Vw(n,we,A,Re).then(ge=>{if(P!==q){ge.cancel();return}_=ge,N=ge.sessionId,I.setBtwOverlayMeta({sessionId:ge.sessionId}),ge.on("event",ke=>{if(P===q)if(ke.kind==="update"){O.append(ke.update);let Ce=Kn(ke.update);if(Ce&&Ce.kind==="usage-update"){let Xt=!1;Ce.used!==void 0&&V.used!==Ce.used&&(V.used=Ce.used,Xt=!0),Ce.size!==void 0&&V.size!==Ce.size&&(V.size=Ce.size,Xt=!0),Ce.costAmount!==void 0&&V.costAmount!==Ce.costAmount&&(V.costAmount=Ce.costAmount,Xt=!0),Ce.costCurrency!==void 0&&V.costCurrency!==Ce.costCurrency&&(V.costCurrency=Ce.costCurrency,Xt=!0),Xt&&I.setBtwOverlayMeta({usage:{...V}})}}else ke.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),_=null):ke.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),_=null,N=null):ke.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),he(`btw errored: ${ke.error.message}`),N!==null&&Vn(n,N).catch(()=>{}),_=null,N=null)})}).catch(ge=>{if(P!==q)return;let ke=ge instanceof Error?ge.message:String(ge);I.setBtwOverlayStatus({label:"errored",style:"errored"}),he(`btw startup failed: ${ke}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ke}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(we==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=k===-1?"":w.slice(k+1).trim(),P=we;return(async()=>{try{let H=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(P)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!H.ok){let ke=await H.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${ke}`.trim(),bodyStyle:"info"}]);return}let O=await H.text(),V=new Date().toISOString().replace(/[:.]/g,"-"),he=`hydra-${lt(P)}-${V}.md`,Re=A.length>0?rt(A):he,ge=Gr.resolve(Re);await op.mkdir(Gr.dirname(ge),{recursive:!0}),await op.writeFile(ge,O,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ge}`,bodyStyle:"system"}])}catch(H){I.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},$o=async(g,w,k)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Re of w)C.push({type:"image",data:Re.data,mimeType:Re.mimeType});ve(1);let A={text:g,displayText:k??g,attachments:w,flushed:!1};nt.push(A),ss=!1;let P=!1,H=null,O=Re=>{typeof Y<"u"&&Y!==null&&Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Re,bodyStyle:"tool-status-fail"}])},V=!1;Ht={text:g,attachments:w,cancel:()=>{if(ss){ss=!1,V=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:we}).catch(ge=>{O(`force-stop failed: ${ge.message}`)});return}if(P)return;P=!0,m.notify("session/cancel",{sessionId:we}).catch(()=>{});let Re=Date.now();H=setTimeout(()=>{Ht!==null&&(Rs>=Re||(ss=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Xr)}};let he;try{let Re=await m.request("session/prompt",{sessionId:we,prompt:C});Re&&typeof Re.stopReason=="string"&&(he=Re.stopReason)}catch(Re){let ge=nt.indexOf(A);ge>=0&&nt.splice(ge,1),A.messageId!==void 0&&pt.delete(A.messageId),V?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Re.message,bodyStyle:"tool-status-fail"}])}finally{if(Ht=null,H!==null&&(clearTimeout(H),H=null),ve(-1),A.flushed&&at===A){let Re=A.messageId!==void 0&&On.has(A.messageId);Re&&A.messageId!==void 0&&On.delete(A.messageId);let ge={kind:"turn-complete"};he!==void 0&&(ge.stopReason=he),Re&&(ge.amended=!0),x(ge),at=null}if(dr!==null){let{text:Re,attachments:ge}=dr;dr=null,_e.state().buffer.every(Ce=>Ce==="")&&(_e.setBuffer(Re,ge),I.refreshPrompt())}}},vt=new Map,ls=new Map,us=new Map,Bs=new Map,pn=[],Ct=0,Sn=`tools:${Ct}`,fs=new Map,wr=new Map,fi=new Set,br=new Map,Bn=new Map,ps=new Map,ft=null,M=null,U=null,ie=null,z=null,ue=e.tui.maxToolItems,le=e.tui.maxPlanItems,je=()=>({maxPlanItems:z??i.planExpanded?1/0:le}),Ne=()=>{if(ie===null)return;let g=Xs(ie,je());g.length>0&&I.upsertLines("plan",[{body:""},...g])},$e="",qe=null,Gt=0,Nn=()=>{if(qe===null)return;let g=I.width(),w=Zs($e,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(qe,w)},St=g=>{g.length!==0&&(qe===null&&(I.ensureSeparator(),qe=`agent:${Gt}`,Gt+=1,$e=""),$e+=g,Nn())},xe=()=>{qe=null,$e=""},ct="",$t=null,zt=0,Ns=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),vr=()=>{if($t===null||ct.length===0)return;let g=so(ct);g.length!==0&&I.upsertLines($t,g)},al=g=>{let w=Bn.get(g);if(w===void 0)return[];let k=so(w.text);return w.workerTaskId&&k.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),k},dl=(g,w)=>{g.length!==0&&($t===null&&(I.ensureSeparator("thought"),$t=`thought:${zt}`,zt+=1,ct=""),ct+=g,Bn.set($t,{text:ct,workerTaskId:w}),vr())},kn=()=>{$t=null,ct=""},Ye=g=>TT({...g,collapsedLimit:ue}),hs=g=>wr.get(g)??i.toolsExpanded,Rt=()=>{if(ft===null)return;let{lines:g,rowOwners:w}=Ye({order:pn,states:vt,startedAt:ft,endedAt:M,stopReason:U,expanded:hs(Sn),perToolExpanded:fi});I.upsertLines(Sn,g),br.set(Sn,w)},Sr=g=>{let w=fs.get(g);if(!w)return;let{lines:k,rowOwners:C}=Ye({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:hs(g),perToolExpanded:fi});I.upsertLines(g,k),br.set(g,C)},lv=()=>{ft!==null&&!fs.has(Sn)&&Rt();for(let g of fs.keys())Sr(g)},cl=()=>{ft!==null&&fs.set(Sn,{order:[...pn],states:new Map(vt),startedAt:ft,endedAt:M??Date.now(),stopReason:U,rowOwners:br.get(Sn)??[]})},hp=()=>{Ct+=1,Sn=`tools:${Ct}`,ft=Date.now(),M=null,U=null,Rt()};function uv(g){if(!g||typeof g!="object")return null;let w=g,k=Array.isArray(w.content)?w.content:void 0;if(!k)return null;let C=[],A=P=>{if(typeof P=="string"){C.push({text:ht(P)});return}if(P&&typeof P=="object"){let H=P;typeof H.__hydraBlob=="string"&&C.push({hash:H.__hydraBlob})}};for(let P of k){if(!P||typeof P!="object")continue;let H=P;if(H.type==="content"&&H.content&&typeof H.content=="object"){let O=H.content;if(O.text!==void 0){A(O.text);continue}}if(H.type==="text"&&H.text!==void 0){A(H.text);continue}H.text!==void 0&&A(H.text)}return C.length>0?C:null}let mp=(g,w)=>{let k=w.map(P=>"text"in P?P.text:"").join(`
244
- `);if(k.length===0)return;let{text:C,truncated:A}=ky(k);g.resultText=C,g.resultTruncated=A},Wa=new Set,fv=(g,w)=>{!w.some(C=>"hash"in C)||Wa.has(g)||(Wa.add(g),(async()=>{let C=await Promise.all(w.map(async P=>"text"in P?P:{text:await ll(P.hash)??""}));Wa.delete(g);let A=vt.get(g);if(!A)for(let P of fs.values()){let H=P.states.get(g);if(H){A=H;break}}if(A){mp(A,C),vt.has(g)&&Rt();for(let[P,H]of fs)H.states.has(g)&&Sr(P);I.repaintNow()}})().catch(()=>{Wa.delete(g)}))},gp=(g,w,k,C,A,P,H,O,V,he)=>{let Re=!vt.has(g),ge=vt.get(g),ke=ge??{initialTitle:w??"tool",latestTitle:w??"tool",status:k??"pending",startedAt:Date.now()};if(!ge&&V!==void 0&&(ke.workerTaskId=V),ge&&w!==void 0&&(ke.latestTitle=w),P!==void 0&&ke.detail===void 0&&(ke.detail=P),H!==void 0&&ke.detailFull===void 0&&(ke.detailFull=H),O!==void 0&&O.length>0&&(ke.locations=O),ge&&k!==void 0&&(ke.status=k),ge||(ke.status=k??"pending"),ke.endedAt===void 0&&ef(ke.status)&&(ke.endedAt=Date.now()),C!==void 0&&(ke.errorText=C),A!==void 0&&(ke.editDiff=A),he!==void 0){let Ce=uv(he);Ce!==null&&(mp(ke,Ce),Ce.some(Xt=>"hash"in Xt)&&fv(g,Ce))}vt.set(g,ke),Re&&(ft===null&&(Ct+=1,Sn=`tools:${Ct}`,ft=Date.now(),M=null,U=null),pn.push(g))},ll=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:we,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},za=new Set,pv=(g,w)=>{za.has(g)||w.oldRef===void 0&&w.newRef===void 0||(za.add(g),(async()=>{let[k,C]=await Promise.all([w.oldRef?ll(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?ll(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&k===null||w.newRef!==void 0&&C===null){za.delete(g);let he=Xu(w,"diff",{deferredStatus:"error"});he.length>0&&(I.upsertLines(`editdiff:${g}`,he),I.repaintNow());return}let P={...w.path!==void 0?{path:w.path}:{},oldText:k??"",newText:C??""};ls.set(g,P);let H=vt.get(g);H?.editDiff&&(H.editDiff=P),za.delete(g);let O=us.get(g),V=O===void 0?i.showFileUpdates:O?"diff":"edit";V!=="none"&&(Ka(g,P,V==="diff"?"diff":"edit"),I.repaintNow())})())},Ka=(g,w,k)=>{let C=`editdiff:${g}`,A=Xu(w,k);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),k==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&I.notifyWhenVisible(C)},hv=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),k=ls.get(w);k&&(k.oldRef!==void 0||k.newRef!==void 0)&&pv(w,k)},yp=g=>{let w=`editdiff:${g}`,k=i.showFileUpdates,C=vt.get(g),A;if(k==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let H=us.get(g);A=H!==void 0?H?"diff":"edit":k==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let P=C.editDiff;ls.set(g,P),Ka(g,P,A)},mv=()=>{let g=i.showFileUpdates;for(let[w,k]of ls){let C=`editdiff:${w}`,A=us.get(w),P=A===void 0?g:A?"diff":"edit";if(P==="none"){I.removeKey(C);continue}Ka(w,k,P==="diff"?"diff":"edit")}},gv=g=>{if(!g.path)return null;let w=ht(g.oldText).split(`
241
+ `)}}function ET(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 J=Math.max(0,c-a),q=e.slice(J),L=[];for(let D=0;D<J;D++){let X=e[D];if(X===void 0)continue;let ee=n.get(X);ee&&!ef(ee.status)&&L.push(X)}l=[...L,...q]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",b=y?`amended \xB7 ${Qn(h)}`:`stopped (${m}) \xB7 ${Qn(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${Qn(h)}`:`thought \xB7 ${Qn(h)}`;else{let J=c===1?"tool":"tools",q=m!==null?b:f?Qn(h):`took ${Qn(h)}`,L=[`${c} ${J}`,q];f&&d&&u>0&&L.push(`${u} hidden`),v=L.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",_=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?x:"dim"}],N=[null];for(let J of l){let q=n.get(J);if(q){let L=ga(q,p);for(let D of L)D.hoverSubKey=J;if(_.push(...L),N.push(...L.map(()=>J)),o?.has(J)){let D=Iy(q);for(let X of D)X.hoverSubKey=J;_.push(...D),N.push(...D.map(()=>J))}}}return{lines:_,rowOwners:N}}async function PT(t,e,n,s,r,i,o){let a=await MT(t,e,n,s,o,i);if(!a)return t.grabInput(!1),ne({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=$T(t,c);d.write(c);let l=n.isLocal?async()=>(await Ut(await Ie())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new fo({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>ne({src:"resilient-ws",line:g})}),m=new Jt(h);await h.start(),m.onNotification(ld,g=>{let w=_h.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,x=(g,w)=>{g&&(b?b(g,w):y.push({event:g,rawUpdate:w}))},T,F=g=>{g!==T&&(T=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},_=null,N=null,J=!1,q=0,L=0,D=!1,X=!1,ee,ae=null,G=null,fe=null,Ve=null,Be=()=>setInterval(()=>{if(ae===null||Y===null)return;let g=Ve===null?0:Date.now()-Ve;Y.setBanner({elapsedMs:Date.now()-ae,stalled:g>=AT}),Rt()},1e3),ns=!1,ve=g=>{let w=L;L=Math.max(0,L+g);let k=typeof Y<"u"&&Y!==null;w===0&&L>0?(X=!1,ae=Date.now(),Ve=Date.now(),Se?.setTurnRunning(!0),k&&Y.setBanner({status:"busy",elapsedMs:0,stalled:!1}),G===null&&k&&(G=Be())):w>0&&L===0?(X=!1,ae=null,Ve=null,Se?.setTurnRunning(!1),G!==null&&(clearInterval(G),G=null),k&&Y.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&X&&(X=!1,k&&Y.setBanner({status:"busy",stalled:!1}))},Y=null,Se=null,De,Vt=null,As=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"]),cn=g=>{let{update:w}=g??{},k=Kn(w,{cwd:Ke});_T(w,k),Ve=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!As.has(C)){let A=w??{};typeof A.messageId=="string"&&(De=A.messageId)}if(C==="prompt_received"?ve(1):k?.kind==="turn-complete"&&(ve(-1),J=!0),C==="permission_resolved"){So(w);return}if(C==="hydra_compaction"){vo(w);return}if(C==="clarifier_question_asked"){let A=w,P=typeof A.question?.question=="string"?A.question.question:"",H=P.length>50?P.slice(0,49)+"\u2026":P;I.notify(H?`new question: ${H} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(x(k,w),La(w))};m.onNotification("session/update",g=>{if(!v){if(Vt!==null){Vt.push(g);return}cn(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&ve(-L),typeof Y<"u"&&Y!==null&&Y.setBanner({status:"cold",elapsedMs:void 0})});let mt=new Map,Cs=200,Rs=0,ss=!1,Xr=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,P=setTimeout(()=>{v||(mt.delete(C),Ue.set(C,Qe(C,A)),Y&&Se&&dt())},Cs);mt.set(C,P)}else Ue.set(w.messageId,Qe(w.messageId,w.prompt)),Y&&Se&&dt();if(Es!==void 0&&w.originator?.clientId===Es){let C=nt.shift();C&&(C.messageId=w.messageId,pt.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!Ue.has(w.messageId))return;Ue.set(w.messageId,Qe(w.messageId,w.prompt));let k=pt.get(w.messageId);if(k){let C=Array.isArray(w.prompt)?w.prompt:[],A="",P=[];for(let H of C){if(!H||typeof H!="object")continue;let O=H;O.type==="text"&&typeof O.text=="string"?A+=O.text:O.type==="image"&&typeof O.data=="string"&&typeof O.mimeType=="string"&&P.push({data:O.data,mimeType:O.mimeType,sizeBytes:Math.floor(O.data.length*3/4)})}k.text=A,k.attachments=P}Y&&Se&&dt()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(ee=w.messageId);let k=mt.get(w.messageId);k!==void 0&&(clearTimeout(k),mt.delete(w.messageId)),Ue.delete(w.messageId)&&Y&&Se&&dt();let A=pt.get(w.messageId);A&&(pt.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),at=A))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let w=g??{};if(!(typeof Y<"u"&&Y!==null))return;Rs=Date.now(),ss=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),m.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let k=w.cancelledMessageId;On.add(k),at!==null&&at.messageId!==void 0&&at.messageId===k&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),at=null,On.delete(k))});let vo=g=>{let w=g??{},k=typeof w.phase=="string"?w.phase:void 0;if(k==="started")I.setCompactionIndicator("compacting...");else if(k==="iteration")I.setCompactionIndicator("compacting...");else if(k==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(k==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(k==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(k==="failed"){I.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},rs=()=>{fe===null&&(fe=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(we)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),fe!==null&&(clearInterval(fe),fe=null)):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),fe!==null&&(clearInterval(fe),fe=null))}catch{}},5e3))},Oa=()=>{fe!==null&&(clearInterval(fe),fe=null)},So=g=>{let w=g??{},k=typeof w.toolCallId=="string"?w.toolCallId:void 0,C;w.outcome&&typeof w.outcome=="object"?C=w.outcome:typeof w.chosenOptionId=="string"&&(C={kind:"selected",optionId:w.chosenOptionId}),Ts(k,C?{outcome:C}:void 0)},pe=null,Ts=(g,w)=>{if(!pe||pe.toolCallId&&g&&pe.toolCallId!==g)return;let k=pe.resolve;pe=null,I.setPermissionPrompt(null),k(w??{outcome:{outcome:"cancelled"}})},La=g=>{if(!pe?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===pe.toolCallId&&(!w.status||w.status==="pending"||Ts(w.toolCallId,void 0))},Zr=()=>{if(!pe){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:pe.title,detail:pe.detail,options:pe.options.map(g=>({label:g.name})),selectedIndex:pe.selectedIndex})},ei=g=>{if(!pe)return;let{options:w,resolve:k}=pe;if(pe=null,I.setPermissionPrompt(null),g===null){k({outcome:{outcome:"cancelled"}});return}k({outcome:{outcome:"selected",optionId:g}})};m.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Kr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(V=>({optionId:V.optionId,name:Te(V.name??""),...V.kind!==void 0?{kind:V.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",P=Te(A),H=Te(kw(Sw(g))),O=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${P} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(V=>{pe={title:P,detail:H,options:C,selectedIndex:0,resolve:V,toolCallId:O},Zr()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let ti,Dt,is=!0,vn=!1;try{let g=await m.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:me}});Dt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(is=!1),vn=nn(g?._meta??void 0).prompt?.amending===!0}catch{}let we=a.sessionId,et=a.agentId,Ke=a.cwd,gt,Es,ni,rr,si,ri,ir,En,ii,Pn,or=!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 w={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Lt]:g}}:{}},k;try{k=await fw({request:()=>m.request("session/new",w),showBanner:(P,H,O)=>pw(t,P,H,O,{authenticate:V=>m.request("authenticate",{methodId:V})}),resolveOnboarding:async P=>{if(P)try{return(await uc(n)).find(V=>V.id===P)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(P){t.grabInput(!1),ne({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let H=P instanceof Error?P.message:String(P);ne({src:"session-new-failed",agentId:s.agentId??null,message:H});let O=await Ub(t,s.agentId,H,{canGoBack:!s.forceNew});if(O==="cancel")return null;let V={...s};return delete V.sessionId,delete V.resume,O==="retry"?V.forceNew=!0:(delete V.forceNew,delete V.agentId),V}if(k.kind==="cancel")return t.grabInput(!1),ne({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(k.kind==="back"){t.grabInput(!1),ne({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let P={...s};return delete P.sessionId,delete P.forceNew,delete P.resume,delete P.agentId,P}let C=k.result;d.write(c),we=C.sessionId,r.sessionId=we,r.readonly=!1;let A=nn(C._meta??void 0);A.clientId&&(Es=A.clientId),ti=A.upstreamSessionId,A.agentId&&(et=A.agentId),A.cwd&&(Ke=A.cwd),A.title&&(gt=A.title),ni=A.currentModel,rr=A.currentMode,ii=A.currentUsage,Pn=A.turnStartedAt,A.availableCommands&&(si=qd(A.availableCommands)),A.availableModes&&(ri=A.availableModes),ir=Yb(C.configOptions),En=A.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 w=await m.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:me},...Object.keys(g).length>0?{_meta:{[Lt]:g}}:{}});we=w.sessionId,w.clientId&&(Es=w.clientId),r.sessionId=we,r.readonly=s.readonly===!0;let k=nn(w._meta??void 0);or=k.resurrected===!0,ti=k.upstreamSessionId,k.agentId&&(et=k.agentId),k.cwd&&(Ke=k.cwd),k.title&&(gt=k.title),ni=k.currentModel,rr=k.currentMode,ii=k.currentUsage,Pn=k.turnStartedAt,k.availableCommands&&(si=qd(k.availableCommands)),k.availableModes&&(ri=k.availableModes),ir=Yb(w.configOptions),En=k.queue}let ar=$.tuiHistoryFile(we),He=$.globalTuiHistoryFile(),Et=await Qo(ar).catch(()=>[]),Pt=await Qo(He).catch(()=>[]);Pt.length>e.tui.promptHistoryMaxEntries&&(Pt=Pt.slice(Pt.length-e.tui.promptHistoryMaxEntries));let Mt=[...Et],_e=new Is({history:xd(Pt,Mt)});Se=_e;let Mn=!1,_t=(g,w)=>{let k=g.replace(/\n+$/,"");if(k.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Go(Et,k),P=A!==Et;Et=A,Mt=Go(Mt,C);let H=Go(Pt,k,e.tui.promptHistoryMaxEntries),O=H!==Pt;Pt=H,_e.setHistory(xd(Pt,Mt)),P&&_r(ar,Et).catch(()=>{}),O&&Pm(He,k).catch(()=>{})};L>0&&_e.setTurnRunning(!0);let Ht=null,dr=null;Ab(Cb(e.tui.ambiguousWidth,process.env)),Ay(e.tui.diffContextLines);let cr=!1,I,oi=()=>{cr&&(cr=!1,I.start())},Ba=()=>{cr||(cr=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",oi);let os=null,Je=null;I=new Qc({term:t,dispatcher:_e,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"?Ba:void 0,onBlockClick:(g,w)=>{bv(g,w)},onBlockDoubleClick:(g,w)=>wv(g,w),onHydraLinkClick:g=>(B(g),!0),onBlockVisible:g=>{mv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=ps.get(g);if(w!==void 0&&w.length>0)return new Set(w);let k=I.contiguousRun(g,new Set(Bn.keys()));return k.length>0?new Set(k):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){os=I.bannerHitAt(g.x,g.y),Je=os?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let k=Je,C=os;if(Je=null,os=null,C!==null&&k!==null&&k.x===g.x&&k.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){yr(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&ap(A))return;Q(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&ap(w)||Q(w)},onKey:g=>{for(let w of g){if(D&&Eo(w)){w.type==="key"&&ne({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(pe&&Ao(w)){w.type==="key"&&ne({src:"key-swallowed",site:"permission",name:w.name});continue}if(ci(w)){w.type==="key"&&ne({src:"key-swallowed",site:"help",name:w.name});continue}if(_o(w)){w.type==="key"&&ne({src:"key-swallowed",site:"questions",name:w.name});continue}if(Gt(w)){w.type==="key"&&ne({src:"key-swallowed",site:"options",name:w.name});continue}if(fr(w)){w.type==="key"&&ne({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(xo(w)){w.type==="key"&&ne({src:"key-swallowed",site:"completion",name:w.name});continue}if(ur(w)){w.type==="key"&&ne({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){oe(w.paths);continue}let k=_e.feed(w);for(let C of k)s.readonly===!0&&ap(C)||Q(C)}Ps(),I.setBannerSearchIndicator(_e.state().historySearchQuery),I.setAttachments(_e.state().attachments),I.refreshPrompt()}}),Y=I,I.setStickyBottomKey("plan");let ko=[{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]"}],lr=si??[],yt=ri??[],Na=ir??[],wt=()=>Na.find(g=>g.id==="agent"),as=()=>{let g=new Set,w=[];for(let k of[...ko,...lr])g.has(k.name)||(g.add(k.name),w.push(k));return w},Io=()=>{let g=_e.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let k=w.indexOf(" "),C=k===-1?w:w.slice(0,k);if(C.lastIndexOf("/")>0)return[];let A=as().filter(P=>P.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},ds=[],Ps=()=>{let g=Io();if(g.length>0){ds=[],I.setCompletions(g);return}I.setCompletions(ds)},xo=g=>{if(g.type!=="key"||g.name!=="tab")return ds.length>0&&(ds=[]),!1;let w=Io();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){ds=[];let k=_e.state().buffer[0]??"",C=_b({matches:w.map(A=>A.name),firstLine:k});return C===null||_e.replaceFirstLine(C),!0}return Da()},Da=()=>{let g=_e.state(),w=g.buffer[g.row]??"",k=tl(w,g.col);if(k===null)return!1;let C=nl(k.token,Ke);return C===null?!1:(C.replacement!==k.token&&_e.replaceRangeOnCurrentLine(k.start,g.col,C.replacement),ds=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},ur=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay(),!0),fr=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let w=I.scrollbackSearchTerm();return w.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Ao=g=>{if(!pe)return!1;let w=pe.options;if(g.type==="key")switch(g.name){case"up":return pe.selectedIndex=Math.max(0,pe.selectedIndex-1),Zr(),!0;case"down":return pe.selectedIndex=Math.min(w.length-1,pe.selectedIndex+1),Zr(),!0;case"enter":{let k=w[pe.selectedIndex];return k&&ei(k.optionId),!0}case"escape":case"ctrl-c":return ei(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let k=parseInt(g.ch,10)-1,C=w[k];return C&&ei(C.optionId),!0}return!0},Ha=et||Dt||"?",ln={...ii??{}};d.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:Ha,cwd:Ke,sessionId:we,title:gt,model:ni,usage:{...ln}}),rr&&I.setBanner({currentMode:rr}),ka().then(g=>{g&&I.notify(`\u2728 ${Ia(g)}`,3e4)}).catch(()=>{});let bt=null,Co=new Promise(g=>{bt=g}),ai=()=>{m.notify("session/cancel",{sessionId:we}).catch(()=>{})},Ms=()=>{Y!==null&&L===1&&(X=!0,Y.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Qt=()=>{if(Ht){Ht.cancel(),Ms();return}if(L>0){ai(),Ms();return}_n()},_n=()=>{Fs(0)},di=()=>{let g="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",w]],...CT]},Ua=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:di(),hint:"any key dismisses \xB7 /help lists commands"})},Ro=()=>{D=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=we;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},To=()=>{D=!1,I.setCompactionPrompt(null)},ja=g=>{let w=I.compactionPromptSpec();if(!w)return;let k=w.options.length;if(k===0)return;let C=((w.selectedIndex+g)%k+k)%k;C!==w.selectedIndex&&I.setCompactionPrompt({...w,selectedIndex:C})},Eo=g=>{if(!D)return!1;if(g.type==="key"){if(g.name==="escape")return To(),!0;if(g.name==="up")return ja(-1),!0;if(g.name==="down")return ja(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?Ro():To(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return Ro(),!0;if(w==="n"||w==="2")return To(),!0}return!0},ci=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,_s=["tools","plan","thoughts","diffs","mouse","enter"],un=0,zt=null,$s=[],pr=[],At=[],hr=0,$n=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}},Fn=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"}},Po=()=>({title:"Session options",options:_s.map(g=>({label:Fn(g),value:$n(g)})),selectedIndex:un}),Mo=()=>{I.isOptionsPromptActive()&&zt===null&&I.setOptionsPrompt(Po())},mr=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}un=0,I.setOptionsPrompt(Po())},cs=()=>{if(zt===null)return;let g=ST(zt,$s,At,hr);I.setOptionsPrompt(g)},fn=()=>{zt=null,$s=[],pr=[],At=[],hr=0,I.setOptionsPrompt(null)},li=async()=>{if(zt!==null){fn();return}try{let w=await m.request(zw,{sessionId:we}),k=yT(w.questions??[]);if(k.length===0){I.notify("no open questions");return}let C=bT(k);zt=C,hr=0,$s=C.map(A=>wT(A.representative)),pr=C.map(()=>!1),At=C.map(()=>!1),cs()}catch(g){I.notify("clarifier unavailable"),ne({src:"questions",step:"list_failed",error:g.message})}},pn=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,wr.clear(),fi.clear(),uv();break;case"plan":i.planExpanded=!i.planExpanded,z=null,Ne();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",us.clear(),gv();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Mo()},ui=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${Fn(g)} is session-only \u2014 not saved`);return;case"thoughts":await Oo("showThoughts",i.showThoughts);break;case"diffs":await Oo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Oo("mouse",i.mouseEnabled);break;case"enter":await Oo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${Fn(g)} ${$n(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Gt=g=>{if(zt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return un=Math.max(0,un-1),Mo(),!0;case"down":return un=Math.min(_s.length-1,un+1),Mo(),!0;case"enter":{let w=_s[un];return w&&pn(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,k=_s[w];return k&&(un=w,pn(k)),!0}if(g.ch==="s"||g.ch==="S"){let w=_s[un];return w&&ui(w),!0}}return!0},_o=g=>{if(zt===null)return!1;let w=xT(g,!0,zt,$s,pr,At,hr,we);switch(w.type){case"noop":return!0;case"row":return hr=w.selectedRow,cs(),!0;case"cycle":return $s[w.selectedRow]=w.newValueIndex,pr[w.selectedRow]=!0,At[w.selectedRow]=!1,cs(),!0;case"dismiss-toggle":{let k=w.selectedRow;return At[k]?(At[k]=!1,pr[k]=!1):(At[k]=!0,pr[k]=!0),cs(),!0}case"discard":return fn(),!0;case"save":{let k=w.dispatches;return fn(),k.length===0||(async()=>{let C=0,A=0,P=0;for(let O of k)try{await m.request(O.method,O.params),O.type==="dismiss"?A++:C++}catch(V){P++,ne({src:"questions",step:"dispatch_failed",method:O.method,error:V.message})}let H=[];C>0&&H.push(`${C} answered`),A>0&&H.push(`${A} dismissed`),P>0&&H.push(`${P} failed`),H.length>0&&I.notify(`clarifier: ${H.join(", ")}`)})(),!0}}return!1},qa=()=>{v=!0,_?(_.cancel(),_=null,N=null):N!==null&&(Vn(n,N).catch(()=>{}),N=null),process.off("SIGINT",Qt),process.platform!=="win32"&&process.off("SIGCONT",oi),G!==null&&(clearInterval(G),G=null),fe!==null&&(clearInterval(fe),fe=null);for(let g of mt.values())clearTimeout(g);mt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),_r(ar,Et).catch(()=>{}),h.close().catch(()=>{})},Fs=(g=0)=>{qa(),bt&&(bt(null),bt=null),g!==0&&process.exit(g)},R=async()=>{if(ne({src:"switch-session",step:"entered",finishSessionNull:bt===null}),!bt)return;_?(_.cancel(),_=null,N=null):N!==null&&(Vn(n,N).catch(()=>{}),N=null),Oa(),I.setSynthesisIndicator(null);let g=_e.state().buffer.join(`
242
+ `);g.replace(/\s+$/,"").length>0&&_t(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),_r(ar,Et).catch(()=>{});let w=!1;try{let k=null,C=null;for(;k===null;){let O=await Yn(n,{includeNonInteractive:!0}),V=await rp(t,{cwd:Ke,sessions:O,config:e,target:n,currentSessionId:we,prefs:o});if(V.kind==="abort")return;if(V.kind==="exit"){w=!0,Fs(0);return}if(V.kind==="new"){k={choice:V,sessions:O};break}if(V.kind==="fork"){let Ce=await tv(t,n,V,O);if(Ce.kind==="cancel")return;if(Ce.kind==="back")continue;k={choice:{kind:"attach",sessionId:Ce.ctx.sessionId,...Ce.ctx.agentId?{agentId:Ce.ctx.agentId}:{}},sessions:O},C={readonly:!1,cwd:Ce.ctx.cwd},Ce.ctx.resumeHint!==void 0&&(C.resumeHint=Ce.ctx.resumeHint);break}let he=O.find(Ce=>Ce.sessionId===V.sessionId);if(!(he!==void 0&&!!he.importedFromMachine&&!he.upstreamSessionId&&V.readonly!==!0)){if(n.isLocal&&he&&!he.importedFromMachine&&V.readonly!==!0&&!(await Aa(he.cwd)).ok){let Zt=await Qr(t,he,{defaultCwd:rt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Zt.kind==="cancel")return;if(Zt.kind==="back")continue;k={choice:V,sessions:O},C={readonly:!1,cwd:Zt.path,resumeHint:{agentId:V.agentId??he.agentId??"",cwd:Zt.path,upstreamSessionId:""}};break}k={choice:V,sessions:O};break}let ge={...s,readonly:!1},ke=await Zb(t,n,he,V,ge);if(ke.kind==="cancel")return;ke.kind!=="back"&&(k={choice:V,sessions:O},C={readonly:ge.readonly===!0,cwd:ke.ctx.cwd},ke.ctx.resumeHint!==void 0&&(C.resumeHint=ke.ctx.resumeHint))}let{choice:A}=k,P=bt;if(bt=null,process.off("SIGINT",Qt),h.close().catch(()=>{}),w=!0,A.kind==="new"){let{sessionId:O,agentId:V,...he}=s,Re={...he,cwd:A.cwd??Ke,forceNew:!0,readonly:!1};A.prompt!==void 0&&(Re.initialPrompt=A.prompt),A.attachments&&A.attachments.length>0&&(Re.initialAttachments=A.attachments),P(Re);return}if(A.kind!=="attach")return;let H={...s,sessionId:A.sessionId,cwd:C?.cwd??Ke,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(H.agentId=A.agentId),C?.resumeHint!==void 0?H.resumeHint=C.resumeHint:delete H.resumeHint,P(H)}finally{!w&&bt&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},E=async(g="next")=>{if(!bt)return;let k=(await Yn(n)).filter(Re=>Re.status==="warm");if(k.length<=1)return;let C=k.findIndex(Re=>Re.sessionId===we),H=((C===-1?0:C)+(g==="prev"?-1:1)+k.length)%k.length,O=k[H],V=bt;bt=null,process.off("SIGINT",Qt),h.close().catch(()=>{});let he={...s,sessionId:O.sessionId,cwd:Ke,readonly:!1};O.agentId!==void 0&&(he.agentId=O.agentId),V(he)},B=async g=>{if(!bt)return;let w=await Yn(n,{includeNonInteractive:!0}),k=g.trim();if(!k){I.notify("usage: /session <id|next|prev>");return}let C=k.startsWith(qt)?[k]:[k,qt+k],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(V=>C.some(he=>V.sessionId.startsWith(he)));if(O.length===1)A=O[0];else if(O.length>1){I.notify(`ambiguous session id: ${k} (${O.length} matches)`);return}}if(!A){I.notify(`no session matches: ${k}`);return}if(A.sessionId===we){I.notify("already on that session");return}let P=bt;bt=null,process.off("SIGINT",Qt),h.close().catch(()=>{});let H={...s,sessionId:A.sessionId,cwd:A.cwd??Ke,readonly:A.status!=="warm"};A.agentId!==void 0&&(H.agentId=A.agentId),delete H.resumeHint,P(H)},Q=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ln(g.text,g.attachments,g.displayText):gr(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?gr(g.text,g.attachments,g.displayText):Ln(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=Os(g.index);if(!w)return;let k=[];g.text.length>0&&k.push({type:"text",text:g.text});for(let C of g.attachments)k.push({type:"image",data:C.data,mimeType:C.mimeType});m.request("hydra-acp/prompt/update",{sessionId:we,messageId:w,prompt:k}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=Os(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:we,messageId:w}).then(k=>{let C=k;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(k=>{I.notify(`queue cancel failed: ${k.message}`)});return}case"cancel":{if(I.isOverlayOpen()){_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay();return}if(g.prefill&&Ht){let w=Ue.size===0,k=_e.state().buffer.every(C=>C==="");w&&k&&(dr={text:Ht.text,attachments:Ht.attachments})}Ht?Ht.cancel():L>0&&ai(),Ms();return}case"exit":_n();return;case"plan-toggle":yr(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":R().catch(w=>{ne({src:"switch-session-failed",stack:w instanceof Error?w.stack??w.message:String(w)})});return;case"next-live-session":E().catch(()=>{});return;case"toggle-options":mr();return;case"toggle-questions":li();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w,I.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Ua();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":re(g.source);return}},oe=async g=>{if(!is){I.notify("agent does not accept image attachments");return}let w=0;for(let k of g){if(k.startsWith("data:")){let A=Mf(k);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>Xn){I.notify(`image too large (${bn(A.sizeBytes)}, max ${bn(Xn)})`);continue}_e.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=Ca(k);if(!C){I.notify(`unsupported image type: ${Gr.basename(k)}`);continue}try{let A=await op.readFile(k);if(A.length>Xn){I.notify(`image too large (${bn(A.length)}, max ${bn(Xn)})`);continue}_e.addAttachment({mimeType:C,data:A.toString("base64"),name:Gr.basename(k),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${Gr.basename(k)}: ${A.message}`)}}w>0&&(I.setAttachments(_e.state().attachments),I.refreshPrompt())},re=async(g="clipboard")=>{let w=g==="primary"?await nb():await qc();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!is){I.notify("agent does not accept image attachments");return}_e.addAttachment(w.attachment),I.setAttachments(_e.state().attachments),I.refreshPrompt();return}let k=_e.feed({type:"paste",text:w.text});for(let C of k)Q(C);I.refreshPrompt()},Ee=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Qe=(g,w)=>{let k=Array.isArray(w)?w:[],C="",A=0;for(let P of k){if(!P||typeof P!="object")continue;let H=P;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&(A+=1)}return{messageId:g,text:Te(C),attachmentCount:A}},Ue=new Map,nt=[],pt=new Map,On=new Set,at=null,dt=()=>{let g=[...Ue.values()],w=g.map(Ee);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),_e.setQueue(g.map(k=>k.text))},Os=g=>[...Ue.values()][g]?.messageId;if(En&&En.length>0){for(let g of En){if(g.position===0){ee=g.messageId;continue}Ue.set(g.messageId,Qe(g.messageId,g.prompt))}Ue.size>0&&dt()}let gr=(g,w,k)=>{I.scrollToBottom(),!Ls(g)&&(_t(g,k),$o(g,w,k))},Ln=(g,w,k)=>{if(I.scrollToBottom(),Ls(g))return;if(_t(g,k),!vn||ee===void 0){$o(g,w,k);return}let C=ee,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of w)A.push({type:"image",data:O.data,mimeType:O.mimeType});let P={text:g,displayText:k??g,attachments:w,flushed:!1};nt.push(P);let H=()=>{let O=nt.indexOf(P);O>=0&&nt.splice(O,1),P.messageId!==void 0&&pt.delete(P.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:we,targetMessageId:C,prompt:A}).then(O=>{let V=O;if(V.amended&&V.reason==="ok"){ve(1);return}if(H(),V.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),_e.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),_e.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),_e.setBuffer(g,w),I.refreshPrompt();return}}).catch(O=>{H(),I.notify(`amend failed: ${O.message}`),_e.setBuffer(g,w),I.refreshPrompt()})},yr=async g=>{if(yt.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),k=yt.findIndex(P=>P.id===w),C=k===-1?0:(k+1)%yt.length,A=yt[C]?.id;if(A){I.setBanner({currentMode:A});try{await m.request("session/set_mode",{sessionId:we,modeId:A})}catch(P){I.notify(`set_mode failed: ${P.message}`)}}},Ls=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
243
+ `))return!1;let k=w.indexOf(" ");switch(k===-1?w:w.slice(0,k)){case"/quit":case"/exit":return _n(),!0;case"/clear":return vt.clear(),Bs.clear(),hn.length=0,ft=null,M=null,U=null,ls.clear(),us.clear(),fs.clear(),wr.clear(),Bn.clear(),ps.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let P of ko)A.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"});if(lr.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let P of lr)A.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=k===-1?"":w.slice(k+1).trim(),P=wt();if(!P)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let O=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let V of P.options){let he=V.value===P.currentValue?"* ":" ";O.push({prefix:" ",body:`${he}${V.value.padEnd(16)} ${V.name}`,bodyStyle:"info"})}return I.appendLines(O),!0}let H=P.options.find(O=>O.value===A)?.value;if(!H){let O=A.toLowerCase(),V=P.options.filter(he=>he.value.toLowerCase().startsWith(O));V.length===1&&(H=V[0].value)}return H?H===P.currentValue?(I.notify(`already on agent ${H}`),!0):(I.notify(`switching to ${H}\u2026`),m.request("session/set_config_option",{sessionId:we,configId:"agent",value:H}).catch(O=>{I.notify(`set_config_option failed: ${O.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return R().catch(A=>{ne({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=k===-1?"":w.slice(k+1).trim();return A?A==="next"||A==="prev"?(E(A).catch(P=>{I.notify(`session ${A} failed: ${P.message}`)}),!0):(B(A).catch(P=>{I.notify(`session switch failed: ${P.message}`)}),!0):(R().catch(P=>{ne({src:"switch-session-failed",stack:P instanceof Error?P.stack??P.message:String(P)})}),!0)}case"/rename":{let A=k===-1?"":w.slice(k+1).trim(),P=A.length>0?`/hydra title ${A}`:"/hydra title";return _t(w,w),$o(P,[],w),!0}case"/btw":{let A=k===-1?"":w.slice(k+1).trim();if(!A)return I.isOverlayOpen()?(_&&(_.cancel(),_=null,N=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(we==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;q+=1;let P=q;_&&(_.cancel(),_=null);let H=null;N!==null&&!J?H=N:N!==null&&(Vn(n,N).catch(()=>{}),N=null),J=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new Hc({getMaxWidth:()=>{let ge=I.width();return ge>0?ge:void 0}});O.on("changed",()=>{I.setBtwOverlayContent(O.getLines())});let V={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let he=ge=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ge}})},Re={};return H!==null&&(Re.reuseSessionId=H),Vw(n,we,A,Re).then(ge=>{if(P!==q){ge.cancel();return}_=ge,N=ge.sessionId,I.setBtwOverlayMeta({sessionId:ge.sessionId}),ge.on("event",ke=>{if(P===q)if(ke.kind==="update"){O.append(ke.update);let Ce=Kn(ke.update);if(Ce&&Ce.kind==="usage-update"){let Zt=!1;Ce.used!==void 0&&V.used!==Ce.used&&(V.used=Ce.used,Zt=!0),Ce.size!==void 0&&V.size!==Ce.size&&(V.size=Ce.size,Zt=!0),Ce.costAmount!==void 0&&V.costAmount!==Ce.costAmount&&(V.costAmount=Ce.costAmount,Zt=!0),Ce.costCurrency!==void 0&&V.costCurrency!==Ce.costCurrency&&(V.costCurrency=Ce.costCurrency,Zt=!0),Zt&&I.setBtwOverlayMeta({usage:{...V}})}}else ke.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),_=null):ke.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),_=null,N=null):ke.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),he(`btw errored: ${ke.error.message}`),N!==null&&Vn(n,N).catch(()=>{}),_=null,N=null)})}).catch(ge=>{if(P!==q)return;let ke=ge instanceof Error?ge.message:String(ge);I.setBtwOverlayStatus({label:"errored",style:"errored"}),he(`btw startup failed: ${ke}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ke}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(we==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=k===-1?"":w.slice(k+1).trim(),P=we;return(async()=>{try{let H=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(P)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!H.ok){let ke=await H.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${ke}`.trim(),bodyStyle:"info"}]);return}let O=await H.text(),V=new Date().toISOString().replace(/[:.]/g,"-"),he=`hydra-${lt(P)}-${V}.md`,Re=A.length>0?rt(A):he,ge=Gr.resolve(Re);await op.mkdir(Gr.dirname(ge),{recursive:!0}),await op.writeFile(ge,O,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ge}`,bodyStyle:"system"}])}catch(H){I.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},$o=async(g,w,k)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Re of w)C.push({type:"image",data:Re.data,mimeType:Re.mimeType});ve(1);let A={text:g,displayText:k??g,attachments:w,flushed:!1};nt.push(A),ss=!1;let P=!1,H=null,O=Re=>{typeof Y<"u"&&Y!==null&&Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Re,bodyStyle:"tool-status-fail"}])},V=!1;Ht={text:g,attachments:w,cancel:()=>{if(ss){ss=!1,V=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:we}).catch(ge=>{O(`force-stop failed: ${ge.message}`)});return}if(P)return;P=!0,m.notify("session/cancel",{sessionId:we}).catch(()=>{});let Re=Date.now();H=setTimeout(()=>{Ht!==null&&(Rs>=Re||(ss=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Xr)}};let he;try{let Re=await m.request("session/prompt",{sessionId:we,prompt:C});Re&&typeof Re.stopReason=="string"&&(he=Re.stopReason)}catch(Re){let ge=nt.indexOf(A);ge>=0&&nt.splice(ge,1),A.messageId!==void 0&&pt.delete(A.messageId),V?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Re.message,bodyStyle:"tool-status-fail"}])}finally{if(Ht=null,H!==null&&(clearTimeout(H),H=null),ve(-1),A.flushed&&at===A){let Re=A.messageId!==void 0&&On.has(A.messageId);Re&&A.messageId!==void 0&&On.delete(A.messageId);let ge={kind:"turn-complete"};he!==void 0&&(ge.stopReason=he),Re&&(ge.amended=!0),x(ge),at=null}if(dr!==null){let{text:Re,attachments:ge}=dr;dr=null,_e.state().buffer.every(Ce=>Ce==="")&&(_e.setBuffer(Re,ge),I.refreshPrompt())}}},vt=new Map,ls=new Map,us=new Map,Bs=new Map,hn=[],Ct=0,Sn=`tools:${Ct}`,fs=new Map,wr=new Map,fi=new Set,br=new Map,Bn=new Map,ps=new Map,ft=null,M=null,U=null,ie=null,z=null,ue=e.tui.maxToolItems,le=e.tui.maxPlanItems,je=()=>({maxPlanItems:z??i.planExpanded?1/0:le}),Ne=()=>{if(ie===null)return;let g=Xs(ie,je());g.length>0&&I.upsertLines("plan",[{body:""},...g])},$e="",qe=null,Xt=0,Nn=()=>{if(qe===null)return;let g=I.width(),w=Zs($e,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(qe,w)},St=g=>{g.length!==0&&(qe===null&&(I.ensureSeparator(),qe=`agent:${Xt}`,Xt+=1,$e=""),$e+=g,Nn())},xe=()=>{qe=null,$e=""},ct="",$t=null,Kt=0,Ns=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),vr=()=>{if($t===null||ct.length===0)return;let g=so(ct);g.length!==0&&I.upsertLines($t,g)},al=g=>{let w=Bn.get(g);if(w===void 0)return[];let k=so(w.text);return w.workerTaskId&&k.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),k},dl=(g,w)=>{g.length!==0&&($t===null&&(I.ensureSeparator("thought"),$t=`thought:${Kt}`,Kt+=1,ct=""),ct+=g,Bn.set($t,{text:ct,workerTaskId:w}),vr())},kn=()=>{$t=null,ct=""},Ye=g=>ET({...g,collapsedLimit:ue}),hs=g=>wr.get(g)??i.toolsExpanded,Rt=()=>{if(ft===null)return;let{lines:g,rowOwners:w}=Ye({order:hn,states:vt,startedAt:ft,endedAt:M,stopReason:U,expanded:hs(Sn),perToolExpanded:fi});I.upsertLines(Sn,g),br.set(Sn,w)},Sr=g=>{let w=fs.get(g);if(!w)return;let{lines:k,rowOwners:C}=Ye({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:hs(g),perToolExpanded:fi});I.upsertLines(g,k),br.set(g,C)},uv=()=>{ft!==null&&!fs.has(Sn)&&Rt();for(let g of fs.keys())Sr(g)},cl=()=>{ft!==null&&fs.set(Sn,{order:[...hn],states:new Map(vt),startedAt:ft,endedAt:M??Date.now(),stopReason:U,rowOwners:br.get(Sn)??[]})},hp=()=>{Ct+=1,Sn=`tools:${Ct}`,ft=Date.now(),M=null,U=null,Rt()};function fv(g){if(!g||typeof g!="object")return null;let w=g,k=Array.isArray(w.content)?w.content:void 0;if(!k)return null;let C=[],A=P=>{if(typeof P=="string"){C.push({text:ht(P)});return}if(P&&typeof P=="object"){let H=P;typeof H.__hydraBlob=="string"&&C.push({hash:H.__hydraBlob})}};for(let P of k){if(!P||typeof P!="object")continue;let H=P;if(H.type==="content"&&H.content&&typeof H.content=="object"){let O=H.content;if(O.text!==void 0){A(O.text);continue}}if(H.type==="text"&&H.text!==void 0){A(H.text);continue}H.text!==void 0&&A(H.text)}return C.length>0?C:null}let mp=(g,w)=>{let k=w.map(P=>"text"in P?P.text:"").join(`
244
+ `);if(k.length===0)return;let{text:C,truncated:A}=ky(k);g.resultText=C,g.resultTruncated=A},Wa=new Set,pv=(g,w)=>{!w.some(C=>"hash"in C)||Wa.has(g)||(Wa.add(g),(async()=>{let C=await Promise.all(w.map(async P=>"text"in P?P:{text:await ll(P.hash)??""}));Wa.delete(g);let A=vt.get(g);if(!A)for(let P of fs.values()){let H=P.states.get(g);if(H){A=H;break}}if(A){mp(A,C),vt.has(g)&&Rt();for(let[P,H]of fs)H.states.has(g)&&Sr(P);I.repaintNow()}})().catch(()=>{Wa.delete(g)}))},gp=(g,w,k,C,A,P,H,O,V,he)=>{let Re=!vt.has(g),ge=vt.get(g),ke=ge??{initialTitle:w??"tool",latestTitle:w??"tool",status:k??"pending",startedAt:Date.now()};if(!ge&&V!==void 0&&(ke.workerTaskId=V),ge&&w!==void 0&&(ke.latestTitle=w),P!==void 0&&ke.detail===void 0&&(ke.detail=P),H!==void 0&&ke.detailFull===void 0&&(ke.detailFull=H),O!==void 0&&O.length>0&&(ke.locations=O),ge&&k!==void 0&&(ke.status=k),ge||(ke.status=k??"pending"),ke.endedAt===void 0&&ef(ke.status)&&(ke.endedAt=Date.now()),C!==void 0&&(ke.errorText=C),A!==void 0&&(ke.editDiff=A),he!==void 0){let Ce=fv(he);Ce!==null&&(mp(ke,Ce),Ce.some(Zt=>"hash"in Zt)&&pv(g,Ce))}vt.set(g,ke),Re&&(ft===null&&(Ct+=1,Sn=`tools:${Ct}`,ft=Date.now(),M=null,U=null),hn.push(g))},ll=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:we,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},za=new Set,hv=(g,w)=>{za.has(g)||w.oldRef===void 0&&w.newRef===void 0||(za.add(g),(async()=>{let[k,C]=await Promise.all([w.oldRef?ll(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?ll(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&k===null||w.newRef!==void 0&&C===null){za.delete(g);let he=Xu(w,"diff",{deferredStatus:"error"});he.length>0&&(I.upsertLines(`editdiff:${g}`,he),I.repaintNow());return}let P={...w.path!==void 0?{path:w.path}:{},oldText:k??"",newText:C??""};ls.set(g,P);let H=vt.get(g);H?.editDiff&&(H.editDiff=P),za.delete(g);let O=us.get(g),V=O===void 0?i.showFileUpdates:O?"diff":"edit";V!=="none"&&(Ka(g,P,V==="diff"?"diff":"edit"),I.repaintNow())})())},Ka=(g,w,k)=>{let C=`editdiff:${g}`,A=Xu(w,k);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),k==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&I.notifyWhenVisible(C)},mv=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),k=ls.get(w);k&&(k.oldRef!==void 0||k.newRef!==void 0)&&hv(w,k)},yp=g=>{let w=`editdiff:${g}`,k=i.showFileUpdates,C=vt.get(g),A;if(k==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let H=us.get(g);A=H!==void 0?H?"diff":"edit":k==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let P=C.editDiff;ls.set(g,P),Ka(g,P,A)},gv=()=>{let g=i.showFileUpdates;for(let[w,k]of ls){let C=`editdiff:${w}`,A=us.get(w),P=A===void 0?g:A?"diff":"edit";if(P==="none"){I.removeKey(C);continue}Ka(w,k,P==="diff"?"diff":"edit")}},yv=g=>{if(!g.path)return null;let w=ht(g.oldText).split(`
245
245
  `),k=ht(g.newText).split(`
246
- `),C=0,A=Math.min(w.length,k.length);for(;C<A&&w[C]===k[C];)C++;let P=k[C];if(!P)return null;let H=Gr.isAbsolute(g.path)?g.path:Gr.resolve(Ke,g.path),O;try{O=hT(H,"utf8")}catch{return null}let V=O.split(`
247
- `);for(let he=0;he<V.length;he++)if(V[he]===P)return he+1;return null},yv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=ls.get(k),P=vt.get(k)?.locations?.[0],H=P?.path??C?.path;if(!H)return!1;let O=null;P?.line!==void 0?O=P.line:C&&(O=gv(C));let V=O===null?"":`:${O}`;return I.tryOpenPathString(H+V)}if(g.startsWith("tools:")){if(w===0)return!1;let k=br.get(g),C=k?k[w]:void 0;if(!C)return!1;let A=vt.get(C),P=A?.locations?.[0];if(P){let O=P.line===void 0?"":`:${P.line}`;if(I.tryOpenPathString(P.path+O))return!0}let H=A?.detailFull??A?.detail;if(H)return I.tryOpenPathString(H)}return!1},wv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=ls.get(k);if(!C)return;let A=us.get(k)??i.showFileUpdates==="diff";us.set(k,!A),Ka(k,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(ie===null)return;z=!(z??i.planExpanded),Ne(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=wr.get(g)??i.toolsExpanded;wr.set(g,!A),g===Sn&&ft!==null?Rt():Sr(g),I.repaintNow();return}let k=br.get(g);if(!k)return;let C=k[w];if(!C)return;CT(C,fi),Sr(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Bn.has(g))return;let k=ps.get(g);if(k!==void 0){ps.delete(g),I.setRunCollapsed(k,!1,al(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Bn.keys()));if(C.length===0)return;let A=C[0];ps.set(A,C),I.setRunCollapsed(C,!0,[Ns()]),I.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){lr=g.commands,Ps();return}if(g.kind==="available-modes"){yt=g.modes;return}if(g.kind==="config-options"){Na=g.options;let C=g.options.find(P=>P.id==="agent");C&&C.currentValue&&C.currentValue!==et&&(et=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(P=>P.id==="mode");A&&(yt=A.options.map(P=>({id:P.value,name:P.name??P.value,...P.description!==void 0?{description:P.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==et&&(et=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&cn.used!==g.used&&(cn.used=g.used,C=!0),g.size!==void 0&&cn.size!==g.size&&(cn.size=g.size,C=!0),g.costAmount!==void 0&&cn.costAmount!==g.costAmount&&(cn.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&cn.costCurrency!==g.costCurrency&&(cn.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...cn}});return}if(g.kind==="user-text"){Mn&&_t(g.text),xe(),kn(),ft!==null&&(M=Date.now(),Rt()),at=null,I.ensureSeparator();let C=Xs(g);C.length>0&&I.appendLines(C),cl(),I.clearKey("plan"),ie=null,z=null,vt.clear(),Bs.clear(),pn.length=0,M=null,hp(),I.redraw();return}if(g.kind==="agent-text"){kn(),qe===null&&F(g.workerTaskId),St(g.text);return}if(g.kind==="agent-thought"){xe(),$t===null&&F(g.workerTaskId),dl(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){xe(),kn();let C=Bs.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(Bs.set(g.toolCallId,A),A.plan.length===0)return;let P=Ty(A);P.length>0&&I.upsertLines(g.toolCallId,P);return}if(g.kind==="tool-call"){xe(),kn(),vt.has(g.toolCallId)||F(g.workerTaskId),gp(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Rt(),yp(g.toolCallId);return}if(g.kind==="plan"){xe(),kn(),ie=g;let C=Xs(g,je());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(P=>(P.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){xe(),kn(),gp(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(ns=!0),Rt(),yp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let k=Xs(g);if(k.length>0&&I.appendLines(k),g.kind==="turn-complete"){ee=void 0,xe(),kn();let C=g.amended?"amended":g.stopReason;if(!g.amended&&ns&&(C===void 0||C==="end_turn")&&(C="error"),ie!==null&&C!==void 0&&C!=="end_turn"){let A=Xs({...ie,stopped:!0,amended:g.amended===!0},je());A.length>0&&I.upsertLines("plan",[{body:""},...A])}ie=null,z=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),ft!==null?(M=Date.now(),U=C??null,Rt(),cl()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),vt.clear(),Bs.clear(),pn.length=0,ft=null,M=null,U=null,ns=!1,I.ensureSeparator(),qb({pendingTurns:L,queueSize:Ue.size,ownTurnInFlight:Ht!==null,hasInFlightHead:ee!==void 0,replayDraining:S,amended:g.amended===!0})&&ve(-L)}};let wp=y;y=[];let Ja=[];for(let{event:g}of wp)g.kind==="user-text"&&typeof g.text=="string"&&Ja.push(g.text);I.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of wp)b(g,w)}finally{S=!1,I.resumeRepaint()}if(Ja.length>0){let g=Su(Et,Ja);g!==Et&&(Et=g,Mt=Su(Mt,Ja),_e.setHistory(xd(Pt,Mt)),_r(ar,Et).catch(()=>{}))}Mn=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(we)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),k=w.compactionState?.status;if(k==="requested"||k==="running"?I.setCompactionIndicator("compacting..."):(k==="swap_pending"||k==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!or||w.shouldCompact!==!0)return;let C=w.approxTokens??0;D=!0,I.setCompactionPrompt({message:`This session has ~${Vm(C)} 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(we)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rs()):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Pn!==void 0&&L>0?(ae=Pn,I.setBanner({status:"busy",elapsedMs:Date.now()-Pn}),G===null&&(G=Be()),ft===null&&hp(),ft=Pn,Rt()):Pn===void 0&&L>0&&ve(-L);let bv=()=>{if(pe){let g=pe.resolve;pe=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}xe(),kn()},bp=()=>{ft!==null&&(M=Date.now(),U="reconnect-recovery-failed",Rt(),cl(),vt.clear(),Bs.clear(),pn.length=0,ft=null,M=null,U=null)};return p=g=>{ne({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{if(ne({src:"reconnect",step:"begin",sessionId:we}),n.isLocal)try{let O=await Ut(await Ie());(O.baseUrl!==n.baseUrl||O.wsUrl!==n.wsUrl)&&(ne({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:O.baseUrl}),n.baseUrl=O.baseUrl,n.wsUrl=O.wsUrl,n.display=O.display)}catch(O){ne({src:"reconnect",step:"target-refresh-failed",message:O instanceof Error?O.message:String(O)})}bv();let g={jsonrpc:"2.0",id:`tui-reinit-${Kb()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:me}}};ne({src:"reconnect",step:"initialize-send"});try{await h.request(g),ne({src:"reconnect",step:"initialize-ok"})}catch(O){ne({src:"reconnect",step:"initialize-fail",message:O.message})}let w=De!==void 0,k={jsonrpc:"2.0",id:`tui-reattach-${Kb()}`,method:"session/attach",params:{sessionId:we,historyPolicy:w?"after_message":"none",...w?{afterMessageId:De}:{},clientInfo:{name:"hydra-acp-tui",version:me},...(()=>{let O={};return ti!==void 0&&(O.resume={upstreamSessionId:ti,agentId:et,cwd:Ke}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[Lt]:O}}:{}})()}};Yt=[];let C,A,P;ne({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:De});try{let O=await h.request(k);if(ne({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);P=jb(O.result),C=P.appliedPolicy,P.clientId!==void 0&&(Es=P.clientId)}catch(O){A=O,ne({src:"reconnect",step:"attach-fail",message:A.message})}let H=Yt??[];if(Yt=null,A)bp(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")bp(),I.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{S=!0;try{for(let O of H)dn(O)}finally{S=!1}}if(P){let O=Wb({daemonTurnStartedAt:P.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&ve(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(ae=O.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),G===null&&(G=Be())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});ne({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
246
+ `),C=0,A=Math.min(w.length,k.length);for(;C<A&&w[C]===k[C];)C++;let P=k[C];if(!P)return null;let H=Gr.isAbsolute(g.path)?g.path:Gr.resolve(Ke,g.path),O;try{O=mT(H,"utf8")}catch{return null}let V=O.split(`
247
+ `);for(let he=0;he<V.length;he++)if(V[he]===P)return he+1;return null},wv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=ls.get(k),P=vt.get(k)?.locations?.[0],H=P?.path??C?.path;if(!H)return!1;let O=null;P?.line!==void 0?O=P.line:C&&(O=yv(C));let V=O===null?"":`:${O}`;return I.tryOpenPathString(H+V)}if(g.startsWith("tools:")){if(w===0)return!1;let k=br.get(g),C=k?k[w]:void 0;if(!C)return!1;let A=vt.get(C),P=A?.locations?.[0];if(P){let O=P.line===void 0?"":`:${P.line}`;if(I.tryOpenPathString(P.path+O))return!0}let H=A?.detailFull??A?.detail;if(H)return I.tryOpenPathString(H)}return!1},bv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=ls.get(k);if(!C)return;let A=us.get(k)??i.showFileUpdates==="diff";us.set(k,!A),Ka(k,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(ie===null)return;z=!(z??i.planExpanded),Ne(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=wr.get(g)??i.toolsExpanded;wr.set(g,!A),g===Sn&&ft!==null?Rt():Sr(g),I.repaintNow();return}let k=br.get(g);if(!k)return;let C=k[w];if(!C)return;RT(C,fi),Sr(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Bn.has(g))return;let k=ps.get(g);if(k!==void 0){ps.delete(g),I.setRunCollapsed(k,!1,al(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Bn.keys()));if(C.length===0)return;let A=C[0];ps.set(A,C),I.setRunCollapsed(C,!0,[Ns()]),I.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){lr=g.commands,Ps();return}if(g.kind==="available-modes"){yt=g.modes;return}if(g.kind==="config-options"){Na=g.options;let C=g.options.find(P=>P.id==="agent");C&&C.currentValue&&C.currentValue!==et&&(et=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(P=>P.id==="mode");A&&(yt=A.options.map(P=>({id:P.value,name:P.name??P.value,...P.description!==void 0?{description:P.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==et&&(et=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&ln.used!==g.used&&(ln.used=g.used,C=!0),g.size!==void 0&&ln.size!==g.size&&(ln.size=g.size,C=!0),g.costAmount!==void 0&&ln.costAmount!==g.costAmount&&(ln.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&ln.costCurrency!==g.costCurrency&&(ln.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...ln}});return}if(g.kind==="user-text"){Mn&&_t(g.text),xe(),kn(),ft!==null&&(M=Date.now(),Rt()),at=null,I.ensureSeparator();let C=Xs(g);C.length>0&&I.appendLines(C),cl(),I.clearKey("plan"),ie=null,z=null,vt.clear(),Bs.clear(),hn.length=0,M=null,hp(),I.redraw();return}if(g.kind==="agent-text"){kn(),qe===null&&F(g.workerTaskId),St(g.text);return}if(g.kind==="agent-thought"){xe(),$t===null&&F(g.workerTaskId),dl(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){xe(),kn();let C=Bs.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(Bs.set(g.toolCallId,A),A.plan.length===0)return;let P=Ty(A);P.length>0&&I.upsertLines(g.toolCallId,P);return}if(g.kind==="tool-call"){xe(),kn(),vt.has(g.toolCallId)||F(g.workerTaskId),gp(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Rt(),yp(g.toolCallId);return}if(g.kind==="plan"){xe(),kn(),ie=g;let C=Xs(g,je());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(P=>(P.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){xe(),kn(),gp(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(ns=!0),Rt(),yp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let k=Xs(g);if(k.length>0&&I.appendLines(k),g.kind==="turn-complete"){ee=void 0,xe(),kn();let C=g.amended?"amended":g.stopReason;if(!g.amended&&ns&&(C===void 0||C==="end_turn")&&(C="error"),ie!==null&&C!==void 0&&C!=="end_turn"){let A=Xs({...ie,stopped:!0,amended:g.amended===!0},je());A.length>0&&I.upsertLines("plan",[{body:""},...A])}ie=null,z=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),ft!==null?(M=Date.now(),U=C??null,Rt(),cl()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),vt.clear(),Bs.clear(),hn.length=0,ft=null,M=null,U=null,ns=!1,I.ensureSeparator(),Wb({pendingTurns:L,queueSize:Ue.size,ownTurnInFlight:Ht!==null,hasInFlightHead:ee!==void 0,replayDraining:S,amended:g.amended===!0})&&ve(-L)}};let wp=y;y=[];let Ja=[];for(let{event:g}of wp)g.kind==="user-text"&&typeof g.text=="string"&&Ja.push(g.text);I.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of wp)b(g,w)}finally{S=!1,I.resumeRepaint()}if(Ja.length>0){let g=Su(Et,Ja);g!==Et&&(Et=g,Mt=Su(Mt,Ja),_e.setHistory(xd(Pt,Mt)),_r(ar,Et).catch(()=>{}))}Mn=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(we)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),k=w.compactionState?.status;if(k==="requested"||k==="running"?I.setCompactionIndicator("compacting..."):(k==="swap_pending"||k==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!or||w.shouldCompact!==!0)return;let C=w.approxTokens??0;D=!0,I.setCompactionPrompt({message:`This session has ~${Vm(C)} 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(we)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rs()):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Pn!==void 0&&L>0?(ae=Pn,I.setBanner({status:"busy",elapsedMs:Date.now()-Pn}),G===null&&(G=Be()),ft===null&&hp(),ft=Pn,Rt()):Pn===void 0&&L>0&&ve(-L);let vv=()=>{if(pe){let g=pe.resolve;pe=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}xe(),kn()},bp=()=>{ft!==null&&(M=Date.now(),U="reconnect-recovery-failed",Rt(),cl(),vt.clear(),Bs.clear(),hn.length=0,ft=null,M=null,U=null)};return p=g=>{ne({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{if(ne({src:"reconnect",step:"begin",sessionId:we}),n.isLocal)try{let O=await Ut(await Ie());(O.baseUrl!==n.baseUrl||O.wsUrl!==n.wsUrl)&&(ne({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:O.baseUrl}),n.baseUrl=O.baseUrl,n.wsUrl=O.wsUrl,n.display=O.display)}catch(O){ne({src:"reconnect",step:"target-refresh-failed",message:O instanceof Error?O.message:String(O)})}vv();let g={jsonrpc:"2.0",id:`tui-reinit-${Jb()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:me}}};ne({src:"reconnect",step:"initialize-send"});try{await h.request(g),ne({src:"reconnect",step:"initialize-ok"})}catch(O){ne({src:"reconnect",step:"initialize-fail",message:O.message})}let w=De!==void 0,k={jsonrpc:"2.0",id:`tui-reattach-${Jb()}`,method:"session/attach",params:{sessionId:we,historyPolicy:w?"after_message":"none",...w?{afterMessageId:De}:{},clientInfo:{name:"hydra-acp-tui",version:me},...(()=>{let O={};return ti!==void 0&&(O.resume={upstreamSessionId:ti,agentId:et,cwd:Ke}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[Lt]:O}}:{}})()}};Vt=[];let C,A,P;ne({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:De});try{let O=await h.request(k);if(ne({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);P=qb(O.result),C=P.appliedPolicy,P.clientId!==void 0&&(Es=P.clientId)}catch(O){A=O,ne({src:"reconnect",step:"attach-fail",message:A.message})}let H=Vt??[];if(Vt=null,A)bp(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")bp(),I.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{S=!0;try{for(let O of H)cn(O)}finally{S=!1}}if(P){let O=zb({daemonTurnStartedAt:P.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&ve(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(ae=O.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),G===null&&(G=Be())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});ne({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
248
248
  connection lost: ${g.message}
249
- `),Fs(g?1:0)}),process.on("SIGINT",Vt),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&gr(s.initialPrompt??"",s.initialAttachments??[]),await Co}async function PT(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 Qb(t,n,s,i)!=="ok"?null:Vb(s,o,e);if(s.resume){let a=await Yn(n,{cwd:o,all:!0}),c=pc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
250
- `),null)}for(;;){let a=await Yn(n,{includeNonInteractive:!0}),c=await rp(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(c.kind==="abort"||c.kind==="exit")return null;if(c.kind==="new"){c.prompt!==void 0&&(s.initialPrompt=c.prompt),c.attachments&&c.attachments.length>0&&(s.initialAttachments=c.attachments),c.cwd!==void 0&&(o=c.cwd,s.cwd=c.cwd);let u=await Qb(t,n,s,i);if(u==="cancel")return null;if(u==="back")continue;return Vb(s,o,e)}if(c.kind==="fork"){let u=await ev(t,n,c,a);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}s.readonly=c.readonly===!0;let d=a.find(u=>u.sessionId===c.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let u=await Xb(t,n,d,c,s);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await Aa(d.cwd)).ok){let f=await Qr(t,d,{defaultCwd:rt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let p=c.agentId??d.agentId??"";return{sessionId:c.sessionId,agentId:p,cwd:f.path,resumeHint:{agentId:p,cwd:f.path,upstreamSessionId:""}}}return{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}}}async function Xb(t,e,n,s,r){for(;;){let i=await Tb(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 Zb(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await Qr(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 Zb(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await uc(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 ip(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 ev(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await Zb(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 u=await Qr(t,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??n.sourceAgentId??"",l;try{l=await fc(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
249
+ `),Fs(g?1:0)}),process.on("SIGINT",Qt),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&gr(s.initialPrompt??"",s.initialAttachments??[]),await Co}async function MT(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 Gb(t,n,s,i)!=="ok"?null:Qb(s,o,e);if(s.resume){let a=await Yn(n,{cwd:o,all:!0}),c=pc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
250
+ `),null)}for(;;){let a=await Yn(n,{includeNonInteractive:!0}),c=await rp(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(c.kind==="abort"||c.kind==="exit")return null;if(c.kind==="new"){c.prompt!==void 0&&(s.initialPrompt=c.prompt),c.attachments&&c.attachments.length>0&&(s.initialAttachments=c.attachments),c.cwd!==void 0&&(o=c.cwd,s.cwd=c.cwd);let u=await Gb(t,n,s,i);if(u==="cancel")return null;if(u==="back")continue;return Qb(s,o,e)}if(c.kind==="fork"){let u=await tv(t,n,c,a);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}s.readonly=c.readonly===!0;let d=a.find(u=>u.sessionId===c.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let u=await Zb(t,n,d,c,s);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await Aa(d.cwd)).ok){let f=await Qr(t,d,{defaultCwd:rt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let p=c.agentId??d.agentId??"";return{sessionId:c.sessionId,agentId:p,cwd:f.path,resumeHint:{agentId:p,cwd:f.path,upstreamSessionId:""}}}return{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}}}async function Zb(t,e,n,s,r){for(;;){let i=await Eb(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 ev(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await Qr(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 ev(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await uc(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 ip(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 tv(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await ev(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 u=await Qr(t,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??n.sourceAgentId??"",l;try{l=await fc(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
251
251
  fork failed: ${u.message}
252
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Vb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Qb(t,e,n,s){if(n.agentId||await Mp())return"ok";let r;try{r=await uc(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await Ie(),o=s.lastChosenAgent??i.defaultAgent,a=await ip(t,r,o);if(a.kind==="cancel")return"cancel";if(a.kind==="back")return"back";if(n.agentId=a.agentId,s.lastChosenAgent=a.agentId,a.persist)try{await Qa(a.agentId)}catch{}return"ok"}function MT(t,e){ne({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function _T(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,u=c.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),h=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${d} ${f}/${p} MB (${h}%)`}return`${e} downloading ${d} ${f} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
253
- `))}}}var dp,xT,AT,Yb,tv=K(()=>{"use strict";Pr();Bt();If();tt();Tf();Rr();Br();ia();Bo();Yw();qn();ye();Tr();sn();Oc();Cf();Ad();pa();Qw();Gw();Nb();ep();Xf();Db();kf();Ub();Gf();$u();Lf();Uc();Wc();Zc();tp();zb();Ks();ro();dp="dismiss";xT=12e4;AT=[["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"]];Yb=!1});var nv={};ul(nv,{runTui:()=>Gb});var sv=K(()=>{"use strict";tv()});import{readFileSync as $T}from"fs";import{fileURLToPath as FT}from"url";import{dirname as OT,resolve as LT}from"path";var vp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),Sv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Sp(t){for(let e of Object.keys(t))if(!vp.has(e)&&!Sv.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(vp.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 kv(t,e){let n=t[e];if(typeof n=="string")return n}function pi(t,e){return t[e]===!0||t[e]==="true"}var Iv="HYDRA_ACP_";function xv(t){return Iv+t.toUpperCase().replace(/-/g,"_")}function kt(t,e){let n=kv(t,e);return n!==void 0?n:process.env[xv(e)]}tt();Rr();async function Yp(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=wl(n);return{target:await Kp(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ie();return{target:await Ut(s),sessionId:n,fromUrl:!1}}function El(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}Tr();ye();tt();ms();import*as Gp from"fs/promises";async function Xp(t){if(await Gp.mkdir($.home(),{recursive:!0}),await Va(),!await gi()){let n=mi();await yi(n),process.stdout.write(`Initialized ${$.authToken()}
252
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Qb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Gb(t,e,n,s){if(n.agentId||await Mp())return"ok";let r;try{r=await uc(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await Ie(),o=s.lastChosenAgent??i.defaultAgent,a=await ip(t,r,o);if(a.kind==="cancel")return"cancel";if(a.kind==="back")return"back";if(n.agentId=a.agentId,s.lastChosenAgent=a.agentId,a.persist)try{await Qa(a.agentId)}catch{}return"ok"}function _T(t,e){ne({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function $T(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,u=c.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),h=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${d} ${f}/${p} MB (${h}%)`}return`${e} downloading ${d} ${f} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
253
+ `))}}}var dp,AT,CT,Vb,nv=K(()=>{"use strict";Pr();Bt();If();tt();Tf();Rr();Br();ia();Bo();Yw();qn();ye();Tr();rn();Oc();Cf();Ad();pa();Qw();Gw();Db();ep();Xf();Hb();kf();jb();Gf();$u();Lf();Uc();Wc();Zc();tp();Kb();Ks();ro();dp="dismiss";AT=12e4;CT=[["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"]];Vb=!1});var sv={};ul(sv,{runTui:()=>Xb});var rv=K(()=>{"use strict";nv()});import{readFileSync as FT}from"fs";import{fileURLToPath as OT}from"url";import{dirname as LT,resolve as BT}from"path";var vp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),kv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Sp(t){for(let e of Object.keys(t))if(!vp.has(e)&&!kv.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(vp.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 Iv(t,e){let n=t[e];if(typeof n=="string")return n}function pi(t,e){return t[e]===!0||t[e]==="true"}var xv="HYDRA_ACP_";function Av(t){return xv+t.toUpperCase().replace(/-/g,"_")}function kt(t,e){let n=Iv(t,e);return n!==void 0?n:process.env[Av(e)]}tt();Rr();async function Yp(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=wl(n);return{target:await Kp(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ie();return{target:await Ut(s),sessionId:n,fromUrl:!1}}function El(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}Tr();ye();tt();ms();import*as Gp from"fs/promises";async function Xp(t){if(await Gp.mkdir($.home(),{recursive:!0}),await Va(),!await gi()){let n=mi();await yi(n),process.stdout.write(`Initialized ${$.authToken()}
254
254
  Service token: ${n}
255
255
  `);return}if(pi(t,"rotate-token")){let n=mi();await yi(n),process.stdout.write(`Rotated token in ${$.authToken()}
256
256
  New token: ${n}
257
257
  `);return}process.stdout.write(`Service token already exists at ${$.authToken()}.
258
258
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
259
- `)}ye();bi();tt();ms();import{setTimeout as vA}from"timers/promises";import Wg from"chalk";import*as Ng from"fs";import*as zi from"fs/promises";import*as Dg from"net";import*as Hg from"tls";import cA from"fastify";import lA from"@fastify/websocket";var Zp="acp.v1";function eh(t,e){return t.has(Zp)?Zp:!1}tt();import Bg from"pino";import uA from"pino-roll";ye();import*as Ot from"fs/promises";import{createHash as cS}from"crypto";import{gzip as lS,gunzip as uS}from"zlib";import{promisify as th}from"util";var nh=th(lS),fS=th(uS),sh=/^[A-Za-z0-9_-]+$/,pS=/^[a-f0-9]{64}$/,Pl=!0;function rh(t){Pl=t}function td(t,e){return sh.test(t)?e===void 0||pS.test(e):!1}function nd(t,e){return`${$.toolBlobFile(t,e)}.gz`}async function Ml(t,e){if(!td(t))return null;let n=cS("sha256").update(e,"utf8").digest("hex"),s=nd(t,n),r=$.toolBlobFile(t,n);for(let a of[s,r])try{return await Ot.access(a),n}catch{}await Ot.mkdir($.toolsDir(t),{recursive:!0});let i=Pl?s:r,o=Pl?await nh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Ot.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function sd(t,e){if(!td(t,e))return null;try{let n=await Ot.readFile(nd(t,e));return(await fS(n)).toString("utf8")}catch{}try{return await Ot.readFile($.toolBlobFile(t,e),"utf8")}catch{return null}}async function ih(t,e){if(!td(t,e))return null;try{return await Ot.readFile(nd(t,e))}catch{}try{let n=await Ot.readFile($.toolBlobFile(t,e));return await nh(n)}catch{return null}}async function oh(t,e,n){if(!td(t,e))return;let s=nd(t,e);try{await Ot.access(s);return}catch{}await Ot.mkdir($.toolsDir(t),{recursive:!0}),await Ot.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function ah(t){sh.test(t)&&await Ot.rm($.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}ye();tt();Ir();import*as wh from"fs/promises";import*as id from"path";import{z as se}from"zod";ye();import*as ch from"fs";import*as jt from"fs/promises";import*as Hs from"path";import{spawn as lh}from"child_process";import{Readable as hS}from"stream";function Hn(){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 Fl(t,e=Hn()){if(e)return t[e]}var vi=t=>{process.stderr.write(t+`
259
+ `)}ye();bi();tt();ms();import{setTimeout as SA}from"timers/promises";import Wg from"chalk";import*as Ng from"fs";import*as zi from"fs/promises";import*as Dg from"net";import*as Hg from"tls";import lA from"fastify";import uA from"@fastify/websocket";var Zp="acp.v1";function eh(t,e){return t.has(Zp)?Zp:!1}tt();import Bg from"pino";import fA from"pino-roll";ye();import*as Ot from"fs/promises";import{createHash as lS}from"crypto";import{gzip as uS,gunzip as fS}from"zlib";import{promisify as th}from"util";var nh=th(uS),pS=th(fS),sh=/^[A-Za-z0-9_-]+$/,hS=/^[a-f0-9]{64}$/,Pl=!0;function rh(t){Pl=t}function td(t,e){return sh.test(t)?e===void 0||hS.test(e):!1}function nd(t,e){return`${$.toolBlobFile(t,e)}.gz`}async function Ml(t,e){if(!td(t))return null;let n=lS("sha256").update(e,"utf8").digest("hex"),s=nd(t,n),r=$.toolBlobFile(t,n);for(let a of[s,r])try{return await Ot.access(a),n}catch{}await Ot.mkdir($.toolsDir(t),{recursive:!0});let i=Pl?s:r,o=Pl?await nh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Ot.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function sd(t,e){if(!td(t,e))return null;try{let n=await Ot.readFile(nd(t,e));return(await pS(n)).toString("utf8")}catch{}try{return await Ot.readFile($.toolBlobFile(t,e),"utf8")}catch{return null}}async function ih(t,e){if(!td(t,e))return null;try{return await Ot.readFile(nd(t,e))}catch{}try{let n=await Ot.readFile($.toolBlobFile(t,e));return await nh(n)}catch{return null}}async function oh(t,e,n){if(!td(t,e))return;let s=nd(t,e);try{await Ot.access(s);return}catch{}await Ot.mkdir($.toolsDir(t),{recursive:!0}),await Ot.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function ah(t){sh.test(t)&&await Ot.rm($.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}ye();tt();Ir();import*as wh from"fs/promises";import*as id from"path";import{z as se}from"zod";ye();import*as ch from"fs";import*as jt from"fs/promises";import*as Hs from"path";import{spawn as lh}from"child_process";import{Readable as mS}from"stream";function Hn(){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 Fl(t,e=Hn()){if(e)return t[e]}var vi=t=>{process.stderr.write(t+`
260
260
  `)};function Ol(t){vi=t??(e=>process.stderr.write(e+`
261
- `))}async function uh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Hn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentInstallDir(t.agentId,e,t.version),s=Hs.resolve(n,t.target.cmd);if(await $l(s))return s;if(await mS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await $l(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await jt.chmod(s,493).catch(()=>{}),s}async function mS(t){await jt.mkdir(Hs.dirname(t.installDir),{recursive:!0});let e=await jt.mkdtemp(`${t.installDir}.partial-`);try{vi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await gS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});vi(`hydra-acp: extracting ${t.agentId}`),Si(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await wS(n,e),await jt.unlink(n).catch(()=>{});try{await jt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await $l(t.installDir)){await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Si(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}vi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Si(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Si(t,e){if(t)try{t(e)}catch{}}async function gS(t){let e=yS(t.url),n=Hs.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=ch.createWriteStream(n),o=hS.fromWeb(s.body);Si(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,Si(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,vi(dh(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),vi(dh(t.agentId,a,r,!0)),Si(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function dh(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 yS(t){let e=new URL(t);return Hs.posix.basename(e.pathname)||"archive"}async function wS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await _l("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await bS("unzip")){await _l("unzip",["-q",t,"-d",e]);return}await _l("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function _l(t,e){return new Promise((n,s)=>{let r=lh(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 bS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=lh(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function $l(t){try{return await jt.access(t),!0}catch{return!1}}ye();import*as en from"fs/promises";import*as Un from"path";import{spawn as vS}from"child_process";var Bl=t=>{process.stderr.write(t+`
261
+ `))}async function uh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Hn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentInstallDir(t.agentId,e,t.version),s=Hs.resolve(n,t.target.cmd);if(await $l(s))return s;if(await gS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await $l(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await jt.chmod(s,493).catch(()=>{}),s}async function gS(t){await jt.mkdir(Hs.dirname(t.installDir),{recursive:!0});let e=await jt.mkdtemp(`${t.installDir}.partial-`);try{vi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await yS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});vi(`hydra-acp: extracting ${t.agentId}`),Si(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await bS(n,e),await jt.unlink(n).catch(()=>{});try{await jt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await $l(t.installDir)){await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Si(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}vi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Si(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Si(t,e){if(t)try{t(e)}catch{}}async function yS(t){let e=wS(t.url),n=Hs.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=ch.createWriteStream(n),o=mS.fromWeb(s.body);Si(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,Si(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,vi(dh(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),vi(dh(t.agentId,a,r,!0)),Si(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function dh(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 wS(t){let e=new URL(t);return Hs.posix.basename(e.pathname)||"archive"}async function bS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await _l("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await vS("unzip")){await _l("unzip",["-q",t,"-d",e]);return}await _l("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function _l(t,e){return new Promise((n,s)=>{let r=lh(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 vS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=lh(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function $l(t){try{return await jt.access(t),!0}catch{return!1}}ye();import*as tn from"fs/promises";import*as Un from"path";import{spawn as SS}from"child_process";var Bl=t=>{process.stderr.write(t+`
262
262
  `)};function Nl(t){Bl=t??(e=>process.stderr.write(e+`
263
- `))}async function ph(t){let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentNpmInstallDir(t.agentId,e,t.version),s=AS(t.packageSpec),r=CS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Un.join(n,"node_modules",".bin",t.bin);if(await Er(o))return o;if(await Er(n)){let u=await fh(i);if(u)return u.binPath}await SS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await fh(i);if(a)return a.binPath;let c=await mh(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 SS(t){await en.mkdir(Un.dirname(t.installDir),{recursive:!0});let e=await en.mkdtemp(`${t.installDir}.partial-`);try{Bl(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Ll(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await xS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await en.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Er(t.installDir)){await en.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ll(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Bl(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Ll(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await en.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Ll(t,e){if(t)try{t(e)}catch{}}var kS=5,IS=25;function xS(t){return hh(t,0)}async function hh(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=vS("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})
264
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<kS)return await new Promise(r=>setTimeout(r,IS*(e+1))),hh(t,e+1);throw n}}function AS(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 CS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function mh(t,e){let n=Un.join(t,"node_modules",e,"package.json");try{let s=await en.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 fh(t){let e=Un.join(t.installDir,"node_modules",".bin"),n=Un.join(e,t.hint);if(await Er(n))return{binName:t.hint,binPath:n};let s=await mh(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Un.join(e,i);if(await Er(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=Un.join(e,i);if(await Er(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Un.join(e,t.basename);if(await Er(r))return{binName:t.basename,binPath:r}}}async function Er(t){try{return await en.access(t),!0}catch{return!1}}var RS=se.object({package:se.string(),bin:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),ki=se.object({archive:se.string().url().optional(),cmd:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),TS=se.object({"darwin-aarch64":ki.optional(),"darwin-x86_64":ki.optional(),"linux-aarch64":ki.optional(),"linux-x86_64":ki.optional(),"windows-x86_64":ki.optional(),"windows-aarch64":ki.optional()}),ES=se.object({package:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),PS=se.object({command:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),MS=se.object({command:se.string().optional(),url:se.string().optional(),description:se.string().optional()}),_S=se.object({npx:RS.optional(),binary:TS.optional(),uvx:ES.optional(),exec:PS.optional()}),$S=se.object({id:se.string(),name:se.string(),version:se.string().optional(),description:se.string().optional(),authors:se.array(se.string()).optional(),license:se.string().optional(),icon:se.string().optional(),repository:se.string().optional(),website:se.string().optional(),distribution:_S,onboarding:MS.optional(),requiredEnv:se.array(se.string().min(1)).optional()}),gh=se.object({version:se.string(),agents:se.array($S),extensions:se.array(se.unknown()).optional()}),rd=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=>Dl(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:rt(n.command??e),args:n.args?.map(rt),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:FS(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=gh.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 hn($.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=gh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Zt($.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function FS(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 Dl(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 Ii(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 Hl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Hl(t){let e=Hn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Fl(t.distribution.binary,e);if(s?.cmd){let r=id.resolve($.agentInstallDir(t.id,e,n),s.cmd);if(await yh(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Dl(t)??s.package,i=$.agentNpmInstallDir(t.id,e,n),o=id.join(i,"node_modules",".bin",r);if(await yh(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function yh(t){try{return await wh.access(t),!0}catch{return!1}}async function mn(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??Dl(t)??r.package,a=n.onInstallProgress;return{command:await ph({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=Fl(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Hn()??"this platform"}.`);let i=n.onInstallProgress,o=await uh({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 DS}from"child_process";import*as fd from"fs";import*as Fh from"path";Bt();function ud(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(`
263
+ `))}async function ph(t){let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentNpmInstallDir(t.agentId,e,t.version),s=CS(t.packageSpec),r=RS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Un.join(n,"node_modules",".bin",t.bin);if(await Er(o))return o;if(await Er(n)){let u=await fh(i);if(u)return u.binPath}await kS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await fh(i);if(a)return a.binPath;let c=await mh(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 kS(t){await tn.mkdir(Un.dirname(t.installDir),{recursive:!0});let e=await tn.mkdtemp(`${t.installDir}.partial-`);try{Bl(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Ll(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await AS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await tn.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Er(t.installDir)){await tn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ll(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Bl(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Ll(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await tn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Ll(t,e){if(t)try{t(e)}catch{}}var IS=5,xS=25;function AS(t){return hh(t,0)}async function hh(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=SS("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})
264
+ stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<IS)return await new Promise(r=>setTimeout(r,xS*(e+1))),hh(t,e+1);throw n}}function CS(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 RS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function mh(t,e){let n=Un.join(t,"node_modules",e,"package.json");try{let s=await tn.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 fh(t){let e=Un.join(t.installDir,"node_modules",".bin"),n=Un.join(e,t.hint);if(await Er(n))return{binName:t.hint,binPath:n};let s=await mh(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Un.join(e,i);if(await Er(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=Un.join(e,i);if(await Er(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Un.join(e,t.basename);if(await Er(r))return{binName:t.basename,binPath:r}}}async function Er(t){try{return await tn.access(t),!0}catch{return!1}}var TS=se.object({package:se.string(),bin:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),ki=se.object({archive:se.string().url().optional(),cmd:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),ES=se.object({"darwin-aarch64":ki.optional(),"darwin-x86_64":ki.optional(),"linux-aarch64":ki.optional(),"linux-x86_64":ki.optional(),"windows-x86_64":ki.optional(),"windows-aarch64":ki.optional()}),PS=se.object({package:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),MS=se.object({command:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),_S=se.object({command:se.string().optional(),url:se.string().optional(),description:se.string().optional()}),$S=se.object({npx:TS.optional(),binary:ES.optional(),uvx:PS.optional(),exec:MS.optional()}),FS=se.object({id:se.string(),name:se.string(),version:se.string().optional(),description:se.string().optional(),authors:se.array(se.string()).optional(),license:se.string().optional(),icon:se.string().optional(),repository:se.string().optional(),website:se.string().optional(),distribution:$S,onboarding:_S.optional(),requiredEnv:se.array(se.string().min(1)).optional()}),gh=se.object({version:se.string(),agents:se.array(FS),extensions:se.array(se.unknown()).optional()}),rd=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=>Dl(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:rt(n.command??e),args:n.args?.map(rt),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:OS(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=gh.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 mn($.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=gh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await en($.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function OS(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 Dl(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 Ii(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 Hl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Hl(t){let e=Hn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Fl(t.distribution.binary,e);if(s?.cmd){let r=id.resolve($.agentInstallDir(t.id,e,n),s.cmd);if(await yh(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Dl(t)??s.package,i=$.agentNpmInstallDir(t.id,e,n),o=id.join(i,"node_modules",".bin",r);if(await yh(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function yh(t){try{return await wh.access(t),!0}catch{return!1}}async function gn(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??Dl(t)??r.package,a=n.onInstallProgress;return{command:await ph({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=Fl(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Hn()??"this platform"}.`);let i=n.onInstallProgress,o=await uh({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 HS}from"child_process";import*as fd from"fs";import*as Fh from"path";Bt();function ud(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(`
265
265
  `);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 u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
266
266
  `)}}),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)+`
267
- `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Pr();ye();var HS=4096,js=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??HS,this.killEscalationMs=e.killEscalationMs??US,this.logger=e.logger,this.fileLog=jS(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()} ---
268
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=ud(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()} ---
267
+ `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Pr();ye();var US=4096,js=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??US,this.killEscalationMs=e.killEscalationMs??jS,this.logger=e.logger,this.fileLog=qS(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()} ---
268
+ `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=ud(n.stdout,n.stdin);this.connection=new Jt(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()} ---
269
269
  `),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()} ---
270
270
  `),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}
271
- stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=DS(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()} ---
271
+ stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=HS(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()} ---
272
272
  `),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()} ---
273
- `),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)})}},US=2e3;function jS(t){try{let e=$.agentLogFile(t);fd.mkdirSync(Fh.dirname(e),{recursive:!0});let n=fd.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Fr from"fs/promises";import*as Td from"os";import*as ta from"path";import{customAlphabet as Xk}from"nanoid";zl();qn();uu();ye();Ir();import*as ws from"fs/promises";import{z as Wn}from"zod";var Lk=Wn.object({version:Wn.literal(1),agentId:Wn.string(),upstreamSessionId:Wn.string(),deletedAt:Wn.string(),upstreamUpdatedAt:Wn.string().optional(),cwd:Wn.string().optional(),title:Wn.string().optional(),reason:Wn.enum(["user","expired"]).optional(),interactive:Wn.boolean().optional()}),bd=class{async add(e){let n={version:1,...e};await Zt($.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await ws.access($.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=$.tombstoneFile(e,n),r=await hn(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 Lk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await ws.unlink($.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await ws.rmdir($.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 ws.readdir($.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 ws.readdir($.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 cm(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as km from"fs/promises";Bt();sn();yd();md();var Dk=12e4;async function um(t,e,n){let s=t.timeoutMs??Dk,r,i,o=!1;try{let a=(async()=>{r=js.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:me}}),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=Uk(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 u=[];r.connection.onNotification("session/update",h=>{let m=Hk(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=n(f);if(!p){let h=JSON.stringify(f.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.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 Sd(t){let e=Pi(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}
273
+ `),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)})}},jS=2e3;function qS(t){try{let e=$.agentLogFile(t);fd.mkdirSync(Fh.dirname(e),{recursive:!0});let n=fd.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Fr from"fs/promises";import*as Td from"os";import*as ta from"path";import{customAlphabet as Zk}from"nanoid";zl();qn();uu();ye();Ir();import*as ws from"fs/promises";import{z as Wn}from"zod";var Bk=Wn.object({version:Wn.literal(1),agentId:Wn.string(),upstreamSessionId:Wn.string(),deletedAt:Wn.string(),upstreamUpdatedAt:Wn.string().optional(),cwd:Wn.string().optional(),title:Wn.string().optional(),reason:Wn.enum(["user","expired"]).optional(),interactive:Wn.boolean().optional()}),bd=class{async add(e){let n={version:1,...e};await en($.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await ws.access($.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=$.tombstoneFile(e,n),r=await mn(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 Bk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await ws.unlink($.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await ws.rmdir($.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 ws.readdir($.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 ws.readdir($.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 cm(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as km from"fs/promises";Bt();rn();yd();md();var Hk=12e4;async function um(t,e,n){let s=t.timeoutMs??Hk,r,i,o=!1;try{let a=(async()=>{r=js.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:me}}),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=jk(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 u=[];r.connection.onNotification("session/update",h=>{let m=Uk(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=n(f);if(!p){let h=JSON.stringify(f.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.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 Sd(t){let e=Pi(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}
274
274
 
275
275
  ${e}
276
276
 
@@ -282,39 +282,39 @@ ${e}
282
282
 
283
283
  ${ru}`:`${n}
284
284
 
285
- ${ru}`;return um(t,s,am)}function Hk(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 Uk(t){let e=new Set;lm(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&lm(e,n.availableModels),e}function lm(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)}}}hu();ye();var jk=2,kd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??jk}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 mn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=$.sessionDir(e);if(await km.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,b,v=0,S,x=Date.now(),T={targetAgentId:r},F=N=>this.opts.onCompactionStateChange?.(e,N,T)??Promise.resolve(),_=N=>{this.opts.broadcastHydraCompaction?.(e,N,T)};await F({status:"requested",requestedAt:x}),_({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:x});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let N=await this.opts.histories.load(e,{maxEntries:1/0});if(N.length===y)break;let J=await fm({agentId:c,cwd:p,plan:l,history:N,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(L,D)=>{F({status:"running",requestedAt:x,iter:m,worker:{upstreamSessionId:L,pid:D??0}})},onFailure:L=>{S=L}});if(J){let L=bm(J.synopsis,N);L&&vm(L)&&(await this.opts.persistSynopsis(e,L,N.length),b=L,v=N.length,S=void 0,await F({status:"running",requestedAt:x,iter:m}),_({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:N.length}),await this.opts.onSynthesisArtifact?.(e,L,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Sm(L)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=N.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(b)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let N=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await F({status:"failed",requestedAt:x,iter:m,lastError:N}),_({sessionUpdate:"hydra_compaction",phase:"failed",error:N})}}catch(N){let J=N instanceof Error?N.message:String(N);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${J}`),await F({status:"failed",requestedAt:x,iter:m,lastError:J}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:J},{targetAgentId:r})}}else{let h=await Sd({agentId:c,cwd:p,plan:l,history:o,modelId:f,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=bm(h.synopsis,o);m&&vm(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=${Sm(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 bm(t,e){let n=gm(e),s=mm(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 vm(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 Sm(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(",")}]`}ye();import*as qt from"fs/promises";function Im(t){return t==="summary"?"summary":"inline"}var mu=256;function xm(t,e){return e!=="summary"?t:t.map(qk)}function qk(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(Am));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=gu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function Wk(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Am(t){if(Wk(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=gu(e.text)),typeof e.content=="string"?n.content=gu(e.content):e.content&&typeof e.content=="object"&&(n.content=Am(e.content)),n}function gu(t){if(typeof t=="string"&&t.length>mu){let e=t.length-mu;return`${t.slice(0,mu)}\u2026[+${e} chars omitted from summary export]`}return t}var zk=2048;function Cm(t){let e=new Set,n=s=>{if(Rm(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 Rm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Kk(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 bu(t,e){if(!Kk(t))return t;let n=t.params,s=n.update,r=await yu(s,e);return{...t,params:{...n,update:r}}}async function yu(t,e){if(typeof t=="string"){if(t.length<=zk)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 yu(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await yu(r,e);return n}return t}async function Tm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await wu(n,e);return s===n?t:{...t,params:s}}async function wu(t,e){if(Rm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await wu(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 wu(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Yo=/^[A-Za-z0-9_-]+$/,Jk=1e3,Id=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Jk}async append(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{await qt.mkdir($.sessionDir(e),{recursive:!0});let s=await bu(n,i=>Ml(e,i)),r=JSON.stringify(s)+`
286
- `;await qt.appendFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{await qt.mkdir($.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await bu(i,o=>Ml(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
285
+ ${ru}`;return um(t,s,am)}function Uk(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 jk(t){let e=new Set;lm(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&lm(e,n.availableModels),e}function lm(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)}}}hu();ye();var qk=2,kd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??qk}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 gn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=$.sessionDir(e);if(await km.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,b,v=0,S,x=Date.now(),T={targetAgentId:r},F=N=>this.opts.onCompactionStateChange?.(e,N,T)??Promise.resolve(),_=N=>{this.opts.broadcastHydraCompaction?.(e,N,T)};await F({status:"requested",requestedAt:x}),_({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:x});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let N=await this.opts.histories.load(e,{maxEntries:1/0});if(N.length===y)break;let J=await fm({agentId:c,cwd:p,plan:l,history:N,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(L,D)=>{F({status:"running",requestedAt:x,iter:m,worker:{upstreamSessionId:L,pid:D??0}})},onFailure:L=>{S=L}});if(J){let L=bm(J.synopsis,N);L&&vm(L)&&(await this.opts.persistSynopsis(e,L,N.length),b=L,v=N.length,S=void 0,await F({status:"running",requestedAt:x,iter:m}),_({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:N.length}),await this.opts.onSynthesisArtifact?.(e,L,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Sm(L)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=N.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(b)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let N=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await F({status:"failed",requestedAt:x,iter:m,lastError:N}),_({sessionUpdate:"hydra_compaction",phase:"failed",error:N})}}catch(N){let J=N instanceof Error?N.message:String(N);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${J}`),await F({status:"failed",requestedAt:x,iter:m,lastError:J}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:J},{targetAgentId:r})}}else{let h=await Sd({agentId:c,cwd:p,plan:l,history:o,modelId:f,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=bm(h.synopsis,o);m&&vm(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=${Sm(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 bm(t,e){let n=gm(e),s=mm(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 vm(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 Sm(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(",")}]`}ye();import*as Wt from"fs/promises";function Im(t){return t==="summary"?"summary":"inline"}var mu=256;function xm(t,e){return e!=="summary"?t:t.map(Wk)}function Wk(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(Am));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=gu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function zk(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Am(t){if(zk(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=gu(e.text)),typeof e.content=="string"?n.content=gu(e.content):e.content&&typeof e.content=="object"&&(n.content=Am(e.content)),n}function gu(t){if(typeof t=="string"&&t.length>mu){let e=t.length-mu;return`${t.slice(0,mu)}\u2026[+${e} chars omitted from summary export]`}return t}var Kk=2048;function Cm(t){let e=new Set,n=s=>{if(Rm(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 Rm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Jk(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 bu(t,e){if(!Jk(t))return t;let n=t.params,s=n.update,r=await yu(s,e);return{...t,params:{...n,update:r}}}async function yu(t,e){if(typeof t=="string"){if(t.length<=Kk)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 yu(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await yu(r,e);return n}return t}async function Tm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await wu(n,e);return s===n?t:{...t,params:s}}async function wu(t,e){if(Rm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await wu(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 wu(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Yo=/^[A-Za-z0-9_-]+$/,Yk=1e3,Id=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Yk}async append(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{await Wt.mkdir($.sessionDir(e),{recursive:!0});let s=await bu(n,i=>Ml(e,i)),r=JSON.stringify(s)+`
286
+ `;await Wt.appendFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{await Wt.mkdir($.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await bu(i,o=>Ml(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
287
287
  `)+`
288
- `;await qt.writeFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{let s;try{s=await qt.readFile($.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
289
- `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await qt.writeFile($.historyFile(e),i.join(`
288
+ `;await Wt.writeFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Yo.test(e))return this.enqueue(e,async()=>{let s;try{s=await Wt.readFile($.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
289
+ `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await Wt.writeFile($.historyFile(e),i.join(`
290
290
  `)+`
291
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Yo.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await qt.readFile($.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
292
- `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}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 f=>{let p=d.get(f);if(p!==void 0)return p;let h=await sd(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await Tm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Yo.test(e))return this.enqueue(e,async()=>{try{await qt.unlink($.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await ah(e);try{await qt.rmdir($.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};ye();tt();Ad();$r();hd();Bt();Bt();sn();Xl();var Mm=900*1e3,Zk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Cd=Xk(Zk,16),Rd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>js.spawn(a)),this.store=s??new wd,this.tombstones=r.tombstones??new bd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Id({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new kd({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 Ii(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_${Cd()}`,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 $i({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=W.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=W.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await mn(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:xi,clientInfo:{name:"hydra",version:me}});o=m.agentCapabilities,i.authMethods=Zo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ws(m,i)}let a;try{let m=_m(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===W.AuthRequired)throw await i.kill().catch(()=>{}),Ws(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
293
- `),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=Cu(a??{}),d=e.agentModes??Iu(Au(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 Ai({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 u=ku(a??{}),f=Iu(xu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ci({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new $i({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:f,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 Ai({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ci({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new $i({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 Fr.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:rt(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=W.AgentNotInstalled,p}let s=await mn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Td.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:xi,clientInfo:{name:"hydra",version:me}})}catch(p){throw await r.kill().catch(()=>{}),Ws(p,r)}if(r.authMethods=Zo(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=$.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(eI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!cm(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${gn}${Cd()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:Ko(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let x=lu(S);await this.store.write(x),u.push({version:1,...x})}return{synced:u,skipped:f}}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=W.AgentNotInstalled,i}let s=await mn(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:xi,clientInfo:{name:"hydra",version:me}}),o=i.agentCapabilities;r.authMethods=Zo(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=ku(a),l=xu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ei(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);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(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Au(a),p=Cu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ws(Fm(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=W.AgentNotInstalled,o}let r=await mn(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:xi,clientInfo:{name:"hydra",version:me}}),a=o.agentCapabilities;i.authMethods=Zo(o.authMethods);let c=_m(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=ku(d),u=Iu(xu(d)),f=Au(d),p=Cu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),Ws(Fm(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=W.AgentNotInstalled,c}let i=await mn(r,[],{npmRegistry:this.npmRegistry}),o=n??rt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:xi,clientInfo:{name:"hydra",version:me}});a.authMethods=Zo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ws(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=W.AgentNotInstalled,s}return mn(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=Bi({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:Lm(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=tI(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 sd(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=Mi(r.update.prompt),o=nu(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(gn))return;let n=gn+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=W.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 ea(n.sessionId),c=Bi({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 ea(s.sessionId),i=Bi(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=>ea(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Bi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.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=>ea(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Bi(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return n.sort((l,u)=>l.updatedAt<u.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=Ko(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Om(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Cm(o)){let l=await ih(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=W.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=`${gn}${Cd()}`;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=W.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let x=new Error(`agent ${r} not found in registry`);throw x.code=W.AgentNotInstalled,x}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=tu(o,n.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw x.code=W.InvalidParams,x}c=n.forkAt,a=o.slice(0,S+1)}else{let S=rI(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 x=new Error(`agent ${r} not found in registry`);throw x.code=W.AgentNotInstalled,x}f=S,u=s.currentModel,l="running"}let h=await Om(e),m=d==="synthesis",y={...s,lineageId:Ko(),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}:{}},b=Xo({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:me,machine:Td.hostname()}),v=`${gn}${Cd()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await mn(f,[],{npmRegistry:this.npmRegistry}),x=await Sd({agentId:r,cwd:n.cwd??$.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});x&&x.synopsis?await this.mutateRecord(v,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:v,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 oh(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Fr.utimes($.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await _r($.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 ea(e),i=Bi(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)})}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 Jh(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<Mm),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Mm/1e3}s)`),await qo(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 qo(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 eI(t,e){if(typeof t!="string"||t.length===0)return!1;let n=ta.resolve(t),s=ta.resolve(e);return n===s||n.startsWith(s+ta.sep)}function tI(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return lu({sessionId:t.sessionId,lineageId:e?.lineageId??Ko(),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:Lm(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(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Lm(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 _m(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ed(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=sI(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function ku(t){return Ed(t,{nestedKey:"models",configId:"model",fromObject:e=>zn(e.currentModelId)??zn(e.currentModel)??zn(e.modelId)??zn(e.model),fromConfig:e=>zn(e.currentValue)})}function Ws(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==W.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=W.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function $m(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Fm(t,e,n,s){if(t&&typeof t=="object"&&t.code===W.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 ${$m(s.cwd)} && ${[s.command,...s.args].map($m).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(`
294
- `));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 Zo(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 zn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function sI(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 Iu(t){return t.length>0?t:void 0}function xu(t){return Ed(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=_i(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=_i(e.options);return n.length>0?n:void 0}})??[]}function Au(t){return Ed(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=Wo(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=Wo(e.options);return n.length>0?n:void 0}})??[]}function Cu(t){return Ed(t,{nestedKey:"modes",configId:"mode",fromObject:e=>zn(e.currentModeId)??zn(e.currentMode)??zn(e.modeId)??zn(e.mode),fromConfig:e=>zn(e.currentValue)})}function rI(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 Om(t){try{let e=await Fr.readFile($.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
295
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function ea(t){try{let e=await Fr.stat($.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Bi(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Mr?!1:e?!0:void 0}import{spawn as iI}from"child_process";import*as Md from"fs";import*as bs from"fs/promises";import*as _d from"path";import oI from"pino-roll";var Pd=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_}};tt();var aI=1e3,dI=6e4,Ru=3e3,Ni=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??aI,this.restartCapMs=r.restartCapMs??dI;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 bs.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()},Ru);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 na(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw na(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 na(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 na(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw na(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{}},Ru);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 Pd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await bs.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 bs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Tu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ru;for(;Date.now()<i&&Tu(r);)await new Promise(o=>setTimeout(o,50));if(Tu(r))try{process.kill(r,"SIGKILL")}catch{}}await bs.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=_d.dirname(this.adapter.paths.logFile(r.name));await bs.mkdir(o,{recursive:!0});let a=await oI({file:_d.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}});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})
291
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Yo.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Wt.readFile($.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
292
+ `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}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 f=>{let p=d.get(f);if(p!==void 0)return p;let h=await sd(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await Tm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Yo.test(e))return this.enqueue(e,async()=>{try{await Wt.unlink($.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await ah(e);try{await Wt.rmdir($.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};ye();tt();Ad();$r();hd();Bt();Bt();rn();Xl();var Mm=900*1e3,eI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Cd=Zk(eI,16),Rd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>js.spawn(a)),this.store=s??new wd,this.tombstones=r.tombstones??new bd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Id({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new kd({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 Ii(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_${Cd()}`,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 $i({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=W.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=W.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await gn(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:xi,clientInfo:{name:"hydra",version:me}});o=m.agentCapabilities,i.authMethods=Zo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ws(m,i)}let a;try{let m=_m(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===W.AuthRequired)throw await i.kill().catch(()=>{}),Ws(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
293
+ `),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=Cu(a??{}),d=e.agentModes??Iu(Au(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 Ai({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 u=ku(a??{}),f=Iu(xu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ci({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new $i({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:f,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 Ai({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ci({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new $i({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 Fr.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:rt(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=W.AgentNotInstalled,p}let s=await gn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Td.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:xi,clientInfo:{name:"hydra",version:me}})}catch(p){throw await r.kill().catch(()=>{}),Ws(p,r)}if(r.authMethods=Zo(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=$.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(tI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!cm(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${qt}${Cd()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:Ko(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let x=lu(S);await this.store.write(x),u.push({version:1,...x})}return{synced:u,skipped:f}}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=W.AgentNotInstalled,i}let s=await gn(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:xi,clientInfo:{name:"hydra",version:me}}),o=i.agentCapabilities;r.authMethods=Zo(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=ku(a),l=xu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ei(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);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(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Au(a),p=Cu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ws(Fm(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=W.AgentNotInstalled,o}let r=await gn(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:xi,clientInfo:{name:"hydra",version:me}}),a=o.agentCapabilities;i.authMethods=Zo(o.authMethods);let c=_m(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=ku(d),u=Iu(xu(d)),f=Au(d),p=Cu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),Ws(Fm(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=W.AgentNotInstalled,c}let i=await gn(r,[],{npmRegistry:this.npmRegistry}),o=n??rt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:xi,clientInfo:{name:"hydra",version:me}});a.authMethods=Zo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ws(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=W.AgentNotInstalled,s}return gn(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=Bi({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:Lm(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=nI(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 sd(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:sI(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=Mi(r.update.prompt),o=nu(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(qt))return;let n=qt+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=W.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 ea(n.sessionId),c=Bi({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 ea(s.sessionId),i=Bi(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=>ea(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Bi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.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=>ea(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Bi(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return n.sort((l,u)=>l.updatedAt<u.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=Ko(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Om(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Cm(o)){let l=await ih(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=W.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=`${qt}${Cd()}`;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=W.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let x=new Error(`agent ${r} not found in registry`);throw x.code=W.AgentNotInstalled,x}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=tu(o,n.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw x.code=W.InvalidParams,x}c=n.forkAt,a=o.slice(0,S+1)}else{let S=iI(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 x=new Error(`agent ${r} not found in registry`);throw x.code=W.AgentNotInstalled,x}f=S,u=s.currentModel,l="running"}let h=await Om(e),m=d==="synthesis",y={...s,lineageId:Ko(),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}:{}},b=Xo({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:me,machine:Td.hostname()}),v=`${qt}${Cd()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await gn(f,[],{npmRegistry:this.npmRegistry}),x=await Sd({agentId:r,cwd:n.cwd??$.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});x&&x.synopsis?await this.mutateRecord(v,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:v,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 oh(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Fr.utimes($.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await _r($.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 ea(e),i=Bi(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)})}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 Jh(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<Mm),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Mm/1e3}s)`),await qo(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 qo(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 tI(t,e){if(typeof t!="string"||t.length===0)return!1;let n=ta.resolve(t),s=ta.resolve(e);return n===s||n.startsWith(s+ta.sep)}function nI(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return lu({sessionId:t.sessionId,lineageId:e?.lineageId??Ko(),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:Lm(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(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Lm(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 sI(t){return t?{...t}:void 0}function _m(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ed(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=rI(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function ku(t){return Ed(t,{nestedKey:"models",configId:"model",fromObject:e=>zn(e.currentModelId)??zn(e.currentModel)??zn(e.modelId)??zn(e.model),fromConfig:e=>zn(e.currentValue)})}function Ws(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==W.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=W.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function $m(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Fm(t,e,n,s){if(t&&typeof t=="object"&&t.code===W.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 ${$m(s.cwd)} && ${[s.command,...s.args].map($m).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(`
294
+ `));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 Zo(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 zn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function rI(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 Iu(t){return t.length>0?t:void 0}function xu(t){return Ed(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=_i(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=_i(e.options);return n.length>0?n:void 0}})??[]}function Au(t){return Ed(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=Wo(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=Wo(e.options);return n.length>0?n:void 0}})??[]}function Cu(t){return Ed(t,{nestedKey:"modes",configId:"mode",fromObject:e=>zn(e.currentModeId)??zn(e.currentMode)??zn(e.modeId)??zn(e.mode),fromConfig:e=>zn(e.currentValue)})}function iI(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 Om(t){try{let e=await Fr.readFile($.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
295
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function ea(t){try{let e=await Fr.stat($.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Bi(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Mr?!1:e?!0:void 0}import{spawn as oI}from"child_process";import*as Md from"fs";import*as bs from"fs/promises";import*as _d from"path";import aI from"pino-roll";var Pd=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_}};tt();var dI=1e3,cI=6e4,Ru=3e3,Ni=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??dI,this.restartCapMs=r.restartCapMs??cI;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 bs.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()},Ru);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 na(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw na(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 na(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 na(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw na(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{}},Ru);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 Pd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await bs.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 bs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Tu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ru;for(;Date.now()<i&&Tu(r);)await new Promise(o=>setTimeout(o,50));if(Tu(r))try{process.kill(r,"SIGKILL")}catch{}}await bs.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=_d.dirname(this.adapter.paths.logFile(r.name));await bs.mkdir(o,{recursive:!0});let a=await aI({file:_d.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}});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})
296
296
  `);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,...u]=i;if(l===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
297
- `),a.end();return}let f=rt(l),p=[...u,...r.args].map(rt),h;try{h=iI(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
297
+ `),a.end();return}let f=rt(l),p=[...u,...r.args].map(rt),h;try{h=oI(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
298
298
  `),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{Md.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
299
299
  `,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${y.message}
300
300
  `)}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}
301
301
  `)}),h.on("exit",(y,b)=>{try{Md.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${b??"null"}
302
302
  `),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 v=e.exitWaiters.splice(0);for(let x of v)x();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}
303
- `);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)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Tu(t){try{return process.kill(t,0),!0}catch{return!1}}function na(t,e){return t.code=e,t}ye();var cI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:$.extensionsDir,logFile:$.extensionLogFile,pidFile:$.extensionPidFile}},$d=class extends Ni{constructor(e,n,s={}){super(e,cI,n,s)}};ye();var lI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:$.transformersDir,logFile:$.transformerLogFile,pidFile:$.transformerPidFile}},Fd=class extends Ni{connected=new Map;constructor(e,n,s={}){super(e,lI,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Od=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{}}};ye();bi();ye();import*as ra from"fs/promises";import*as Ld from"path";var sa=t=>{process.stderr.write(t+`
303
+ `);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)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Tu(t){try{return process.kill(t,0),!0}catch{return!1}}function na(t,e){return t.code=e,t}ye();var lI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:$.extensionsDir,logFile:$.extensionLogFile,pidFile:$.extensionPidFile}},$d=class extends Ni{constructor(e,n,s={}){super(e,lI,n,s)}};ye();var uI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:$.transformersDir,logFile:$.transformerLogFile,pidFile:$.transformerPidFile}},Fd=class extends Ni{connected=new Map;constructor(e,n,s={}){super(e,uI,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Od=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{}}};ye();bi();ye();import*as ra from"fs/promises";import*as Ld from"path";var sa=t=>{process.stderr.write(t+`
304
304
  `)};function Eu(t){sa=t??(e=>process.stderr.write(e+`
305
- `))}async function Bm(t,e){let n=Hn();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=Ld.join($.agentsDir(),n),a;try{a=await ra.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;sa(`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 u=i.get(d)??new Set,f=Ld.join(o,d),p;try{p=await ra.readdir(f,{withFileTypes:!0})}catch(h){sa(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Ld.join(f,m);try{await ra.rm(y,{recursive:!0,force:!0}),sa(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){sa(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function Nm(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 u of l.agents)await Hl(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}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 Pu(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 u=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 ${uI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function Dm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Pu({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 uI(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`}sn();ia();ye();Ir();import*as jm from"path";import{createHash as pI,randomBytes as hI,timingSafeEqual as mI}from"crypto";var qm="hydra_session_",gI=3600*24*30,Hm=12,yI=32,wI=50;function bI(){return jm.join($.home(),"session-tokens.json")}function Um(t){return pI("sha256").update(t).digest("hex")}function Wm(t){return hI(t).toString("hex")}function vI(){return Wm(Hm).slice(0,Hm*2)}function SI(){return`${qm}${Wm(yI)}`}var Bd=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=bI(),s=await hn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(kI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=SI(),s=Um(n),r=vI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:gI,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(qm))return;let n=Um(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||!mI(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(()=>{})},wI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Zt(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 kI(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")}ms();var zm="Bearer ",Nd=class{constructor(e){this.token=e}token;async validate(e){return II(e,this.token)?"service":void 0}},Dd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Hd=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 Km(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(zm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Jm(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 Ud=class{tokens=new Map;mint(e,n){let s=mi();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 II(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 jd=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)}};ye();tt();$u();$r();zd();import*as Bu from"fs";import*as da from"os";import*as fg from"path";import*as Nu from"readline";Ks();qn();function Kd(t){let e=GI(t),n=XI(e),s=[];ZI(s,t),ex(s,e,n);let r=s.join(`
305
+ `))}async function Bm(t,e){let n=Hn();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=Ld.join($.agentsDir(),n),a;try{a=await ra.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;sa(`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 u=i.get(d)??new Set,f=Ld.join(o,d),p;try{p=await ra.readdir(f,{withFileTypes:!0})}catch(h){sa(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Ld.join(f,m);try{await ra.rm(y,{recursive:!0,force:!0}),sa(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){sa(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function Nm(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 u of l.agents)await Hl(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}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 Pu(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 u=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 ${fI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function Dm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Pu({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 fI(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`}rn();ia();ye();Ir();import*as jm from"path";import{createHash as hI,randomBytes as mI,timingSafeEqual as gI}from"crypto";var qm="hydra_session_",yI=3600*24*30,Hm=12,wI=32,bI=50;function vI(){return jm.join($.home(),"session-tokens.json")}function Um(t){return hI("sha256").update(t).digest("hex")}function Wm(t){return mI(t).toString("hex")}function SI(){return Wm(Hm).slice(0,Hm*2)}function kI(){return`${qm}${Wm(wI)}`}var Bd=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=vI(),s=await mn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(II));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=kI(),s=Um(n),r=SI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:yI,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(qm))return;let n=Um(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(()=>{})},bI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>en(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 II(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")}ms();var zm="Bearer ",Nd=class{constructor(e){this.token=e}token;async validate(e){return xI(e,this.token)?"service":void 0}},Dd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Hd=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 Km(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(zm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Jm(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 Ud=class{tokens=new Map;mint(e,n){let s=mi();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 xI(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 jd=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)}};ye();tt();$u();$r();zd();import*as Bu from"fs";import*as da from"os";import*as fg from"path";import*as Nu from"readline";Ks();qn();function Kd(t){let e=XI(t),n=ZI(e),s=[];ex(s,t),tx(s,e,n);let r=s.join(`
306
306
  `);return r.endsWith(`
307
307
  `)||(r+=`
308
- `),r}function GI(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=Kn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function XI(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 ZI(t,e){let n=e.session,s=lt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Or(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?`${Ou(a.size)}`:void 0;c.push(d?`${Ou(a.used)} / ${d} tokens`:`${Ou(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(`
309
- `)),t.push("")}function ex(t,e,n){if(!e.some(d=>tx(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
308
+ `),r}function XI(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=Kn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function ZI(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 ex(t,e){let n=e.session,s=lt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Or(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?`${Ou(a.size)}`:void 0;c.push(d?`${Ou(a.used)} / ${d} tokens`:`${Ou(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(`
309
+ `)),t.push("")}function tx(t,e,n){if(!e.some(d=>nx(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
310
310
  `))t.push(`> ${Or(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":c(),i+=d.text;break;case"agent-thought":{c(),a();let l=d.text.split(`
311
- `);for(let u of l)t.push(`> _${Or(u)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${sx(l.status)} ${nx(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${Or(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Or(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Or(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function tx(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`${Or(t.title)}${n}`}function sx(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 Or(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ou(t){return t.toLocaleString("en-US")}Bt();sn();Lo();Ks();function rx(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 u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>ix(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function ix(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:rg(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:rg(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function rg(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function ox(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var ax=5,dx=200,ig=30;async function dg(t,e,n={}){let s=rx(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??ax,i=n.maxSessions??dx,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=cx(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function cx(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=lx(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 lx(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=ux(a).filter(d=>ox(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:gx(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 ux(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=Jd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ht(s.text):Jd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(hx(s))return[];let i=Jd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=mx(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return fx(s);default:return[]}}function fx(t){let e=og(t,"name"),n=og(t,"title"),s=[];if(n!==void 0){let a=Te(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=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=ag(r);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=ag(i);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=px(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function px(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=Te(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=Te(s);if(r.length>0)return r}}return null}function hx(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 Jd(t){if(typeof t=="string")return ht(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?ht(e.text):""}function mx(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Jd(n);s.length>0&&e.push(s)}return e.join("")}function og(t,e){let n=t[e];return typeof n=="string"?n:void 0}function ag(t){try{return JSON.stringify(t)}catch{return""}}function gx(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-ig),c=Math.min(s.length,o+i.length+ig),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as lg}from"crypto";function cg(t){let e=lg(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 Lu(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(cg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(cg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Ui(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Ui(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=lg(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 Yd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ug(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!xr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function pg(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),t.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await dg(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=rt(u.cwd??n.cwd),p=u.agentId??n.agentId,h=Ui(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,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 u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await Pu({manager:e,maxAgeMs:f,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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);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=>fg.join(da.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);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(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),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(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":Im(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=Xo({record:m.record,history:h==="summary"?xm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:me,machine:da.hostname(),hydraHost:ug(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);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(v=>v.trim()).filter(v=>v.length>0)):void 0,b=Di(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:Hi(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=Xo({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:me,machine:da.hostname(),hydraHost:ug(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Kd(h))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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=rt(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(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===W.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===W.InvalidParams||y.code===W.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 u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=Cn(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===W.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&n.compaction){let T=h??0,F=x.length,N=x.slice(T).reduce((D,X)=>D+JSON.stringify(X.params).length,0);v=_u(N);let J=p?.currentModel,q=x.at(-1).recordedAt,L=p?.currentUsage;b=Ym({summarizedThroughEntry:T,totalEntries:F,unsummarizedChars:N,compactionInFlight:e.getCompactionInFlight(),currentModel:J,lastActivityMs:q,nowMs:Date.now(),config:n.compaction,...typeof L?.used=="number"?{agentReportedUsed:L.used}:{},...typeof L?.size=="number"?{agentReportedSize:L.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),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 u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,x=[];if(m){p&&(b=m.onBroadcast(F=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(F)+`
311
+ `);for(let u of l)t.push(`> _${Or(u)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${rx(l.status)} ${sx(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${Or(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Or(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Or(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function nx(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function sx(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Or(t.title)}${n}`}function rx(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 Or(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ou(t){return t.toLocaleString("en-US")}Bt();rn();Lo();Ks();function ix(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 u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>ox(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function ox(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:rg(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:rg(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function rg(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function ax(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var dx=5,cx=200,ig=30;async function dg(t,e,n={}){let s=ix(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??dx,i=n.maxSessions??cx,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=lx(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function lx(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=ux(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 ux(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=fx(a).filter(d=>ax(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:yx(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 fx(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=Jd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ht(s.text):Jd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(mx(s))return[];let i=Jd(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 px(s);default:return[]}}function px(t){let e=og(t,"name"),n=og(t,"title"),s=[];if(n!==void 0){let a=Te(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=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=ag(r);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=ag(i);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=hx(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function hx(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=Te(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=Te(s);if(r.length>0)return r}}return null}function mx(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 Jd(t){if(typeof t=="string")return ht(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?ht(e.text):""}function gx(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Jd(n);s.length>0&&e.push(s)}return e.join("")}function og(t,e){let n=t[e];return typeof n=="string"?n:void 0}function ag(t){try{return JSON.stringify(t)}catch{return""}}function yx(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-ig),c=Math.min(s.length,o+i.length+ig),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as lg}from"crypto";function cg(t){let e=lg(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 Lu(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(cg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(cg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Ui(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Ui(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=lg(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 Yd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ug(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!xr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function pg(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),t.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await dg(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=rt(u.cwd??n.cwd),p=u.agentId??n.agentId,h=Ui(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,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 u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await Pu({manager:e,maxAgeMs:f,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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);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=>fg.join(da.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);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(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),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(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":Im(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=Xo({record:m.record,history:h==="summary"?xm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:me,machine:da.hostname(),hydraHost:ug(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);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(v=>v.trim()).filter(v=>v.length>0)):void 0,b=Di(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:Hi(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=Xo({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:me,machine:da.hostname(),hydraHost:ug(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Kd(h))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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=rt(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(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===W.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===W.InvalidParams||y.code===W.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 u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=Cn(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===W.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 u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&n.compaction){let T=h??0,F=x.length,N=x.slice(T).reduce((D,X)=>D+JSON.stringify(X.params).length,0);v=_u(N);let J=p?.currentModel,q=x.at(-1).recordedAt,L=p?.currentUsage;b=Ym({summarizedThroughEntry:T,totalEntries:F,unsummarizedChars:N,compactionInFlight:e.getCompactionInFlight(),currentModel:J,lastActivityMs:q,nowMs:Date.now(),config:n.compaction,...typeof L?.used=="number"?{agentReportedUsed:L.used}:{},...typeof L?.size=="number"?{agentReportedSize:L.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),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 u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,x=[];if(m){p&&(b=m.onBroadcast(F=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(F)+`
312
312
  `):(x.push(F),x.length>S&&x.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(F){throw b?.(),F}}else{let F=await e.getHistory(h);if(F===void 0)return l.code(404).send({error:"session not found"}),l;y=F}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let F of y??[]){l.raw.write(JSON.stringify(F)+`
313
313
  `);let _=F;typeof _.recordedAt=="number"&&T.add(String(_.recordedAt))}for(;x.length>0;){let F=x.splice(0,x.length);for(let _ of F){let N=_,J=typeof N.recordedAt=="number"?String(N.recordedAt):"";J&&T.has(J)||l.raw.write(JSON.stringify(_)+`
314
314
  `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}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"||u!==void 0&&h.recordedAt<u||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 b=m.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=Nu.createInterface({input:Bu.createReadStream(l),crlfDelay:1/0}),h=o(d,p,u,f),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 u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.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(!Yd.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...Yd].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.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}),b=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 v=[];for(let S of b)try{let x=$.historyFile(S.sessionId),T=await a(S.sessionId,x,h,m);T.exhausted||v.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,x=1/0;for(let F=0;F<v.length;F++){let _=v[F];_.current!==null&&_.current.ts<x&&(x=_.current.ts,S=F)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
315
315
  `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let x of v)try{x.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=f.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(F=>F.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let F of y)if(!Yd.has(F))return l.code(400).send({error:`kind "${F}" is not queryable; allowed kinds: ${[...Yd].join(", ")}`}),l;let b=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let F=new Date(f.since);if(isNaN(F.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=F.getTime()}let S=$.historyFile(p),x=Bu.createReadStream(S),T=Nu.createInterface({input:x,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let F of T){let _=typeof F=="string"?F.trim():"";if(_.length===0)continue;let N;try{N=JSON.parse(_)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!N||typeof N!="object"||Array.isArray(N)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let J=N;if(typeof J.recordedAt!="number"||typeof J.params!="object"||J.params===null||Array.isArray(J.params))continue;let q=J.params;if(typeof q.update!="object"||q.update===null||Array.isArray(q.update))continue;let L=q.update,D=L.sessionUpdate;if(typeof D!="string"||!b.has(D)||v!==void 0&&J.recordedAt<v)continue;let X={ts:new Date(J.recordedAt).toISOString(),kind:D,update:L};L.messageId!==void 0&&L.messageId!==null&&(X.messageId=L.messageId),l.raw.write(JSON.stringify(X)+`
316
- `)}}catch(F){if(F.code==="ENOENT")return l.raw.end(),l;throw F}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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 b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let F=Array.from(b.listAttentionFlags()).map(_=>`${_.source}::${_.reason}`);for(let _ of F)b.clearAttentionFlag(_.split("::")[0],_.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let F=`${m}::${y}`;T=x.filter(_=>`${_.source}::${_.reason}`!==F)}else T=[];if(T.length===x.length&&T.every((F,_)=>F.source===x[_].source&&F.reason===x[_].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Bt();function hg(t,e,n,s={}){t.get("/v1/agents",async()=>Ii(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 mn(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===W.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function mg(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var yx=/^[A-Za-z0-9._-]+$/;function Vd(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=wx(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){ca(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){ca(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){ca(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){ca(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){ca(o,c)}})}function ca(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 wx(t){let e=t.name;if(typeof e!="string"||!yx.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 gg(t,e){Vd(t,"extension",e)}function yg(t,e){Vd(t,"transformer",e)}function wg(t,e){t.get("/v1/config",async()=>e)}import{z as ji}from"zod";ye();import*as Js from"fs/promises";import*as kg from"path";import{randomBytes as bx,scrypt as vx,timingSafeEqual as Sx}from"crypto";import{promisify as kx}from"util";var Ig=kx(vx);function Du(){return kg.join($.home(),"password-hash")}var bg=32768,vg=8,Sg=1,Ix=64,xx=16,xg=128*1024*1024;async function Ag(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=bx(xx),n=await Ig(t,e,Ix,{N:bg,r:vg,p:Sg,maxmem:xg}),s=`scrypt$${bg}$${vg}$${Sg}$${e.toString("hex")}$${n.toString("hex")}
317
- `;await Js.mkdir($.home(),{recursive:!0}),await Js.writeFile(Du(),s,{encoding:"utf8",mode:384})}async function Qd(){try{return(await Js.readFile(Du(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Js.readFile(Du(),"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 Ig(t,o,a.length,{N:s,r,p:i,maxmem:xg});return c.length!==a.length?!1:Sx(c,a)}var Ax=ji.object({password:ji.string().min(1),label:ji.string().min(1).max(256).optional(),ttlSec:ji.number().int().positive().optional()}),Cx=ji.object({id:ji.string().optional()}).optional();function Cg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=Rx(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ax.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Qd())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Gd(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=Cx.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 Rx(t){return t.ip||"unknown"}Pr();qi();import{nanoid as Hu}from"nanoid";hd();Bt();sn();import{randomBytes as Tg}from"crypto";import*as Eg from"os";import*as Pg from"path";function ce(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function _x(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 rn(t,e,n){let s=t.get(e);if(!s)throw ce(W.SessionNotFound,n??`session ${e} not found`);return s}async function Xd(t,e){let n=Ui(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Tg(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=Lu({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,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return Hx(d,t),d}function Mg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Jm({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=Jn(n),a=new Kt(o),c={clientId:`hydra_client_${Hu(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw ce(W.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=bh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),Dx()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},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 b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},h=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,h,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let h=e.transformers.resolveChain([i.name])[0];if(h)for(let m of e.manager.liveSessions())m.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!p)throw ce(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw ce(-32602,"emit_message requires method");let b=rn(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,m),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="queue"){if(h!=="session/prompt")throw ce(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,m)}}if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw ce(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(m),{ok:!0}}throw ce(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(-32602,"hydra-acp/session/request_permission requires sessionId");return rn(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Ox(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!h&&m){let F=e.manager.get(m);F&&(h=F.cwd)}if(!h)throw ce(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:h,parentSessionId:m,interactive:x,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw ce(W.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0,y=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0,b=typeof f.model=="string"&&f.model.length>0?f.model:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...h!==void 0?{cwd:h}:{},...m!==void 0?{agentId:m}:{},...y!==void 0?{mode:y}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw ce(W.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=e.manager.get(p);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(p),await e.manager.hasRecord(p)&&await e.manager.deleteRecord(p),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw ce(W.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,h=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw ce(-32602,"await_child requires childSessionId");let y=rn(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],F=0,_=!1,N,J,q=!1,L=()=>{q||(q=!0,clearTimeout(D),N?.(),J?.(),b(_?{entries:x,truncated:!0}:{entries:x}))};N=y.onBroadcast(X=>{let ee=_x(X);for(x.push(X),T.push(ee),F+=ee;x.length>0&&(x.length>1e3||F>1048576);)x.shift(),F-=T.shift()??0,_=!0;h==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&L()});let D=setTimeout(L,m);typeof D.unref=="function"&&D.unref(),J=y.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw ce(-32602,"close_child_session requires childSessionId");let h=e.manager.get(p);return h&&await h.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>Lx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>Bx(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,h=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&h&&e.manager.get(h)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw ce(W.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw ce(W.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>$x(u,e)),a.onRequest("session/new",async u=>{let f=vh.parse(u),p=tn(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(D=>typeof D=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Tg(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let X={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],X]}let S,x,T=Ui(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let F=Lu({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),_;try{_=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Rg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...F?{mintMcpServersForSwap:F}:{}})}catch(D){throw b!==void 0&&b.abandon(D instanceof Error?D:void 0),x!==void 0&&x.abandon(D instanceof Error?D:void 0),T!==void 0&&T.abandon(D instanceof Error?D:void 0),D}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let D=y,X=e.mcpTokenRegistry;b.complete(_),_.onClose(()=>{X.unbind(D)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let D=S,X=e.mcpTokenRegistry;x.complete(_),_.onClose(()=>{X.unbind(D)})}T!==void 0&&T.bindToSession(_);let N,J;try{N=la(a,_,c),{entries:J}=await _.attach(N,"full")}catch(D){throw await _.close({deleteRecord:!1}).catch(()=>{}),D}c.attached.set(_.sessionId,{sessionId:_.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let D of J){if(a.isClosed())break;await a.notify(D.method,D.params).catch(()=>{})}})()});let q=Zd(_),L=ec(_);return{sessionId:_.sessionId,...q?{modes:q}:{},...L?{models:L}:{},configOptions:_.buildConfigOptions(),_meta:tc(e.manager,_,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=kh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=tn(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw ce(W.SessionNotFound,`session ${f.sessionId} not found`);let D=await e.manager.loadHistory(v),X=f.clientId??`cli_${Hu(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:X,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${X} attachedCount=${c.attached.size} replayed=${D.length}`);for(let ee of D)await a.notify(ee.method,ee.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:X,connectedClients:[X],historyPolicy:"full",replayed:D.length,_meta:Nx(L)}}let x=!S;if(!S){let L=await e.manager.loadFromDisk(v),D=L;if(m&&(D={...L,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!D)throw ce(W.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(D.agentId,D.upstreamSessionId))throw ce(W.SessionNotFound,`session ${f.sessionId} was deleted`);let X=D.originatingClient?D:{...D,originatingClient:c.clientInfo},ee=b!==void 0?{...X,forwardedEnv:b}:X;S=await Xd(e,{...ee,onInstallProgress:Rg(a)})}let T=la(a,S,c,f.clientInfo,f.clientId),F=h.replayMode==="drip",{entries:_,appliedPolicy:N}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:F,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${N} replayed=${_.length} readonly=${y}${F?" replayMode=drip":""}`),F){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,D=750;(async()=>{let X=null;for(let ee of _){let ae=typeof ee.recordedAt=="number"?ee.recordedAt:null;if(X!==null&&ae!==null){let G=Math.min(D,Math.max(0,(ae-X)/L));G>0&&await new Promise(fe=>setTimeout(fe,G))}ae!==null&&(X=ae);try{await a.notify(ee.method,ee.params)}catch{return}}})()}else for(let L=0;L<_.length&&!a.isClosed();L++){let D=_[L],X=a.notify(D.method,D.params).catch(()=>{});(L+1)%200===0&&await X}S.replayPendingPermissions(T);let J=Zd(S),q=ec(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:N,replayed:_.length,...J?{modes:J}:{},...q?{models:q}:{},configOptions:S.buildConfigOptions(),_meta:tc(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=Ih.parse(u),p=c.attached.get(f.sessionId);if(!p)throw ce(W.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Lt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=xh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Mr).map(Ah)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw ce(W.InternalError,"agent registry unavailable");return Ii(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw ce(W.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=Ch.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),ce(W.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw ce(W.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Xd(e,m);let y=la(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=cd.parse(u)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=cd.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Th.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),rn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=cd.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),rn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Eh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),rn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Ph.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw ce(W.SessionNotFound,"not attached to session");return rn(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(W.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 ce(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Xd(e,S)}let y=la(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 b=Zd(m),v=ec(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:tc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(W.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let x=await e.manager.loadFromDisk(h);if(!x)throw ce(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Xd(e,x)}let y=la(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let v=Zd(m),S=ec(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:tc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=Fx(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),ce(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",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw ce(W.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw ce(W.InvalidParams,"session/set_mode requires string modeId");let h=rn(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>ce(W.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=rn(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw ce(W.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw ce(W.MethodNotFound,`Method not found: ${f}`);return d(y,f),rn(e.manager,y).forwardRequest(f,u)})})}async function $x(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw ce(W.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 ce(W.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,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,x)=>{if(!Array.isArray(S))throw ce(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw ce(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Pg.isAbsolute(S)?S:h.command,y=p(u.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,x=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...x]}let b={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(b[S]=x);Object.assign(b,h.env);let v=Eg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Ws(p,a)}}function Rg(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(ld,n).catch(()=>{})}}function Zd(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 ec(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 Fx(t,e){if(!t||typeof t!="object")return{kind:"error",code:W.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:W.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:W.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:W.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Ei(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:W.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 Ox(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw ce(W.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw ce(W.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw ce(W.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return rn(n.manager,r).addTransformer(i),{ok:!0}}async function Lx(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 ce(W.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw ce(W.InvalidParams,"hydra-acp/attention/set requires string reason");return rn(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function Bx(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 ce(W.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw ce(W.InvalidParams,"hydra-acp/attention/clear requires string reason");return rn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function Nx(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{[Lt]:ad(e,n)}}function tc(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 Uo(e.agentMeta,ad(s,r))}function Dx(){return{protocolVersion:1,agentInfo:{name:"hydra",version:me},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{},resume:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Uo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Hx(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 la(t,e,n,s,r){return{clientId:r??`cli_${Hu(8)}`,connection:t,clientInfo:s}}var nc=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 Ux}from"crypto";import{McpServer as jx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as qx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Nt}from"zod";function*Uu(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 on(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var _g="Bearer ";function Wi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(_g))return;let n=e.slice(_g.length).trim();return n.length>0?n:void 0}function Wx(t){let e=new jx({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:Nt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return on(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:Nt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return on(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:Nt.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:Nt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Nt.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 on(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:Nt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Nt.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 on({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:Nt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Nt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Nt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Nt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Nt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Nt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Nt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Nt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Nt.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 on(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 on(n)}),e}var zx=1e4;function $g(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=Wx(a),l=new qx({sessionIdGenerator:()=>Ux()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),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=Wi(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 f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),zx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}md();import{randomUUID as Kx}from"crypto";import{McpServer as Jx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Yx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ys}from"zod";function Vx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Qx(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 Gx(t){let e=new Jx({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:Ys.string().min(1).describe("Case-insensitive substring to search for."),limit:Ys.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ys.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 on({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:u}of Uu(o)){if(u==="tool_call"&&!r)continue;let f=Pi([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=Vx(u),m=Qx(f,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 on({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:Ys.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ys.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 on({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),u=Pi(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,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:Ys.string().optional(),file_path:Ys.string().optional(),limit:Ys.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 on({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 Uu(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))v.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];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(),b=["file_path","filePath","path"],v=!1;for(let S of b){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return on({calls:u,truncated:f})}),e}var Xx=1e4;function Fg(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=Gx(a),l=new Yx({sessionIdGenerator:()=>Kx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),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=Wi(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 u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Xx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.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 oA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as aA}from"crypto";import{Server as Zx}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as eA,ListToolsRequestSchema as tA}from"@modelcontextprotocol/sdk/types.js";function Og(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new Zx({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(tA,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(eA,async(o,a)=>{let c=o.params.name;if(!i.has(c))return rc(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=sA(d,a.sendNotification);try{let u=await s(),f=await rA(e.connection,t,c,o.params.arguments??{},u);return iA(f,c)}catch(u){return rc(u instanceof Error?u.message:String(u))}finally{l()}}),r}var nA=15e3;function sA(t,e,n=nA){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 rA(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function iA(t,e){if(t===null||typeof t!="object")return rc(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:rc(`extension ${e} omitted content array`)}function rc(t){return{content:[{type:"text",text:t}],isError:!0}}var dA=1e4;function Lg(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=Og(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),dA)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId}),y=new oA({sessionIdGenerator:()=>aA()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Wi(d);if(u===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,h=await o(u,p);if(h===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await h.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function Ug(t,e){hA(t);let n=t.daemon.tls?await zi.readFile(rt(t.daemon.tls.key)):void 0,s=t.daemon.tls?await zi.readFile(rt(t.daemon.tls.cert)):void 0;await zi.mkdir($.home(),{recursive:!0});let{stream:r,fileStream:i}=await fA(t.daemon.logLevel),o=cA({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(lA,{options:{handleProtocols:eh}}),Ol(Y=>{o.log.info(Y)}),Nl(Y=>{o.log.info(Y)});let a=await Bd.load(),c=new jd,d=new Ud,l=new Hd([new Nd(e),new Dd(a),d]),u=Km({validator:l});o.addHook("onRequest",async(Y,Se)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await u(Y,Se)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new rd(t,{onFetched:()=>{Bm(h,v)}});Eu(Y=>o.log.info(Y));let m={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},y=Y=>js.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});rh(t.compressToolContent);let b=new Od,v=new Rd(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,logger:m,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new $d(Cp(t),void 0,{tokenRegistry:d}),x=new Fd(Rp(t),void 0,{tokenRegistry:d});mg(o,me,zs(t));let T=new nc,F=new sc,_,N=()=>{if(_!==void 0)return _;let Y=o.server.address();return _=`http://127.0.0.1:${Y&&typeof Y=="object"?Y.port:t.daemon.port}`,_};pg(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:F,mcpTokenRegistry:T,getDaemonOrigin:N}),hg(o,h,v,{npmRegistry:t.npmRegistry}),gg(o,S),yg(o,x),wg(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]}),Cg(o,{store:a,rateLimiter:c}),$g(o,T),Fg(o,T),Lg(o,T,F),Mg(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,Se)=>S.reportVersion(Y,Se),onTransformerVersion:(Y,Se)=>x.reportVersion(Y,Se),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:F,getDaemonOrigin:N,registry:h});let J=!!t.daemon.tls;await o.listen({host:J?"127.0.0.1":t.daemon.host,port:J?0:t.daemon.port});let q=o.server.address(),L=q&&typeof q=="object"?q.port:t.daemon.port,D,X=t.daemon.host,ee=L;if(J&&n&&s){D=pA({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let Y=D.address();Y&&typeof Y=="object"&&(ee=Y.port)}await zi.mkdir($.home(),{recursive:!0}),await Op({pid:process.pid,host:X,port:ee,loopbackPort:L,startedAt:new Date().toISOString()});let ae={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:$.home()};S.setContext(ae),x.setContext(ae),await S.start(),await x.start();try{await v.reconcilePermissionFlags()}catch(Y){o.log.warn(`permission flag reconcile failed: ${Y.message}`)}v.resurrectPendingQueues().catch(Y=>{o.log.warn(`queue replay scan failed: ${Y.message}`)}),v.resumePendingCompactions().catch(Y=>{o.log.warn(`compaction resume scan failed: ${Y.message}`)}),v.resumePendingAgentSwaps().catch(Y=>{o.log.warn(`agent-swap resume scan failed: ${Y.message}`)});let G=t.daemon.agentSyncIntervalMinutes*60*1e3,fe=G>0?Nm({registry:h,manager:v,intervalMs:G,logger:m}):void 0,Ve=t.daemon.sessionGcIntervalMinutes*60*1e3,Be=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ns=Ve>0?Dm({manager:v,intervalMs:Ve,maxAgeMs:Be,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:F,processRegistry:d,shutdown:async()=>{ns&&ns(),fe&&fe(),clearInterval(f),clearInterval(p);let Y=async(Se,De)=>{try{await De()}catch(Yt){o.log.warn(`shutdown step ${Se} failed: ${Yt instanceof Error?Yt.message:String(Yt)}`)}};await Y("sessionTokenStore.flush",()=>a.flush()),await Y("extensions.stop",()=>S.stop()),await Y("transformers.stop",()=>x.stop()),await Y("manager.closeAll",()=>v.closeAll()),await Y("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await Y("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await Y("manager.flushMetaWrites",()=>v.flushMetaWrites()),await Y("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Ol(null),Nl(null),Eu(null),D&&await Y("tlsTerminator.close",()=>new Promise(Se=>D.close(()=>Se()))),await Y("app.close",()=>o.close());try{Ng.unlinkSync($.pidFile())}catch{}await Y("fileStream.flushSync",()=>i.flushSync())}}}async function fA(t){let e=await uA({file:$.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=Bg.destination(2);return{stream:Bg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function pA(t){let e=Hg.createServer(t.tlsOptions,n=>{let s=Dg.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 hA(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.`)}Br();sn();ia();ua();async function zg(t={}){let e=await Ie(),n=await Fo();if(await ic(e)){let r=await Yi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
316
+ `)}}catch(F){if(F.code==="ENOENT")return l.raw.end(),l;throw F}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,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 b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let F=Array.from(b.listAttentionFlags()).map(_=>`${_.source}::${_.reason}`);for(let _ of F)b.clearAttentionFlag(_.split("::")[0],_.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let F=`${m}::${y}`;T=x.filter(_=>`${_.source}::${_.reason}`!==F)}else T=[];if(T.length===x.length&&T.every((F,_)=>F.source===x[_].source&&F.reason===x[_].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Bt();function hg(t,e,n,s={}){t.get("/v1/agents",async()=>Ii(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 gn(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===W.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function mg(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var wx=/^[A-Za-z0-9._-]+$/;function Vd(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=bx(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){ca(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){ca(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){ca(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){ca(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){ca(o,c)}})}function ca(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 bx(t){let e=t.name;if(typeof e!="string"||!wx.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 gg(t,e){Vd(t,"extension",e)}function yg(t,e){Vd(t,"transformer",e)}function wg(t,e){t.get("/v1/config",async()=>e)}import{z as ji}from"zod";ye();import*as Js from"fs/promises";import*as kg from"path";import{randomBytes as vx,scrypt as Sx,timingSafeEqual as kx}from"crypto";import{promisify as Ix}from"util";var Ig=Ix(Sx);function Du(){return kg.join($.home(),"password-hash")}var bg=32768,vg=8,Sg=1,xx=64,Ax=16,xg=128*1024*1024;async function Ag(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=vx(Ax),n=await Ig(t,e,xx,{N:bg,r:vg,p:Sg,maxmem:xg}),s=`scrypt$${bg}$${vg}$${Sg}$${e.toString("hex")}$${n.toString("hex")}
317
+ `;await Js.mkdir($.home(),{recursive:!0}),await Js.writeFile(Du(),s,{encoding:"utf8",mode:384})}async function Qd(){try{return(await Js.readFile(Du(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Js.readFile(Du(),"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 Ig(t,o,a.length,{N:s,r,p:i,maxmem:xg});return c.length!==a.length?!1:kx(c,a)}var Cx=ji.object({password:ji.string().min(1),label:ji.string().min(1).max(256).optional(),ttlSec:ji.number().int().positive().optional()}),Rx=ji.object({id:ji.string().optional()}).optional();function Cg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=Tx(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Cx.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Qd())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Gd(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=Rx.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 Tx(t){return t.ip||"unknown"}Pr();qi();import{nanoid as Hu}from"nanoid";hd();Bt();rn();import{randomBytes as Tg}from"crypto";import*as Eg from"os";import*as Pg from"path";function ce(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function $x(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 on(t,e,n){let s=t.get(e);if(!s)throw ce(W.SessionNotFound,n??`session ${e} not found`);return s}async function Xd(t,e){let n=Ui(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Tg(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=Lu({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,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return Ux(d,t),d}function Mg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Jm({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=Jn(n),a=new Jt(o),c={clientId:`hydra_client_${Hu(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw ce(W.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=bh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),Hx()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},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 b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},h=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,h,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let h=e.transformers.resolveChain([i.name])[0];if(h)for(let m of e.manager.liveSessions())m.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!p)throw ce(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw ce(-32602,"emit_message requires method");let b=on(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,m),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="queue"){if(h!=="session/prompt")throw ce(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,m)}}if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw ce(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(m),{ok:!0}}throw ce(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(-32602,"hydra-acp/session/request_permission requires sessionId");return on(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Lx(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!h&&m){let F=e.manager.get(m);F&&(h=F.cwd)}if(!h)throw ce(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:h,parentSessionId:m,interactive:x,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw ce(W.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0,y=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0,b=typeof f.model=="string"&&f.model.length>0?f.model:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...h!==void 0?{cwd:h}:{},...m!==void 0?{agentId:m}:{},...y!==void 0?{mode:y}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw ce(W.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=e.manager.get(p);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(p),await e.manager.hasRecord(p)&&await e.manager.deleteRecord(p),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw ce(W.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,h=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw ce(-32602,"await_child requires childSessionId");let y=on(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],F=0,_=!1,N,J,q=!1,L=()=>{q||(q=!0,clearTimeout(D),N?.(),J?.(),b(_?{entries:x,truncated:!0}:{entries:x}))};N=y.onBroadcast(X=>{let ee=$x(X);for(x.push(X),T.push(ee),F+=ee;x.length>0&&(x.length>1e3||F>1048576);)x.shift(),F-=T.shift()??0,_=!0;h==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&L()});let D=setTimeout(L,m);typeof D.unref=="function"&&D.unref(),J=y.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw ce(-32602,"close_child_session requires childSessionId");let h=e.manager.get(p);return h&&await h.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>Bx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>Nx(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,h=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&h&&e.manager.get(h)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw ce(W.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw ce(W.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>Fx(u,e)),a.onRequest("session/new",async u=>{let f=vh.parse(u),p=nn(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(D=>typeof D=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Tg(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let X={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],X]}let S,x,T=Ui(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let F=Lu({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),_;try{_=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Rg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...F?{mintMcpServersForSwap:F}:{}})}catch(D){throw b!==void 0&&b.abandon(D instanceof Error?D:void 0),x!==void 0&&x.abandon(D instanceof Error?D:void 0),T!==void 0&&T.abandon(D instanceof Error?D:void 0),D}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let D=y,X=e.mcpTokenRegistry;b.complete(_),_.onClose(()=>{X.unbind(D)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let D=S,X=e.mcpTokenRegistry;x.complete(_),_.onClose(()=>{X.unbind(D)})}T!==void 0&&T.bindToSession(_);let N,J;try{N=la(a,_,c),{entries:J}=await _.attach(N,"full")}catch(D){throw await _.close({deleteRecord:!1}).catch(()=>{}),D}c.attached.set(_.sessionId,{sessionId:_.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let D of J){if(a.isClosed())break;await a.notify(D.method,D.params).catch(()=>{})}})()});let q=Zd(_),L=ec(_);return{sessionId:_.sessionId,...q?{modes:q}:{},...L?{models:L}:{},configOptions:_.buildConfigOptions(),_meta:tc(e.manager,_,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=kh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=nn(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw ce(W.SessionNotFound,`session ${f.sessionId} not found`);let D=await e.manager.loadHistory(v),X=f.clientId??`cli_${Hu(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:X,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${X} attachedCount=${c.attached.size} replayed=${D.length}`);for(let ee of D)await a.notify(ee.method,ee.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:X,connectedClients:[X],historyPolicy:"full",replayed:D.length,_meta:Dx(L)}}let x=!S;if(!S){let L=await e.manager.loadFromDisk(v),D=L;if(m&&(D={...L,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!D)throw ce(W.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(D.agentId,D.upstreamSessionId))throw ce(W.SessionNotFound,`session ${f.sessionId} was deleted`);let X=D.originatingClient?D:{...D,originatingClient:c.clientInfo},ee=b!==void 0?{...X,forwardedEnv:b}:X;S=await Xd(e,{...ee,onInstallProgress:Rg(a)})}let T=la(a,S,c,f.clientInfo,f.clientId),F=h.replayMode==="drip",{entries:_,appliedPolicy:N}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:F,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${N} replayed=${_.length} readonly=${y}${F?" replayMode=drip":""}`),F){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,D=750;(async()=>{let X=null;for(let ee of _){let ae=typeof ee.recordedAt=="number"?ee.recordedAt:null;if(X!==null&&ae!==null){let G=Math.min(D,Math.max(0,(ae-X)/L));G>0&&await new Promise(fe=>setTimeout(fe,G))}ae!==null&&(X=ae);try{await a.notify(ee.method,ee.params)}catch{return}}})()}else for(let L=0;L<_.length&&!a.isClosed();L++){let D=_[L],X=a.notify(D.method,D.params).catch(()=>{});(L+1)%200===0&&await X}S.replayPendingPermissions(T);let J=Zd(S),q=ec(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:N,replayed:_.length,...J?{modes:J}:{},...q?{models:q}:{},configOptions:S.buildConfigOptions(),_meta:tc(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=Ih.parse(u),p=c.attached.get(f.sessionId);if(!p)throw ce(W.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Lt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=xh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Mr).map(Ah)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw ce(W.InternalError,"agent registry unavailable");return Ii(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw ce(W.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=Ch.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),ce(W.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw ce(W.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Xd(e,m);let y=la(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=cd.parse(u)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=cd.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Th.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),on(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=cd.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),on(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Eh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),on(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Ph.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw ce(W.SessionNotFound,"not attached to session");return on(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(W.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 ce(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Xd(e,S)}let y=la(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 b=Zd(m),v=ec(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:tc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw ce(W.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let x=await e.manager.loadFromDisk(h);if(!x)throw ce(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Xd(e,x)}let y=la(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let v=Zd(m),S=ec(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:tc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=Ox(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),ce(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",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw ce(W.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw ce(W.InvalidParams,"session/set_mode requires string modeId");let h=on(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>ce(W.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=on(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw ce(W.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw ce(W.MethodNotFound,`Method not found: ${f}`);return d(y,f),on(e.manager,y).forwardRequest(f,u)})})}async function Fx(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw ce(W.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 ce(W.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,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,x)=>{if(!Array.isArray(S))throw ce(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw ce(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Pg.isAbsolute(S)?S:h.command,y=p(u.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,x=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...x]}let b={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(b[S]=x);Object.assign(b,h.env);let v=Eg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Ws(p,a)}}function Rg(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(ld,n).catch(()=>{})}}function Zd(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 ec(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 Ox(t,e){if(!t||typeof t!="object")return{kind:"error",code:W.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:W.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:W.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:W.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Ei(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:W.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 Lx(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw ce(W.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw ce(W.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw ce(W.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return on(n.manager,r).addTransformer(i),{ok:!0}}async function Bx(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 ce(W.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw ce(W.InvalidParams,"hydra-acp/attention/set requires string reason");return on(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function Nx(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 ce(W.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw ce(W.InvalidParams,"hydra-acp/attention/clear requires string reason");return on(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function Dx(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{[Lt]:ad(e,n)}}function tc(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 Uo(e.agentMeta,ad(s,r))}function Hx(){return{protocolVersion:1,agentInfo:{name:"hydra",version:me},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{},resume:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Uo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Ux(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 la(t,e,n,s,r){return{clientId:r??`cli_${Hu(8)}`,connection:t,clientInfo:s}}var nc=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 jx}from"crypto";import{McpServer as qx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Wx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Nt}from"zod";function*Uu(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 an(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var _g="Bearer ";function Wi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(_g))return;let n=e.slice(_g.length).trim();return n.length>0?n:void 0}function zx(t){let e=new qx({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:Nt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return an(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:Nt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return an(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:Nt.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:Nt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Nt.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 an(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:Nt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Nt.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 an({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:Nt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Nt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Nt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Nt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Nt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Nt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Nt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Nt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Nt.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 an(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 an(n)}),e}var Kx=1e4;function $g(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=zx(a),l=new Wx({sessionIdGenerator:()=>jx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),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=Wi(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 f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Kx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}md();import{randomUUID as Jx}from"crypto";import{McpServer as Yx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Vx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ys}from"zod";function Qx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Gx(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 Xx(t){let e=new Yx({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:Ys.string().min(1).describe("Case-insensitive substring to search for."),limit:Ys.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ys.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 an({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:u}of Uu(o)){if(u==="tool_call"&&!r)continue;let f=Pi([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=Qx(u),m=Gx(f,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 an({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:Ys.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ys.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 an({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),u=Pi(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,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:Ys.string().optional(),file_path:Ys.string().optional(),limit:Ys.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 an({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 Uu(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))v.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];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(),b=["file_path","filePath","path"],v=!1;for(let S of b){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return an({calls:u,truncated:f})}),e}var Zx=1e4;function Fg(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=Xx(a),l=new Vx({sessionIdGenerator:()=>Jx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),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=Wi(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 u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Zx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.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 aA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as dA}from"crypto";import{Server as eA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as tA,ListToolsRequestSchema as nA}from"@modelcontextprotocol/sdk/types.js";function Og(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new eA({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(nA,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(tA,async(o,a)=>{let c=o.params.name;if(!i.has(c))return rc(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=rA(d,a.sendNotification);try{let u=await s(),f=await iA(e.connection,t,c,o.params.arguments??{},u);return oA(f,c)}catch(u){return rc(u instanceof Error?u.message:String(u))}finally{l()}}),r}var sA=15e3;function rA(t,e,n=sA){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 iA(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function oA(t,e){if(t===null||typeof t!="object")return rc(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:rc(`extension ${e} omitted content array`)}function rc(t){return{content:[{type:"text",text:t}],isError:!0}}var cA=1e4;function Lg(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=Og(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),cA)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId}),y=new aA({sessionIdGenerator:()=>dA()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Wi(d);if(u===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,h=await o(u,p);if(h===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await h.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function Ug(t,e){mA(t);let n=t.daemon.tls?await zi.readFile(rt(t.daemon.tls.key)):void 0,s=t.daemon.tls?await zi.readFile(rt(t.daemon.tls.cert)):void 0;await zi.mkdir($.home(),{recursive:!0});let{stream:r,fileStream:i}=await pA(t.daemon.logLevel),o=lA({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(uA,{options:{handleProtocols:eh}}),Ol(Y=>{o.log.info(Y)}),Nl(Y=>{o.log.info(Y)});let a=await Bd.load(),c=new jd,d=new Ud,l=new Hd([new Nd(e),new Dd(a),d]),u=Km({validator:l});o.addHook("onRequest",async(Y,Se)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await u(Y,Se)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new rd(t,{onFetched:()=>{Bm(h,v)}});Eu(Y=>o.log.info(Y));let m={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},y=Y=>js.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});rh(t.compressToolContent);let b=new Od,v=new Rd(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,logger:m,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new $d(Cp(t),void 0,{tokenRegistry:d}),x=new Fd(Rp(t),void 0,{tokenRegistry:d});mg(o,me,zs(t));let T=new nc,F=new sc,_,N=()=>{if(_!==void 0)return _;let Y=o.server.address();return _=`http://127.0.0.1:${Y&&typeof Y=="object"?Y.port:t.daemon.port}`,_};pg(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:F,mcpTokenRegistry:T,getDaemonOrigin:N}),hg(o,h,v,{npmRegistry:t.npmRegistry}),gg(o,S),yg(o,x),wg(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]}),Cg(o,{store:a,rateLimiter:c}),$g(o,T),Fg(o,T),Lg(o,T,F),Mg(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,Se)=>S.reportVersion(Y,Se),onTransformerVersion:(Y,Se)=>x.reportVersion(Y,Se),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:F,getDaemonOrigin:N,registry:h});let J=!!t.daemon.tls;await o.listen({host:J?"127.0.0.1":t.daemon.host,port:J?0:t.daemon.port});let q=o.server.address(),L=q&&typeof q=="object"?q.port:t.daemon.port,D,X=t.daemon.host,ee=L;if(J&&n&&s){D=hA({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let Y=D.address();Y&&typeof Y=="object"&&(ee=Y.port)}await zi.mkdir($.home(),{recursive:!0}),await Op({pid:process.pid,host:X,port:ee,loopbackPort:L,startedAt:new Date().toISOString()});let ae={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:$.home()};S.setContext(ae),x.setContext(ae),await S.start(),await x.start();try{await v.reconcilePermissionFlags()}catch(Y){o.log.warn(`permission flag reconcile failed: ${Y.message}`)}v.resurrectPendingQueues().catch(Y=>{o.log.warn(`queue replay scan failed: ${Y.message}`)}),v.resumePendingCompactions().catch(Y=>{o.log.warn(`compaction resume scan failed: ${Y.message}`)}),v.resumePendingAgentSwaps().catch(Y=>{o.log.warn(`agent-swap resume scan failed: ${Y.message}`)});let G=t.daemon.agentSyncIntervalMinutes*60*1e3,fe=G>0?Nm({registry:h,manager:v,intervalMs:G,logger:m}):void 0,Ve=t.daemon.sessionGcIntervalMinutes*60*1e3,Be=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ns=Ve>0?Dm({manager:v,intervalMs:Ve,maxAgeMs:Be,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:F,processRegistry:d,shutdown:async()=>{ns&&ns(),fe&&fe(),clearInterval(f),clearInterval(p);let Y=async(Se,De)=>{try{await De()}catch(Vt){o.log.warn(`shutdown step ${Se} failed: ${Vt instanceof Error?Vt.message:String(Vt)}`)}};await Y("sessionTokenStore.flush",()=>a.flush()),await Y("extensions.stop",()=>S.stop()),await Y("transformers.stop",()=>x.stop()),await Y("manager.closeAll",()=>v.closeAll()),await Y("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await Y("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await Y("manager.flushMetaWrites",()=>v.flushMetaWrites()),await Y("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Ol(null),Nl(null),Eu(null),D&&await Y("tlsTerminator.close",()=>new Promise(Se=>D.close(()=>Se()))),await Y("app.close",()=>o.close());try{Ng.unlinkSync($.pidFile())}catch{}await Y("fileStream.flushSync",()=>i.flushSync())}}}async function pA(t){let e=await fA({file:$.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=Bg.destination(2);return{stream:Bg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function hA(t){let e=Hg.createServer(t.tlsOptions,n=>{let s=Dg.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 mA(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.`)}Br();rn();ia();ua();async function zg(t={}){let e=await Ie(),n=await Fo();if(await ic(e)){let r=await Yi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
318
318
  `);return}if(pi(t,"foreground")){process.title="hydra-daemon";let r=await Ug(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
319
319
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
320
320
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
@@ -326,10 +326,10 @@ ${ru}`;return um(t,s,am)}function Hk(t){if(!t||typeof t!="object")return"";let e
326
326
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
327
327
  `)}}async function Jg(){let t=await Ie();await Fo();let e=await Yi();if(e&&An(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
328
328
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
329
- `),process.exit(1)}await SA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
329
+ `),process.exit(1)}await kA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
330
330
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
331
331
  `);if(oc(),await ac(t),await ic(t)){let n=await Yi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
332
- `)}}async function SA(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!An(t))return!0;await vA(50)}return!1}async function Yg(t){await Ji($.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Vg(){let t=await Yi();if(!t){process.stdout.write(`Daemon: not running
332
+ `)}}async function kA(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!An(t))return!0;await SA(50)}return!1}async function Yg(t){await Ji($.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Vg(){let t=await Yi();if(!t){process.stdout.write(`Daemon: not running
333
333
  `),process.stdout.write(`CLI version: ${me}
334
334
  `);return}let e=An(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
335
335
  `);let n,s;if(e)try{let o=await Ie();n=await Lr(o),s=zs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${me}
@@ -360,24 +360,24 @@ ${ru}`;return um(t,s,am)}function Hk(t){if(!t||typeof t!="object")return"";let e
360
360
  `),process.exit(2));let s=await kr(),r=await Vi(),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}
361
361
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
362
362
  `)||process.stdout.write(`
363
- `);return}let c=e==="."?DA(o,t):e;await yn.mkdir(wn.dirname(wn.resolve(c)),{recursive:!0}),await yn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
363
+ `);return}let c=e==="."?HA(o,t):e;await yn.mkdir(wn.dirname(wn.resolve(c)),{recursive:!0}),await yn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
364
364
  `)}async function hy(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
365
- `),process.exit(2));let n,s,r=await FA(t);if(r!==null){let o=OA(r.raw);n=Kd(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${wn.basename(t,wn.extname(t))}-${a}.md`}else{let o=await kr(),a=await Vi(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
365
+ `),process.exit(2));let n,s,r=await OA(t);if(r!==null){let o=LA(r.raw);n=Kd(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${wn.basename(t,wn.extname(t))}-${a}.md`}else{let o=await kr(),a=await Vi(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
366
366
  `),process.exit(1)}n=await c.text();let d=new Date().toISOString().replace(/[:.]/g,"-");s=`hydra-${t}-${d}.md`}if(!e){process.stdout.write(n),n.endsWith(`
367
367
  `)||process.stdout.write(`
368
368
  `);return}let i=e==="."?s:e;await yn.mkdir(wn.dirname(wn.resolve(i)),{recursive:!0}),await yn.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
369
- `)}async function FA(t){try{if(!(await yn.stat(t)).isFile())return null}catch{return null}let e=await yn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
370
- `),process.exit(1)}}function OA(t){try{return Cn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
369
+ `)}async function OA(t){try{if(!(await yn.stat(t)).isFile())return null}catch{return null}let e=await yn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
370
+ `),process.exit(1)}}function LA(t){try{return Cn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
371
371
  `),process.exit(1)}}async function my(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
372
372
  `),process.exit(2));let n;if(e.cwd!==void 0){let a=wn.resolve(e.cwd);try{(await yn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
373
373
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
374
- `),process.exit(1)}n=a}let s;t==="-"?s=await NA():s=await yn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
375
- `),process.exit(1)}if(e.info===!0){let a=await Ie();BA(r,a.tui.cwdColumnMaxWidth);return}let i=await Me("/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.
374
+ `),process.exit(1)}n=a}let s;t==="-"?s=await DA():s=await yn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
375
+ `),process.exit(1)}if(e.info===!0){let a=await Ie();NA(r,a.tui.cwdColumnMaxWidth);return}let i=await Me("/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.
376
376
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
377
377
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
378
378
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
379
- `)}function LA(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 BA(t,e){let n;try{n=Cn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
380
- `),process.exit(1)}let s=LA(n),r=eo(s),i={columns:mc,cwdMaxWidth:e},o=to([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Gs(Zi,o,a,i)+`
379
+ `)}function BA(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 NA(t,e){let n;try{n=Cn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
380
+ `),process.exit(1)}let s=BA(n),r=eo(s),i={columns:mc,cwdMaxWidth:e},o=to([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Gs(Zi,o,a,i)+`
381
381
  `),process.stdout.write(Gs(r,o,a,i)+`
382
382
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
383
383
  lineage: ${n.session.lineageId}
@@ -386,10 +386,10 @@ origin session: ${n.session.sessionId}
386
386
  origin upstream: ${c}
387
387
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
388
388
  `:`
389
- `))}async function NA(){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 DA(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 gy(t,e={}){let n=await Ie(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ut(n),l=e.cwd?wn.resolve(e.cwd):process.cwd(),u=await Yn(d,{cwd:l,all:!0}),f=pc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
390
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=HA(e.host,n),a=lt(s),c=_p({host:r,port:i,sessionId:a});process.stdout.write(c+`
389
+ `))}async function DA(){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 HA(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 gy(t,e={}){let n=await Ie(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ut(n),l=e.cwd?wn.resolve(e.cwd):process.cwd(),u=await Yn(d,{cwd:l,all:!0}),f=pc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
390
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=UA(e.host,n),a=lt(s),c=_p({host:r,port:i,sessionId:a});process.stdout.write(c+`
391
391
  `),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.
392
- `)}function HA(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=ay(t,xn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=ay(e.daemon.publicHost,xn);return{host:n,port:s,isFallback:!1}}return UA(e.daemon.host)?{host:jA(),port:e.daemon.port,isFallback:!1}:xr(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 UA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function jA(){let t=dy.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function ay(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}}af();gc();nf();tt();ye();ua();Qs();var AC={extension:{singular:"extension",plural:"extensions",logFile:t=>$.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>$.transformerLogFile(t)}};function kc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function io(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ic(t){let e=AC[t],n=`/v1/${e.plural}`;async function s(){let u=(await Me(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
392
+ `)}function UA(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=ay(t,xn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=ay(e.daemon.publicHost,xn);return{host:n,port:s,isFallback:!1}}return jA(e.daemon.host)?{host:qA(),port:e.daemon.port,isFallback:!1}:xr(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 jA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function qA(){let t=dy.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function ay(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}}af();gc();nf();tt();ye();ua();Qs();var CC={extension:{singular:"extension",plural:"extensions",logFile:t=>$.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>$.transformerLogFile(t)}};function kc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function io(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ic(t){let e=CC[t],n=`/v1/${e.plural}`;async function s(){let u=(await Me(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
393
393
  `);return}let f=u.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?Qi(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:io(p.name,f.map(y=>y.name)),status:io(p.status,f.map(y=>y.status)),version:io(p.version,f.map(y=>y.version)),pid:io(p.pid,f.map(y=>y.pid)),restarts:io(p.restarts,f.map(y=>y.restarts)),started:io(p.started,f.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)+`
394
394
  `);for(let y of f)process.stdout.write(m(y)+`
395
395
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
@@ -413,18 +413,18 @@ history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.pr
413
413
  `),h+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${m.name}: ${b.status}${v}
414
414
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
415
415
  `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=dc(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
416
- `),process.exit(2);return}let f=e.logFile(l);await Ji(f,u,`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 _y(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Dr=Ic("extension"),$y=Dr.list,Fy=Dr.add,Oy=Dr.remove,Ly=Dr.start,By=Dr.stop,Ny=Dr.restart,Dy=Dr.logs;var Hr=Ic("transformer"),Hy=Hr.list,Uy=Hr.add,jy=Hr.remove,qy=Hr.start,Wy=Hr.stop,zy=Hr.restart,Ky=Hr.logs;wf();fa();qi();Pr();tt();Rr();Br();Bt();sn();od();kf();import jC from"os";import{spawn as qC}from"child_process";async function WC({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",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await zC(c,s),u=await Sf(l,{authenticate:f=>t.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
416
+ `),process.exit(2);return}let f=e.logFile(l);await Ji(f,u,`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 _y(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Dr=Ic("extension"),$y=Dr.list,Fy=Dr.add,Oy=Dr.remove,Ly=Dr.start,By=Dr.stop,Ny=Dr.restart,Dy=Dr.logs;var Hr=Ic("transformer"),Hy=Hr.list,Uy=Hr.add,jy=Hr.remove,qy=Hr.start,Wy=Hr.stop,zy=Hr.restart,Ky=Hr.logs;wf();fa();qi();Pr();tt();Rr();Br();Bt();rn();od();kf();import qC from"os";import{spawn as WC}from"child_process";async function zC({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",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await KC(c,s),u=await Sf(l,{authenticate:f=>t.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
417
417
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
418
418
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
419
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:jC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
420
- `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===W.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function zC(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}
419
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:qC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
420
+ `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===W.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function KC(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}
421
421
  `),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:
422
422
  ${s.join(`
423
423
  `)}
424
424
  `);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}
425
425
  `),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})
426
426
  `),process.exit(2)}async function hw(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
427
- `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(wf(),Qy)),s=await n(t,"hydra agent auth"),r=await Ie(),i=await Ut(r);await Vs(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Nr(i.wsUrl,o),c=Jn(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:me}})}catch{}let l;try{l=await WC({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:qC})}finally{a.close()}process.exit(l.exitCode)}ua();Sl();Qs();async function mw(t){let e=pi(t,"force");if(await Qd()&&!e){let r=await wi("Current password: ");await Gd(r)||(process.stderr.write(`Wrong password.
427
+ `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(wf(),Qy)),s=await n(t,"hydra agent auth"),r=await Ie(),i=await Ut(r);await Vs(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Nr(i.wsUrl,o),c=Jn(a),d=new Jt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:me}})}catch{}let l;try{l=await zC({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:WC})}finally{a.close()}process.exit(l.exitCode)}ua();Sl();Qs();async function mw(t){let e=pi(t,"force");if(await Qd()&&!e){let r=await wi("Current password: ");await Gd(r)||(process.stderr.write(`Wrong password.
428
428
  `),process.exit(1))}let n=await wi("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
429
429
  `),process.exit(2));let s=await wi("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
430
430
  `),process.exit(1)),await Ag(n),process.stdout.write(`Password set.
@@ -435,26 +435,26 @@ ${s.join(`
435
435
  `),process.exit(2));let e=await Me(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
436
436
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
437
437
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
438
- `),process.exit(1)}function _c(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as er from"fs";tt();Rr();Br();If();Bt();var $c=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Af(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(xf(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(!xf(e)&&!Af(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(xf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};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(!Af(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=tn(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 xf(t){return"method"in t&&"id"in t&&t.id!==void 0}function Af(t){return!("method"in t)&&"id"in t}Oc();sn();ye();Bo();import{writeFileSync as GC}from"fs";var XC=t=>{GC("/proc/self/comm",t)};function po(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??XC;try{s(e.commName??Dn())}catch{}}function ho(t,e=Dn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Bc(t){po(ho(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ie(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Vs(e);let s=new $c,r=ud(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ut(await Ie())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new fo({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await rR(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
439
- `);for(let l of d)await iR(a,l,s.lastMessageId(l.sessionId))}}});ZC({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
440
- `),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 ZC({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(xw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&cR(i)){e.send({jsonrpc:"2.0",id:i.id,result:Kr(i.params)});return}eR(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(xw("client\u2192daemon",i),s.observeFromClient(i),aR(i)){e.send(dR(i));return}if(oR(i)){if(t.sessionId){e.send(lR(i,t.sessionId));return}let o=i;t.agentId&&(o=Lc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Lc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Lc(o,{title:r.name}),r.used=!0),t.model&&(o=Lc(o,{model:t.model})),e.send(o);return}e.send(i)})}function eR(t,e,n){let s=tR(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=sR(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function tR(t){if(!nR(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function nR(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function sR(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function rR(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
441
- `);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 iR(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}
438
+ `),process.exit(1)}function _c(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as er from"fs";tt();Rr();Br();If();Bt();var $c=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Af(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(xf(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(!xf(e)&&!Af(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(xf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};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(!Af(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=nn(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 xf(t){return"method"in t&&"id"in t&&t.id!==void 0}function Af(t){return!("method"in t)&&"id"in t}Oc();rn();ye();Bo();import{writeFileSync as XC}from"fs";var ZC=t=>{XC("/proc/self/comm",t)};function po(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??ZC;try{s(e.commName??Dn())}catch{}}function ho(t,e=Dn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Bc(t){po(ho(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ie(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Vs(e);let s=new $c,r=ud(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ut(await Ie())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new fo({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await iR(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
439
+ `);for(let l of d)await oR(a,l,s.lastMessageId(l.sessionId))}}});eR({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
440
+ `),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 eR({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(xw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&lR(i)){e.send({jsonrpc:"2.0",id:i.id,result:Kr(i.params)});return}tR(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(xw("client\u2192daemon",i),s.observeFromClient(i),dR(i)){e.send(cR(i));return}if(aR(i)){if(t.sessionId){e.send(uR(i,t.sessionId));return}let o=i;t.agentId&&(o=Lc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Lc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Lc(o,{title:r.name}),r.used=!0),t.model&&(o=Lc(o,{model:t.model})),e.send(o);return}e.send(i)})}function tR(t,e,n){let s=nR(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=rR(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function nR(t){if(!sR(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function sR(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function rR(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function iR(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
441
+ `);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 oR(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}
442
442
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
443
- `)}}function oR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function aR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function dR(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:me}}}}function cR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function lR(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var uR=25*1024*1024,Iw=!1,Jr=null;function xw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Iw){Iw=!0;try{Jr=$.shimWireLogFile(),er.mkdirSync($.home(),{recursive:!0});let n=er.statSync(Jr,{throwIfNoEntry:!1});n&&n.size>uR&&er.renameSync(Jr,`${Jr}.1`)}catch{Jr=null}}if(Jr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
444
- `;er.appendFile(Jr,n,()=>{})}catch{}}}function Lc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Pr();qi();fa();tt();Rr();Br();Ks();Bt();sn();Oc();import{mkdtempSync as kR,rmSync as IR}from"fs";import{tmpdir as xR}from"os";import{join as AR}from"path";function Aw(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())}}}ro();import fR from"chalk";import pR from"strip-ansi";var Nc=new fR.Instance({level:3});function Cw(t,e){if(t.length===0)return"";let n=Zs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(hR(i,e));let r=s.join(`
443
+ `)}}function aR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function dR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function cR(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:me}}}}function lR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function uR(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var fR=25*1024*1024,Iw=!1,Jr=null;function xw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Iw){Iw=!0;try{Jr=$.shimWireLogFile(),er.mkdirSync($.home(),{recursive:!0});let n=er.statSync(Jr,{throwIfNoEntry:!1});n&&n.size>fR&&er.renameSync(Jr,`${Jr}.1`)}catch{Jr=null}}if(Jr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
444
+ `;er.appendFile(Jr,n,()=>{})}catch{}}}function Lc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Pr();qi();fa();tt();Rr();Br();Ks();Bt();rn();Oc();import{mkdtempSync as IR,rmSync as xR}from"fs";import{tmpdir as AR}from"os";import{join as CR}from"path";function Aw(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())}}}ro();import pR from"chalk";import hR from"strip-ansi";var Nc=new pR.Instance({level:3});function Cw(t,e){if(t.length===0)return"";let n=Zs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(mR(i,e));let r=s.join(`
445
445
  `);return r.endsWith(`
446
446
  `)||(r+=`
447
- `),r}function hR(t,e){let n=vR(t.body,e);return e==="ansi"?n=SR(n,t.bodyStyle):n=pR(n),n}var mR="\x1B[1m",gR="\x1B[96m",yR="\x1B[93m",wR="\x1B[0m",bR="\0";function vR(t,e){let n=t.replace(/\^\^/g,bR);return e==="ansi"&&(n=n.replace(/\^\+/g,mR).replace(/\^C/g,gR).replace(/\^Y/g,yR).replace(/\^:/g,wR)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function SR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Nc.bold.yellowBright(t);case"heading-2":return Nc.bold.cyanBright(t);case"heading-3":return Nc.bold(t);case"dim":return Nc.dim(t);default:return t}}var CR=1*1024*1024,Rw="mcp__hydra-acp-stdin__";function Tw(t,e){return{sessionId:t,prompt:e,_meta:{[Lt]:{ancillary:!0}}}}function RR(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 TR(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(Rw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Rw))}async function Ew(t){if(po(ho(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.
448
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=kR(AR(xR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{IR(c,{recursive:!0,force:!0})}catch{}})}let e=await Ie(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Vs(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Nr(n.wsUrl,s),i=Jn(r),o=new Kt(i),a=await PR({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:ER(n.baseUrl,n.token)});process.exit(a.exitCode)}function ER(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 PR(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 G=>n.dangerouslySkipPermissions?Kr(G):TR(G)?Kr(G):vw(G));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Mr,version:me}})}catch{}let u=await $R(e,n,l),f=!1,p=!0,h="",m=0,y=G=>{G.length!==0&&(o(G),p=G.charCodeAt(G.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let G=Cw(h,c);if(h="",G.length===0)return;let fe=m>0?`
447
+ `),r}function mR(t,e){let n=SR(t.body,e);return e==="ansi"?n=kR(n,t.bodyStyle):n=hR(n),n}var gR="\x1B[1m",yR="\x1B[96m",wR="\x1B[93m",bR="\x1B[0m",vR="\0";function SR(t,e){let n=t.replace(/\^\^/g,vR);return e==="ansi"&&(n=n.replace(/\^\+/g,gR).replace(/\^C/g,yR).replace(/\^Y/g,wR).replace(/\^:/g,bR)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function kR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Nc.bold.yellowBright(t);case"heading-2":return Nc.bold.cyanBright(t);case"heading-3":return Nc.bold(t);case"dim":return Nc.dim(t);default:return t}}var RR=1*1024*1024,Rw="mcp__hydra-acp-stdin__";function Tw(t,e){return{sessionId:t,prompt:e,_meta:{[Lt]:{ancillary:!0}}}}function TR(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 ER(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(Rw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Rw))}async function Ew(t){if(po(ho(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.
448
+ `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=IR(CR(AR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{xR(c,{recursive:!0,force:!0})}catch{}})}let e=await Ie(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Vs(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Nr(n.wsUrl,s),i=Jn(r),o=new Jt(i),a=await MR({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:PR(n.baseUrl,n.token)});process.exit(a.exitCode)}function PR(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 MR(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 G=>n.dangerouslySkipPermissions?Kr(G):ER(G)?Kr(G):vw(G));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Mr,version:me}})}catch{}let u=await FR(e,n,l),f=!1,p=!0,h="",m=0,y=G=>{G.length!==0&&(o(G),p=G.charCodeAt(G.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let G=Cw(h,c);if(h="",G.length===0)return;let fe=m>0?`
449
449
  `:"";y(fe+G),m+=1},v=()=>{b(),f&&!p&&y(`
450
450
  `),f=!1};e.onNotification("session/update",G=>{let fe=G?.update,Ve=Kn(fe,{cwd:n.cwd});if(Ve){if(Ve.kind==="agent-text"){d?y(Ve.text):h+=Ve.text;return}if(Ve.kind==="turn-complete"){v();return}switch(Ve.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,x=async G=>{let fe=[];if(n.prompt&&!S&&fe.push({type:"text",text:n.prompt}),G.length>0&&fe.push({type:"text",text:G}),fe.length!==0){try{await e.request("session/prompt",Tw(u,fe)),S=!0}catch(Ve){a(`hydra-acp cat: prompt failed: ${Ve.message}
451
451
  `);return}v()}},T=0,F,_=new Promise(G=>{F=G}),N=!1,J=async G=>{N||(N=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Ve=>setTimeout(Ve,500))]),await e.close().catch(()=>{}),F({exitCode:G}))};e.onClose(G=>{G&&(a(`hydra-acp cat: ${G.message}
452
- `),T=1),N||(N=!0,v(),F({exitCode:T}))});let q=[],L=!1,D=!1,X=async()=>{if(!L){L=!0;try{for(;q.length>0;){let G=q.shift();if(G===void 0)break;await x(G)}}finally{L=!1,D&&q.length===0&&await J(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await J(0),_;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),MR({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{D=!0,!L&&q.length===0&&J(T)},onError:G=>{a(`hydra-acp cat: stdin error: ${G.message}
452
+ `),T=1),N||(N=!0,v(),F({exitCode:T}))});let q=[],L=!1,D=!1,X=async()=>{if(!L){L=!0;try{for(;q.length>0;){let G=q.shift();if(G===void 0)break;await x(G)}}finally{L=!1,D&&q.length===0&&await J(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await J(0),_;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),_R({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{D=!0,!L&&q.length===0&&J(T)},onError:G=>{a(`hydra-acp cat: stdin error: ${G.message}
453
453
  `),T=1,D=!0,!L&&q.length===0&&J(T)},onPromptFailed:G=>{a(`hydra-acp cat: ${G.message}
454
454
  `),T=1,D=!0,!L&&q.length===0&&J(T)}}),_;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let G=Aw({scheduleFlushCheck:fe=>{let Ve=setImmediate(fe);return()=>clearImmediate(Ve)},onChunk:fe=>{q.push(fe),X()}});return s.on("data",fe=>{G.feed(typeof fe=="string"?fe:fe.toString("utf8"))}),s.on("end",()=>{G.eof(),D=!0,!L&&q.length===0&&J(T)}),s.on("error",fe=>{a(`hydra-acp cat: stdin error: ${fe.message}
455
455
  `),T=1,D=!0,!L&&q.length===0&&J(T)}),_}let ae="";return s.on("data",G=>{ae+=typeof G=="string"?G:G.toString("utf8")}),s.on("end",()=>{D=!0,ae.length>0&&q.push(ae),X()}),s.on("error",G=>{a(`hydra-acp cat: stdin error: ${G.message}
456
- `),T=1,D=!0,!L&&q.length===0&&J(T)}),_}function MR(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??CR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let x=v.toString("base64");h=h.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
457
- `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=_R(r.prompt,v.capacityBytes);e.request("session/prompt",Tw(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=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 _R(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:
456
+ `),T=1,D=!0,!L&&q.length===0&&J(T)}),_}function _R(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??RR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let x=v.toString("base64");h=h.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
457
+ `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=$R(r.prompt,v.capacityBytes);e.request("session/prompt",Tw(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=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 $R(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:
458
458
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
459
459
  - \`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.
460
460
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -469,11 +469,11 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
469
469
  User's question:
470
470
  ${t}`:`${s}
471
471
 
472
- 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 $R(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Mr,version:me}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=RR(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={[Lt]:s});let o=await t.request("session/new",i);return tn(o._meta),o.sessionId}tt();ye();function Dc(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 Pw(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 FR(t){try{return JSON.parse(t)}catch{return t}}function Mw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function _w(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
472
+ 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 FR(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Mr,version:me}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=TR(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={[Lt]:s});let o=await t.request("session/new",i);return nn(o._meta),o.sessionId}tt();ye();function Dc(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 Pw(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 OR(t){try{return JSON.parse(t)}catch{return t}}function Mw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function _w(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
473
473
  `),process.exit(2));let e=Dc(t),n=await Ie(),s=Pw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
474
474
  `),process.exit(1)),process.stdout.write(`${Mw(s)}
475
475
  `)}async function $w(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
476
- `),process.exit(2));let n=Dc(t),s=FR(e);try{await gs(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}
476
+ `),process.exit(2));let n=Dc(t),s=OR(e);try{await gs(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}
477
477
  `),process.exit(1)}process.stdout.write(`set ${t} = ${Mw(s)}
478
478
  `)}async function Fw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
479
479
  `),process.exit(2));let e=Dc(t);try{await gs(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}
@@ -481,20 +481,20 @@ Use those tools to inspect the piped input and report what's there. Start with \
481
481
  `)}async function Ow(t){let e=await Ie(),n=t?Pw(e,Dc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
482
482
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
483
483
  `)}function Lw(){process.stdout.write(`${$.config()}
484
- `)}tt();ms();Br();sn();Qs();async function Dw(t={}){let{report:e,configLoaded:n}=await OR();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
484
+ `)}tt();ms();Br();rn();Qs();async function Dw(t={}){let{report:e,configLoaded:n}=await LR();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
485
485
  `);return}process.stdout.write(`CLI: ${e.cli}
486
486
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
487
487
  `),e.daemonReachable&&(Bw("Extensions",e.extensions),Bw("Transformers",e.transformers)))}function Bw(t,e){if(process.stdout.write(`
488
488
  ${t}:
489
489
  `),e.length===0){process.stdout.write(` (none)
490
490
  `);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}
491
- `)}}async function OR(){let t={cli:me,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ie()}catch{return{report:t,configLoaded:!1}}let n=await Lr(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 kr()}catch{return{report:t,configLoaded:!0}}let r=await Vi(),i={Authorization:`Bearer ${s}`};return t.extensions=await Nw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Nw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Nw(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 LR}from"child_process";import{accessSync as BR,constants as NR,statSync as DR}from"fs";import{delimiter as HR,join as UR}from"path";var jR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function qR(t){return jR.has(t)}function WR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function zR(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 KR(t){try{if(!DR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return BR(t,NR.X_OK),!0}catch{return!1}}function JR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(HR).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=UR(o,r+a);if(KR(c))return c}}function YR(t,e){let n=LR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
492
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function Hw(t){let e=WR(t);if(e===void 0||qR(e))return!1;let n=JR(e);if(n===void 0)return!1;YR(n,zR(t))}Cf();var sr=!1,rv=!1;function iv(t){!t||rv||(rv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
493
- `))}async function BT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Ho(),Up));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],x=v.slice(1),{flags:T}=fl(b);if(av(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
491
+ `)}}async function LR(){let t={cli:me,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ie()}catch{return{report:t,configLoaded:!1}}let n=await Lr(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 kr()}catch{return{report:t,configLoaded:!0}}let r=await Vi(),i={Authorization:`Bearer ${s}`};return t.extensions=await Nw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Nw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Nw(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 BR}from"child_process";import{accessSync as NR,constants as DR,statSync as HR}from"fs";import{delimiter as UR,join as jR}from"path";var qR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function WR(t){return qR.has(t)}function zR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function KR(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 JR(t){try{if(!HR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return NR(t,DR.X_OK),!0}catch{return!1}}function YR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(UR).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=jR(o,r+a);if(JR(c))return c}}function VR(t,e){let n=BR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
492
+ `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function Hw(t){let e=zR(t);if(e===void 0||WR(e))return!1;let n=YR(e);if(n===void 0)return!1;VR(n,KR(t))}Cf();var sr=!1,iv=!1;function ov(t){!t||iv||(iv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
493
+ `))}async function NT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Ho(),Up));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],x=v.slice(1),{flags:T}=fl(b);if(dv(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
494
494
  `),process.exit(2);return}let F=S??kt(T,"agent");if(!F){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
495
- `),process.exit(2);return}let _=await dv(El(T),{allowPrompt:!1}),N=kt(T,"name"),J=kt(T,"model");sr=!0;let q=T["dangerously-skip-permissions"]===!0;iv(q);let L={agentId:F,agentArgs:x,name:N,model:J,dangerouslySkipPermissions:q};_?.sessionId!==void 0&&(L.sessionId=_.sessionId),_?.target!==void 0&&_.fromUrl&&(L.target=_.target),await Bc(L);return}cp(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&Hw(e);let{positional:s,flags:r}=fl(e);if(av(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${NT()}
496
- `);return}if(r.help===!0){pp(s[0]);return}let i=cp(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=kt(r,"name"),d=kt(r,"agent"),l=kt(r,"model"),u=r["dangerously-skip-permissions"]===!0;iv(u);let f=El(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await dv(f,{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.
497
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){sr=!0,await ov(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}sr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Bc(b);return}switch(a){case"shim":{sr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Bc(b);return}case"cat":{let b=cp(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=kt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let F=fp(r,"stream-threshold");F!==void 0&&(T.streamThreshold=F);let _=fp(r,"stream-bytes");_!==void 0&&(T.streamBufferBytes=_),d!==void 0&&await xc(d),sr=!0,await Ew(T);return}case"version":{sr=!0,await Dw({json:r.json===!0});return}case"init":await Xp(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Vg();return}if(S==="start"){await zg(r);return}if(S==="stop"){await Kg();return}if(S==="restart"){await Jg();return}if(S==="log"||S==="logs"){await Yg(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
495
+ `),process.exit(2);return}let _=await cv(El(T),{allowPrompt:!1}),N=kt(T,"name"),J=kt(T,"model");sr=!0;let q=T["dangerously-skip-permissions"]===!0;ov(q);let L={agentId:F,agentArgs:x,name:N,model:J,dangerouslySkipPermissions:q};_?.sessionId!==void 0&&(L.sessionId=_.sessionId),_?.target!==void 0&&_.fromUrl&&(L.target=_.target),await Bc(L);return}cp(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&Hw(e);let{positional:s,flags:r}=fl(e);if(dv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${DT()}
496
+ `);return}if(r.help===!0){pp(s[0]);return}let i=cp(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=kt(r,"name"),d=kt(r,"agent"),l=kt(r,"model"),u=r["dangerously-skip-permissions"]===!0;ov(u);let f=El(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await cv(f,{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.
497
+ `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){sr=!0,await av(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}sr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Bc(b);return}switch(a){case"shim":{sr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Bc(b);return}case"cat":{let b=cp(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=kt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let F=fp(r,"stream-threshold");F!==void 0&&(T.streamThreshold=F);let _=fp(r,"stream-bytes");_!==void 0&&(T.streamBufferBytes=_),d!==void 0&&await xc(d),sr=!0,await Ew(T);return}case"version":{sr=!0,await Dw({json:r.json===!0});return}case"init":await Xp(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Vg();return}if(S==="start"){await zg(r);return}if(S==="stop"){await Kg();return}if(S==="restart"){await Jg();return}if(S==="log"||S==="logs"){await Yg(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
498
498
  `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=kt(r,"columns"),S;if(v!==void 0)try{S=oy(v)}catch(x){process.stderr.write(`${x.message}
499
499
  `),process.exit(2);return}await cy({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(b==="info"){await My(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(b==="diff"){await Py(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(b==="kill"){await ly(s[2]);return}if(b==="remove"){await uy(s[2]);return}if(b==="collect"){let v=kt(r,"max-age-days"),S=kt(r,"limit"),x={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
500
500
  `),process.exit(2);return}x.maxAgeDays=T}if(S!==void 0){let T=Number(S);if(!Number.isFinite(T)||T<=0){process.stderr.write(`--limit must be a positive number
@@ -506,13 +506,13 @@ ${t}:
506
506
  `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await mw(r);return}process.stderr.write(`Unknown auth password action: ${v}
507
507
  `),process.exit(2);return}if(b===void 0||b==="list"){await gw();return}if(b==="revoke"){await yw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
508
508
  `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await Ow(s[2]);return}if(b==="get"){await _w(s[2]);return}if(b==="set"){await $w(s[2],s[3]);return}if(b==="unset"){await Fw(s[2]);return}if(b==="path"){Lw();return}process.stderr.write(`Unknown config subcommand: ${b}
509
- `),process.exit(2);return}case"tui":sr=!0,await ov(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
510
- `),pp(),process.exit(2)}}async function ov(t,e){let n=kt(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 xc(e.agentId),po(ho(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(sv(),nv)),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.
511
- `),process.exit(2)),a.drip=!0;let c=fp(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function fp(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 av(t){let e=Sp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
509
+ `),process.exit(2);return}case"tui":sr=!0,await av(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
510
+ `),pp(),process.exit(2)}}async function av(t,e){let n=kt(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 xc(e.agentId),po(ho(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(rv(),sv)),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.
511
+ `),process.exit(2)),a.drip=!0;let c=fp(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function fp(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 dv(t){let e=Sp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
512
512
 
513
- `),pp(),process.exit(2))}function cp(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 dv(t,e){try{return await Yp(t,e)}catch(n){ne({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
514
- `),process.exit(1)}}function NT(){try{let t=OT(FT(import.meta.url));return JSON.parse($T(LT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var lp=["tui"],DT=["shim"],xt=["cat"],il=["launch"],HT=["init"],ol=["daemon"],UT=["version"],ut=["session","sessions"],_a=["extension","extensions"],$a=["transformer","transformers"],ts=["agent","agents"],jT=["registry"],Fa=["config"],up=["auth"];function pp(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."],[DT," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[xt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[xt," Pipe-friendly headless mode. Reads stdin and sends it"],[xt," as a prompt to a fresh session, streams the agent's"],[xt," response to stdout, exits when stdin closes. A bounded"],[xt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[xt," as one turn; a streaming input (e.g. `tail -f`) is"],[xt," chunked by the natural pauses in the writer. -p is an"],[xt," optional standing instruction prepended to every chunk;"],[xt," if stdin already contains the question, -p is not needed."],[xt," By default, agent markdown is post-processed: ANSI-styled"],[xt," on a TTY, stripped to plain text on a pipe, tables laid"],[xt," out in both modes. Tool calls / thoughts split paragraphs"],[xt," but otherwise stay hidden. --raw bypasses the renderer"],[xt," and emits chunks immediately, the way cat used to behave."],[xt," With --session, attach to an existing session instead"],[xt," of creating a new one. With --detach, the session"],[xt," survives in the daemon for slack/browser/notifier"],[xt," extensions."],[il," hydra-acp launch <agent> [agent-args...]"],[il," Shim mode, force daemon to spawn <agent>"],[il," from the registry. Args after <agent>"],[il," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","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)."]]})(),[HT," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[ol," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[ol," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[ol," hydra-acp daemon stop|restart"],[ol," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[UT," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ut," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ut," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ut," --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."],[ut," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ut," --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."],[ut," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ut," 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)."],[ut," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ut," 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."],[ut," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ut," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ut," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ut," 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."],[ut," hydra-acp session export <id> [--out <file>|.]"],[ut," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ut," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ut," 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"],[ut," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ut," 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"],[ut," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ut," 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)."],[_a," hydra-acp extension list List configured extensions and live state"],[_a," hydra-acp extension add <name> [opts] Add an extension to config"],[_a," hydra-acp extension remove <name> Remove an extension from config"],[_a," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[_a," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[$a," hydra-acp transformer list List configured transformers and live state"],[$a," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[$a," hydra-acp transformer remove <name> Remove a transformer from config"],[$a," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[$a," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[ts," hydra-acp agent [list] List agents in the cached registry"],[ts," hydra-acp agent refresh Force a registry re-fetch"],[ts," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[ts," 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>])."],[ts," 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."],[ts," 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)."],[ts," hydra-acp agent remove <id> Remove a local agent."],[jT," 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."],[ts," 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`"],[ts," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[ts," hydra-acp agent auth <id> Run the auth flow for <id>"],[Fa," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Fa," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Fa," 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."],[Fa," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Fa," hydra-acp config path Print the config file path"],[up," hydra-acp auth password [--force] Set the daemon's master password"],[up," hydra-acp auth [list] List active session tokens"],[up," 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(`
513
+ `),pp(),process.exit(2))}function cp(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 cv(t,e){try{return await Yp(t,e)}catch(n){ne({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
514
+ `),process.exit(1)}}function DT(){try{let t=LT(OT(import.meta.url));return JSON.parse(FT(BT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var lp=["tui"],HT=["shim"],xt=["cat"],il=["launch"],UT=["init"],ol=["daemon"],jT=["version"],ut=["session","sessions"],_a=["extension","extensions"],$a=["transformer","transformers"],ts=["agent","agents"],qT=["registry"],Fa=["config"],up=["auth"];function pp(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."],[HT," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[xt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[xt," Pipe-friendly headless mode. Reads stdin and sends it"],[xt," as a prompt to a fresh session, streams the agent's"],[xt," response to stdout, exits when stdin closes. A bounded"],[xt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[xt," as one turn; a streaming input (e.g. `tail -f`) is"],[xt," chunked by the natural pauses in the writer. -p is an"],[xt," optional standing instruction prepended to every chunk;"],[xt," if stdin already contains the question, -p is not needed."],[xt," By default, agent markdown is post-processed: ANSI-styled"],[xt," on a TTY, stripped to plain text on a pipe, tables laid"],[xt," out in both modes. Tool calls / thoughts split paragraphs"],[xt," but otherwise stay hidden. --raw bypasses the renderer"],[xt," and emits chunks immediately, the way cat used to behave."],[xt," With --session, attach to an existing session instead"],[xt," of creating a new one. With --detach, the session"],[xt," survives in the daemon for slack/browser/notifier"],[xt," extensions."],[il," hydra-acp launch <agent> [agent-args...]"],[il," Shim mode, force daemon to spawn <agent>"],[il," from the registry. Args after <agent>"],[il," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","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)."]]})(),[UT," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[ol," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[ol," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[ol," hydra-acp daemon stop|restart"],[ol," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[jT," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ut," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ut," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ut," --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."],[ut," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ut," --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."],[ut," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ut," 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)."],[ut," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ut," 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."],[ut," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ut," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ut," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ut," 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."],[ut," hydra-acp session export <id> [--out <file>|.]"],[ut," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ut," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ut," 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"],[ut," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ut," 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"],[ut," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ut," 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)."],[_a," hydra-acp extension list List configured extensions and live state"],[_a," hydra-acp extension add <name> [opts] Add an extension to config"],[_a," hydra-acp extension remove <name> Remove an extension from config"],[_a," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[_a," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[$a," hydra-acp transformer list List configured transformers and live state"],[$a," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[$a," hydra-acp transformer remove <name> Remove a transformer from config"],[$a," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[$a," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[ts," hydra-acp agent [list] List agents in the cached registry"],[ts," hydra-acp agent refresh Force a registry re-fetch"],[ts," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[ts," 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>])."],[ts," 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."],[ts," 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)."],[ts," hydra-acp agent remove <id> Remove a local agent."],[qT," 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."],[ts," 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`"],[ts," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[ts," hydra-acp agent auth <id> Run the auth flow for <id>"],[Fa," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Fa," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Fa," 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."],[Fa," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Fa," hydra-acp config path Print the config file path"],[up," hydra-acp auth password [--force] Set the daemon's master password"],[up," hydra-acp auth [list] List active session tokens"],[up," 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(`
515
515
  `)+`
516
- `)}async function cv(){if(!sr)try{let t=await ka();t&&process.stderr.write(`\u2728 ${Ia(t)}
517
- `)}catch{}}BT().then(cv).catch(async t=>{ne({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
518
- `),await cv(),process.exit(1)});
516
+ `)}async function lv(){if(!sr)try{let t=await ka();t&&process.stderr.write(`\u2728 ${Ia(t)}
517
+ `)}catch{}}NT().then(lv).catch(async t=>{ne({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
518
+ `),await lv(),process.exit(1)});