@hydra-acp/cli 0.1.118 → 0.1.119

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 +201 -201
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- var iS=Object.defineProperty;var Y=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ll=(n,e)=>{for(var t in e)iS(n,t,{get:e[t],enumerable:!0})};import*as ge from"path";import*as Nl from"os";function ct(n){let e=Nl.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function uS(){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 ke(){let n=process.env[lS];if(n&&n.length>0)return ge.resolve(n);let e=uS();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 ge.join(Nl.homedir(),".hydra-acp")}var lS,O,be=Y(()=>{"use strict";lS="HYDRA_ACP_HOME";O={home:ke,config:()=>ge.join(ke(),"config.json"),authToken:()=>ge.join(ke(),"auth-token"),remotes:()=>ge.join(ke(),"remotes.json"),pidFile:()=>ge.join(ke(),"daemon.pid"),logFile:()=>ge.join(ke(),"daemon.log"),currentLogFile:()=>ge.join(ke(),"current.log"),registryCache:()=>ge.join(ke(),"registry.json"),ttySessionDir:()=>ge.join(ke(),"tty"),ttySessionFile:n=>ge.join(ke(),"tty",n),agentsDir:()=>ge.join(ke(),"agents"),agentLogFile:n=>ge.join(ke(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>ge.join(ke(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>ge.join(ke(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>ge.join(ke(),"sessions"),sessionDir:n=>ge.join(ke(),"sessions",n),sessionFile:n=>ge.join(ke(),"sessions",n,"meta.json"),historyFile:n=>ge.join(ke(),"sessions",n,"history.jsonl"),historyArchiveFile:(n,e)=>ge.join(ke(),"sessions",n,`history.jsonl.${e}`),toolsDir:n=>ge.join(ke(),"sessions",n,"tools"),toolBlobFile:(n,e)=>ge.join(ke(),"sessions",n,"tools",e),queueFile:n=>ge.join(ke(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>ge.join(ke(),"sessions",".tombstones"),tombstoneAgentDir:n=>ge.join(ke(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>ge.join(ke(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>ge.join(ke(),"extensions"),extensionLogDir:n=>ge.join(ke(),"extensions",n),extensionLogFile:n=>ge.join(ke(),"extensions",n,"current.log"),extensionPidFile:n=>ge.join(ke(),"extensions",n,"extension.pid"),transformersDir:()=>ge.join(ke(),"transformers"),transformerLogDir:n=>ge.join(ke(),"transformers",n),transformerLogFile:n=>ge.join(ke(),"transformers",n,"current.log"),transformerPidFile:n=>ge.join(ke(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>ge.join(ke(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>ge.join(ke(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>ge.join(ke(),"prompt-history"),tuiLogFile:()=>ge.join(ke(),"tui.log"),shimWireLogFile:()=>ge.join(ke(),"shim-wire.log")}});import*as Ii from"fs/promises";function xi(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Ai(){try{let e=(await Ii.readFile(O.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Fr(){let n=await Ai();if(!n)throw new Error(`No service token found at ${O.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Ci(n){await Ii.mkdir(O.home(),{recursive:!0}),await Ii.writeFile(O.authToken(),n+`
2
+ var aS=Object.defineProperty;var Y=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ll=(n,e)=>{for(var t in e)aS(n,t,{get:e[t],enumerable:!0})};import*as ge from"path";import*as Nl from"os";function ct(n){let e=Nl.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function pS(){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 ke(){let n=process.env[fS];if(n&&n.length>0)return ge.resolve(n);let e=pS();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 ge.join(Nl.homedir(),".hydra-acp")}var fS,O,be=Y(()=>{"use strict";fS="HYDRA_ACP_HOME";O={home:ke,config:()=>ge.join(ke(),"config.json"),authToken:()=>ge.join(ke(),"auth-token"),remotes:()=>ge.join(ke(),"remotes.json"),pidFile:()=>ge.join(ke(),"daemon.pid"),logFile:()=>ge.join(ke(),"daemon.log"),currentLogFile:()=>ge.join(ke(),"current.log"),registryCache:()=>ge.join(ke(),"registry.json"),ttySessionDir:()=>ge.join(ke(),"tty"),ttySessionFile:n=>ge.join(ke(),"tty",n),agentsDir:()=>ge.join(ke(),"agents"),agentLogFile:n=>ge.join(ke(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>ge.join(ke(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>ge.join(ke(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>ge.join(ke(),"sessions"),sessionDir:n=>ge.join(ke(),"sessions",n),sessionFile:n=>ge.join(ke(),"sessions",n,"meta.json"),historyFile:n=>ge.join(ke(),"sessions",n,"history.jsonl"),historyArchiveFile:(n,e)=>ge.join(ke(),"sessions",n,`history.jsonl.${e}`),toolsDir:n=>ge.join(ke(),"sessions",n,"tools"),toolBlobFile:(n,e)=>ge.join(ke(),"sessions",n,"tools",e),queueFile:n=>ge.join(ke(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>ge.join(ke(),"sessions",".tombstones"),tombstoneAgentDir:n=>ge.join(ke(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>ge.join(ke(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>ge.join(ke(),"extensions"),extensionLogDir:n=>ge.join(ke(),"extensions",n),extensionLogFile:n=>ge.join(ke(),"extensions",n,"current.log"),extensionPidFile:n=>ge.join(ke(),"extensions",n,"extension.pid"),transformersDir:()=>ge.join(ke(),"transformers"),transformerLogDir:n=>ge.join(ke(),"transformers",n),transformerLogFile:n=>ge.join(ke(),"transformers",n,"current.log"),transformerPidFile:n=>ge.join(ke(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>ge.join(ke(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>ge.join(ke(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>ge.join(ke(),"prompt-history"),tuiLogFile:()=>ge.join(ke(),"tui.log"),shimWireLogFile:()=>ge.join(ke(),"shim-wire.log")}});import*as Ii from"fs/promises";function xi(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Ai(){try{let e=(await Ii.readFile(O.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Fr(){let n=await Ai();if(!n)throw new Error(`No service token found at ${O.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Ci(n){await Ii.mkdir(O.home(),{recursive:!0}),await Ii.writeFile(O.authToken(),n+`
3
3
  `,{encoding:"utf8",mode:384})}async function Zo(){let n=await Ai();if(n)return n;let e=xi();return await Ci(e),process.stderr.write(`hydra-acp: initialized ${O.authToken()} with a fresh service token.
4
- `),e}var Es=Y(()=>{"use strict";be()});import*as Et from"fs/promises";import*as Vp from"fs";import*as Fn from"path";import{randomBytes as fS}from"crypto";async function rn(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await pS(n,r,t)}async function pS(n,e,t={}){let s=await hS(n),r=mS(s);await Et.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${gS()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Et.writeFile(i,e,o),await Et.rename(i,s)}catch(o){throw await Et.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Vp.chmodSync(s,t.mode)}catch{}}async function hS(n){let e;try{e=await Et.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Et.readlink(n),s=Fn.isAbsolute(t)?t:Fn.resolve(Fn.dirname(n),t);try{let r=await Et.realpath(Fn.dirname(s));return Fn.join(r,Fn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function wn(n){let e;try{e=await Et.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function mS(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function gS(){return fS(4).toString("hex")}var Or=Y(()=>{"use strict"});import*as Zs from"fs/promises";import{homedir as Dl}from"os";import{z as W}from"zod";function Xp(n){return n.tui.inAppSelection??n.tui.mouse}function Zp(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function eh(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function wd(){return await CS(),await wn(O.config())??{}}async function CS(){let n;try{n=await Zs.lstat(O.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Zs.stat(O.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Zs.readlink(O.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${O.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function bd(){let n=await wd(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Zs.access(O.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${O.authToken()} and ${O.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ci(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await rn(O.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${O.config()} to ${O.authToken()}.
6
- `)}async function Ie(){return await bd(),Hl.parse(await wd())}async function Ps(n){await bd();let e=await wd();n(e),Hl.parse(e),await rn(O.config(),e,{mode:384})}async function ea(n,e){await Ps(t=>{let s=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};s[n]=e,t.tui=s})}async function Ri(n){await Ps(e=>{e.defaultAgent=n})}async function th(n,e){await Ps(t=>{let s=t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{};s[n]=e,t.defaultModels=s})}async function nh(n,e){await Ps(t=>{let s=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{};e===void 0?delete s[n]:s[n]={packageSpec:e},t.agentOverrides=s})}async function Ul(n,e){await Ps(t=>{let s=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete s[n]:s[n]=e,t.agents=s})}async function sh(n){await Ps(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function rh(){let n=await wd();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function tt(n){return n==="~"||n==="$HOME"?Dl():n.startsWith("~/")?Dl()+n.slice(1):n.startsWith("$HOME/")?Dl()+n.slice(5):n}var Gp,yS,On,wS,bS,vS,SS,kS,IS,Qp,xS,AS,Hl,Ge=Y(()=>{"use strict";be();Es();Or();Gp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",yS=W.object({cert:W.string(),key:W.string()}),On=55514,wS=W.object({host:W.string().default("127.0.0.1"),port:W.number().int().positive().default(On),logLevel:W.enum(["debug","info","warn","error"]).default("info"),tls:yS.optional(),sessionIdleTimeoutSeconds:W.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:W.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:W.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:W.number().int().positive().default(10),agentStderrTailBytes:W.number().int().positive().default(4096),publicHost:W.string().optional(),agentSyncIntervalMinutes:W.number().nonnegative().default(60),sessionGcIntervalMinutes:W.number().nonnegative().default(60),sessionGcMaxAgeDays:W.number().positive().default(2)}),bS=W.object({url:W.string().url().default(Gp),ttlHours:W.number().positive().default(24),pinned:W.boolean().default(!1)}),vS=W.object({name:W.string().optional(),description:W.string().optional(),command:W.string().optional(),args:W.array(W.string()).optional(),env:W.record(W.string()).optional()}),SS=W.object({packageSpec:W.string().optional()}),kS=W.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),IS=W.object({repaintThrottleMs:W.number().int().nonnegative().default(1e3),maxScrollbackLines:W.number().int().positive().default(1e4),mouse:W.boolean().default(!0),inAppSelection:W.boolean().optional(),selectionClipboard:W.enum(["primary","clipboard","both"]).default("both"),openFileCommand:W.union([W.string(),W.array(W.string())]).optional(),logMaxBytes:W.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:W.number().int().positive().default(32),progressIndicator:W.boolean().default(!0),defaultEnterAction:W.enum(["enqueue","amend"]).default("amend"),showThoughts:W.boolean().default(!0),ambiguousWidth:W.enum(["auto","narrow","wide"]).default("auto"),toolContent:W.enum(["inline","references"]).default("references"),diffContextLines:W.number().int().min(0).default(3),promptHistoryMaxEntries:W.number().int().positive().default(2e3),maxToolItems:W.number().int().nonnegative().default(5),maxPlanItems:W.number().int().nonnegative().default(5),showFileUpdates:W.enum(["none","edit","diff"]).default("edit"),sessionColumns:W.array(W.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:W.record(kS,W.object({command:W.union([W.string(),W.array(W.string())])})).default({})}),Qp=W.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),xS=W.object({command:W.array(W.string()).default([]),args:W.array(W.string()).default([]),env:W.record(W.string()).default({}),enabled:W.boolean().default(!0)}),AS=W.object({command:W.array(W.string()).default([]),args:W.array(W.string()).default([]),env:W.record(W.string()).default({}),enabled:W.boolean().default(!0)}),Hl=W.object({daemon:wS.default({}),registry:bS.default({url:Gp,ttlHours:24,pinned:!1}),agents:W.record(W.string(),vS).default({}),agentOverrides:W.record(W.string(),SS).default({}),defaultAgent:W.string().default("opencode"),defaultModels:W.record(W.string(),W.string()).default({}),synopsisAgent:W.string().optional(),synopsisModel:W.string().optional(),compaction:W.object({agent:W.string().optional(),model:W.string().optional(),tailK:W.number().int().nonnegative().default(20),maxIterations:W.number().int().positive().default(3),contextFraction:W.number().min(0).max(1).default(.5),hardCeilingFraction:W.number().min(0).max(1).default(.85),absoluteFallback:W.number().int().positive().default(12e4),idleBeforePromptMs:W.number().int().nonnegative().default(3e5),modelContextWindows:W.record(W.string(),W.number().int().positive()).default({})}).default({}),defaultCwd:W.string().default("~"),compressToolContent:W.boolean().default(!0),sessionListColdLimit:W.number().int().nonnegative().default(20),extensions:W.record(Qp,xS).default({}),transformers:W.record(Qp,AS).default({}),defaultTransformers:W.array(W.string()).default([]),npmRegistry:W.string().url().optional(),tui:IS.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function Lr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function jl(n){return{httpScheme:"https",wsScheme:"wss"}}function ql(n){if(typeof n!="string"||n.length===0)throw new Error("expected a hydra:// URL");if(!n.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${vd(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${vd(n)}`);let t=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(t){let d=Number(t[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${t[1]}`)}let s=RS(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${vd(n)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${vd(n)}`);let i=Lr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=On;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function ih(n){let e=n.port!==void 0&&n.port!==On?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function RS(n){try{return new URL(n)}catch{return null}}function vd(n){return n.length>80?`${n.slice(0,77)}...`:n}var ta=Y(()=>{"use strict";Ge()});function Br(n,e){return`${n}:${e}`}function oh(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function TS(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}async function ES(){let n=await wn(O.remotes());return n===void 0?{version:1,entries:{}}:PS(n)}function PS(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(t)){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 Wl(n){await rn(O.remotes(),n,{mode:384})}var Sd,zl=Y(()=>{"use strict";be();Or();Sd=class n{data;constructor(e){this.data=e}static async load(){let e=await ES(),t=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(oh(a,t)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Wl(i),new n(i)}get(e,t){let s=this.data.entries[Br(e,t)];if(s&&!oh(s,Date.now()))return s}async set(e,t,s){this.data.entries[Br(e,t)]=s,await Wl(this.data)}async delete(e,t){let s=Br(e,t);return s in this.data.entries?(delete this.data.entries[s],await Wl(this.data),!0):!1}list(){let e=[];for(let[t,s]of Object.entries(this.data.entries)){let r=TS(t);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Ti(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{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(),t(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),t(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):MS()}function MS(){return new Promise((n,e)=>{let t="";process.stdin.setEncoding("utf8");let s=i=>{t+=i;let o=t.indexOf(`
8
- `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),n(t.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 Kl=Y(()=>{"use strict"});import*as ah from"path";function ns(){let n=process.argv[1];if(!n)return"hydra-acp";let e=ah.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var na=Y(()=>{"use strict"});import*as kd from"fs/promises";async function Ms(){try{let n=await kd.readFile(O.pidFile(),"utf8"),e=JSON.parse(n);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(n){if(n.code==="ENOENT")return;throw n}}async function dh(n){await kd.writeFile(O.pidFile(),JSON.stringify(n)+`
9
- `,{encoding:"utf8",mode:384})}function Ln(n){try{return process.kill(n,0),!0}catch{return!1}}var Ei=Y(()=>{"use strict";be()});var hh={};Ll(hh,{_resetForTests:()=>HS,clearPin:()=>NS,fetchPeerFingerprint:()=>Ql,formatFingerprint:()=>Id,getPin:()=>Yl,installGlobalTlsTrust:()=>Xl,loadPinsFromStore:()=>Vl,setPin:()=>sa,sha256Hex:()=>Gl,wsTlsOptions:()=>ra});import{createHash as _S}from"crypto";import*as ch from"tls";import{Agent as $S,Dispatcher as FS,buildConnector as OS,getGlobalDispatcher as LS,setGlobalDispatcher as BS}from"undici";function sa(n,e,t){Nr.set(Br(n,e),lh(t))}function NS(n,e){Nr.delete(Br(n,e))}function Yl(n,e){return Nr.get(Br(n,e))}function Vl(n){Nr.clear();for(let e of n.list())e.entry.pinnedFingerprint&&sa(e.host,e.port,e.entry.pinnedFingerprint)}async function Ql(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=ch.connect({host:n,port:e,servername:n,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 ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${n}:${e} did not present a TLS certificate`));return}c(null,Gl(l.raw))}),o.once("error",l=>c(l))})}function Gl(n){return _S("sha256").update(n).digest("hex")}function Id(n){let e=lh(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function lh(n){return n.replace(/:/g,"").toLowerCase()}function Xl(){if(Jl)return;Jl=!0;let n=LS(),e=new $S({connect:OS({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>fh(s,r)})}),t=new FS;t.dispatch=(s,r)=>{let i=DS(s.origin);return(i&&uh(i)?e:n).dispatch(s,r)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(s=>Promise.all([e.destroy(s??null),n.destroy(s??null)]).then(()=>{})),BS(t)}function DS(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function uh(n){for(let e of Nr.keys())if(ph(e)?.host===n)return!0;return!1}function fh(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Gl(e.raw);for(let[s,r]of Nr.entries()){let i=ph(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${Id(t)})`)}function ph(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}function ra(n){return uh(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>fh(e,t)}:{autoSelectFamily:!0}}function HS(){Nr.clear(),Jl=!1}var Nr,Jl,ia=Y(()=>{"use strict";zl();Nr=new Map,Jl=!1});import*as wh from"os";async function Bt(n){let e=await Zo(),t=await Ms();if(t&&Ln(t.pid))return{baseUrl:`http://127.0.0.1:${t.loopbackPort}`,wsUrl:`ws://127.0.0.1:${t.loopbackPort}/acp`,token:e,display:`${t.host}:${t.port}`,isLocal:!0};let s=n.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=n.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Lr(r)}}function mh(n,e){let{httpScheme:t,wsScheme:s}=jl(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${s}://${n.host}:${n.port}/acp`,token:e,display:vh(n),isLocal:n.isLoopback}}async function bh(n,e={}){let t=e.fetchImpl??fetch,s=e.promptImpl??Ti,r=e.confirmImpl??WS,i=e.tlsHandshakeImpl??US,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&o){let w=await Ai();if(w)return qS(n,w)}let c=e.store??await Sd.load();Vl(c),Xl();let d=c.get(n.host,n.port);if(d)return d.pinnedFingerprint&&sa(n.host,n.port,d.pinnedFingerprint),mh(n,d.token);if(!a)throw new Zl(n.host,n.port);let l=vh(n),{httpScheme:u}=jl(n.host),f;if(u==="https"&&Yl(n.host,n.port)===void 0){let w=await i(n.host,n.port);if(w.kind==="untrusted"){let b=w.subject||w.issuer?`
4
+ `),e}var Ps=Y(()=>{"use strict";be()});import*as Et from"fs/promises";import*as Vp from"fs";import*as On from"path";import{randomBytes as hS}from"crypto";async function rn(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await mS(n,r,t)}async function mS(n,e,t={}){let s=await gS(n),r=yS(s);await Et.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${wS()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Et.writeFile(i,e,o),await Et.rename(i,s)}catch(o){throw await Et.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Vp.chmodSync(s,t.mode)}catch{}}async function gS(n){let e;try{e=await Et.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Et.readlink(n),s=On.isAbsolute(t)?t:On.resolve(On.dirname(n),t);try{let r=await Et.realpath(On.dirname(s));return On.join(r,On.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function wn(n){let e;try{e=await Et.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function yS(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function wS(){return hS(4).toString("hex")}var Or=Y(()=>{"use strict"});import*as Zs from"fs/promises";import{homedir as Dl}from"os";import{z as W}from"zod";function Xp(n){return n.tui.inAppSelection??n.tui.mouse}function Zp(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function eh(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function wd(){return await TS(),await wn(O.config())??{}}async function TS(){let n;try{n=await Zs.lstat(O.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Zs.stat(O.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Zs.readlink(O.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${O.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function bd(){let n=await wd(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Zs.access(O.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${O.authToken()} and ${O.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ci(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await rn(O.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${O.config()} to ${O.authToken()}.
6
+ `)}async function Ie(){return await bd(),Hl.parse(await wd())}async function Ms(n){await bd();let e=await wd();n(e),Hl.parse(e),await rn(O.config(),e,{mode:384})}async function ea(n,e){await Ms(t=>{let s=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};s[n]=e,t.tui=s})}async function Ri(n){await Ms(e=>{e.defaultAgent=n})}async function th(n,e){await Ms(t=>{let s=t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{};s[n]=e,t.defaultModels=s})}async function nh(n,e){await Ms(t=>{let s=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{};e===void 0?delete s[n]:s[n]={packageSpec:e},t.agentOverrides=s})}async function Ul(n,e){await Ms(t=>{let s=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete s[n]:s[n]=e,t.agents=s})}async function sh(n){await Ms(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function rh(){let n=await wd();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function tt(n){return n==="~"||n==="$HOME"?Dl():n.startsWith("~/")?Dl()+n.slice(1):n.startsWith("$HOME/")?Dl()+n.slice(5):n}var Gp,bS,Ln,vS,SS,kS,IS,xS,AS,Qp,CS,RS,Hl,Ge=Y(()=>{"use strict";be();Ps();Or();Gp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",bS=W.object({cert:W.string(),key:W.string()}),Ln=55514,vS=W.object({host:W.string().default("127.0.0.1"),port:W.number().int().positive().default(Ln),logLevel:W.enum(["debug","info","warn","error"]).default("info"),tls:bS.optional(),sessionIdleTimeoutSeconds:W.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:W.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:W.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:W.number().int().positive().default(10),agentStderrTailBytes:W.number().int().positive().default(4096),publicHost:W.string().optional(),agentSyncIntervalMinutes:W.number().nonnegative().default(60),sessionGcIntervalMinutes:W.number().nonnegative().default(60),sessionGcMaxAgeDays:W.number().positive().default(2)}),SS=W.object({url:W.string().url().default(Gp),ttlHours:W.number().positive().default(24),pinned:W.boolean().default(!1)}),kS=W.object({name:W.string().optional(),description:W.string().optional(),command:W.string().optional(),args:W.array(W.string()).optional(),env:W.record(W.string()).optional()}),IS=W.object({packageSpec:W.string().optional()}),xS=W.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),AS=W.object({repaintThrottleMs:W.number().int().nonnegative().default(1e3),maxScrollbackLines:W.number().int().positive().default(1e4),mouse:W.boolean().default(!0),inAppSelection:W.boolean().optional(),selectionClipboard:W.enum(["primary","clipboard","both"]).default("both"),openFileCommand:W.union([W.string(),W.array(W.string())]).optional(),logMaxBytes:W.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:W.number().int().positive().default(32),progressIndicator:W.boolean().default(!0),defaultEnterAction:W.enum(["enqueue","amend"]).default("amend"),showThoughts:W.boolean().default(!0),ambiguousWidth:W.enum(["auto","narrow","wide"]).default("auto"),toolContent:W.enum(["inline","references"]).default("references"),diffContextLines:W.number().int().min(0).default(3),promptHistoryMaxEntries:W.number().int().positive().default(2e3),maxToolItems:W.number().int().nonnegative().default(5),maxPlanItems:W.number().int().nonnegative().default(5),showFileUpdates:W.enum(["none","edit","diff"]).default("edit"),sessionColumns:W.array(W.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:W.record(xS,W.object({command:W.union([W.string(),W.array(W.string())])})).default({})}),Qp=W.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),CS=W.object({command:W.array(W.string()).default([]),args:W.array(W.string()).default([]),env:W.record(W.string()).default({}),enabled:W.boolean().default(!0)}),RS=W.object({command:W.array(W.string()).default([]),args:W.array(W.string()).default([]),env:W.record(W.string()).default({}),enabled:W.boolean().default(!0)}),Hl=W.object({daemon:vS.default({}),registry:SS.default({url:Gp,ttlHours:24,pinned:!1}),agents:W.record(W.string(),kS).default({}),agentOverrides:W.record(W.string(),IS).default({}),defaultAgent:W.string().default("opencode"),defaultModels:W.record(W.string(),W.string()).default({}),synopsisAgent:W.string().optional(),synopsisModel:W.string().optional(),compaction:W.object({agent:W.string().optional(),model:W.string().optional(),tailK:W.number().int().nonnegative().default(20),maxIterations:W.number().int().positive().default(3),contextFraction:W.number().min(0).max(1).default(.5),hardCeilingFraction:W.number().min(0).max(1).default(.85),absoluteFallback:W.number().int().positive().default(12e4),idleBeforePromptMs:W.number().int().nonnegative().default(3e5),modelContextWindows:W.record(W.string(),W.number().int().positive()).default({})}).default({}),defaultCwd:W.string().default("~"),compressToolContent:W.boolean().default(!0),sessionListColdLimit:W.number().int().nonnegative().default(20),extensions:W.record(Qp,CS).default({}),transformers:W.record(Qp,RS).default({}),defaultTransformers:W.array(W.string()).default([]),npmRegistry:W.string().url().optional(),tui:AS.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function Lr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function jl(n){return{httpScheme:"https",wsScheme:"wss"}}function ql(n){if(typeof n!="string"||n.length===0)throw new Error("expected a hydra:// URL");if(!n.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${vd(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${vd(n)}`);let t=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(t){let d=Number(t[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${t[1]}`)}let s=ES(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${vd(n)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${vd(n)}`);let i=Lr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=Ln;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function ih(n){let e=n.port!==void 0&&n.port!==Ln?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function ES(n){try{return new URL(n)}catch{return null}}function vd(n){return n.length>80?`${n.slice(0,77)}...`:n}var ta=Y(()=>{"use strict";Ge()});function Br(n,e){return`${n}:${e}`}function oh(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function PS(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}async function MS(){let n=await wn(O.remotes());return n===void 0?{version:1,entries:{}}:_S(n)}function _S(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(t)){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 Wl(n){await rn(O.remotes(),n,{mode:384})}var Sd,zl=Y(()=>{"use strict";be();Or();Sd=class n{data;constructor(e){this.data=e}static async load(){let e=await MS(),t=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(oh(a,t)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Wl(i),new n(i)}get(e,t){let s=this.data.entries[Br(e,t)];if(s&&!oh(s,Date.now()))return s}async set(e,t,s){this.data.entries[Br(e,t)]=s,await Wl(this.data)}async delete(e,t){let s=Br(e,t);return s in this.data.entries?(delete this.data.entries[s],await Wl(this.data),!0):!1}list(){let e=[];for(let[t,s]of Object.entries(this.data.entries)){let r=PS(t);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Ti(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{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(),t(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),t(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):$S()}function $S(){return new Promise((n,e)=>{let t="";process.stdin.setEncoding("utf8");let s=i=>{t+=i;let o=t.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),n(t.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 Kl=Y(()=>{"use strict"});import*as ah from"path";function ns(){let n=process.argv[1];if(!n)return"hydra-acp";let e=ah.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var na=Y(()=>{"use strict"});import*as kd from"fs/promises";async function ss(){try{let n=await kd.readFile(O.pidFile(),"utf8"),e=JSON.parse(n);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(n){if(n.code==="ENOENT")return;throw n}}async function dh(n){await kd.writeFile(O.pidFile(),JSON.stringify(n)+`
9
+ `,{encoding:"utf8",mode:384})}function bn(n){try{return process.kill(n,0),!0}catch{return!1}}var Ei=Y(()=>{"use strict";be()});var hh={};Ll(hh,{_resetForTests:()=>jS,clearPin:()=>HS,fetchPeerFingerprint:()=>Ql,formatFingerprint:()=>Id,getPin:()=>Yl,installGlobalTlsTrust:()=>Xl,loadPinsFromStore:()=>Vl,setPin:()=>sa,sha256Hex:()=>Gl,wsTlsOptions:()=>ra});import{createHash as FS}from"crypto";import*as ch from"tls";import{Agent as OS,Dispatcher as LS,buildConnector as BS,getGlobalDispatcher as NS,setGlobalDispatcher as DS}from"undici";function sa(n,e,t){Nr.set(Br(n,e),lh(t))}function HS(n,e){Nr.delete(Br(n,e))}function Yl(n,e){return Nr.get(Br(n,e))}function Vl(n){Nr.clear();for(let e of n.list())e.entry.pinnedFingerprint&&sa(e.host,e.port,e.entry.pinnedFingerprint)}async function Ql(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=ch.connect({host:n,port:e,servername:n,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 ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${n}:${e} did not present a TLS certificate`));return}c(null,Gl(l.raw))}),o.once("error",l=>c(l))})}function Gl(n){return FS("sha256").update(n).digest("hex")}function Id(n){let e=lh(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function lh(n){return n.replace(/:/g,"").toLowerCase()}function Xl(){if(Jl)return;Jl=!0;let n=NS(),e=new OS({connect:BS({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>fh(s,r)})}),t=new LS;t.dispatch=(s,r)=>{let i=US(s.origin);return(i&&uh(i)?e:n).dispatch(s,r)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(s=>Promise.all([e.destroy(s??null),n.destroy(s??null)]).then(()=>{})),DS(t)}function US(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function uh(n){for(let e of Nr.keys())if(ph(e)?.host===n)return!0;return!1}function fh(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Gl(e.raw);for(let[s,r]of Nr.entries()){let i=ph(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${Id(t)})`)}function ph(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}function ra(n){return uh(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>fh(e,t)}:{autoSelectFamily:!0}}function jS(){Nr.clear(),Jl=!1}var Nr,Jl,ia=Y(()=>{"use strict";zl();Nr=new Map,Jl=!1});import*as wh from"os";async function Bt(n){let e=await Zo(),t=await ss();if(t&&bn(t.pid))return{baseUrl:`http://127.0.0.1:${t.loopbackPort}`,wsUrl:`ws://127.0.0.1:${t.loopbackPort}/acp`,token:e,display:`${t.host}:${t.port}`,isLocal:!0};let s=n.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=n.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Lr(r)}}function mh(n,e){let{httpScheme:t,wsScheme:s}=jl(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${s}://${n.host}:${n.port}/acp`,token:e,display:vh(n),isLocal:n.isLoopback}}async function bh(n,e={}){let t=e.fetchImpl??fetch,s=e.promptImpl??Ti,r=e.confirmImpl??KS,i=e.tlsHandshakeImpl??qS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&o){let w=await Ai();if(w)return zS(n,w)}let c=e.store??await Sd.load();Vl(c),Xl();let d=c.get(n.host,n.port);if(d)return d.pinnedFingerprint&&sa(n.host,n.port,d.pinnedFingerprint),mh(n,d.token);if(!a)throw new Zl(n.host,n.port);let l=vh(n),{httpScheme:u}=jl(n.host),f;if(u==="https"&&Yl(n.host,n.port)===void 0){let w=await i(n.host,n.port);if(w.kind==="untrusted"){let b=w.subject||w.issuer?`
10
10
  subject: ${w.subject??"(unknown)"}
11
11
  issuer: ${w.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
12
  sha256: ${Id(w.fingerprint)}${b}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);sa(n.host,n.port,w.fingerprint),f=w.fingerprint}else if(w.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${w.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${n.host}:${n.port}`,m=await t(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:yh()})});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(n.host,n.port,{token:y.session_token,expiresAt:y.expires_at,label:yh(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),mh(n,y.session_token)}async function US(n,e){let t=await jS(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await Ql(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function jS(n,e,t=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:n,port:e,servername:n,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);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?gh(p.subject):void 0,issuer:p?.issuer?gh(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 gh(n){if(!n)return"";let e=[];for(let[t,s]of Object.entries(n)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${t}=${r}`)}return e.join(", ")}async function qS(n,e){let t=await Ms(),r=t&&Ln(t.pid)?t.loopbackPort:n.port,i=n.port===On?n.host:`${n.host}:${n.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 WS(n){return process.stdout.write(n),new Promise(e=>{let t="",s=r=>{t+=r.toString("utf8");let i=t.indexOf(`
14
- `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=t.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function yh(){try{let n=wh.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function vh(n){return n.port===On?n.host:`${n.host}:${n.port}`}var Zl,Dr=Y(()=>{"use strict";Ge();Es();ta();zl();Kl();na();Ei();ia();ta();Zl=class extends Error{host;port;constructor(e,t){let s=t===On?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${ns()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as zS,renameSync as KS,statSync as JS}from"fs";function Ih(n){kh=n}function ie(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?O.tuiLogFile():e;if(t.length!==0)try{YS(t);let s=JSON.stringify({t:new Date().toISOString(),...n});zS(t,`${s}
15
- `)}catch{}}function YS(n){try{if(JS(n).size<kh)return;KS(n,`${n}.0`)}catch{}}var kh,Hr=Y(()=>{"use strict";be();kh=5*1024*1024});import*as Lh from"fs";import*as Nt from"fs/promises";import*as er from"path";import{spawn as Bh}from"child_process";import{Readable as ek}from"stream";function bn(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function iu(n,e=bn()){if(e)return n[e]}function ou(n){Pi=n??(e=>process.stderr.write(e+`
16
- `))}async function Nh(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${bn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=bn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=O.agentInstallDir(n.agentId,e,n.version),s=er.resolve(t,n.target.cmd);if(await ru(s))return s;if(await tk({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await ru(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Nt.chmod(s,493).catch(()=>{}),s}async function tk(n){await Nt.mkdir(er.dirname(n.installDir),{recursive:!0});let e=await Nt.mkdtemp(`${n.installDir}.partial-`);try{Pi(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await nk({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Pi(`hydra-acp: extracting ${n.agentId}`),Mi(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await rk(t,e),await Nt.unlink(t).catch(()=>{});try{await Nt.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await ru(n.installDir)){await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Mi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Pi(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Mi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Mi(n,e){if(n)try{n(e)}catch{}}async function nk(n){let e=sk(n.url),t=er.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Lh.createWriteStream(t),o=ek.fromWeb(s.body);Mi(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.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,Mi(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Pi(Oh(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),Pi(Oh(n.agentId,a,r,!0)),Mi(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Oh(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function sk(n){let e=new URL(n);return er.posix.basename(e.pathname)||"archive"}async function rk(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await su("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ik("unzip")){await su("unzip",["-q",n,"-d",e]);return}await su("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function su(n,e){return new Promise((t,s)=>{let r=Bh(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function ik(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Bh(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function ru(n){try{return await Nt.access(n),!0}catch{return!1}}var Pi,_i=Y(()=>{"use strict";be();Pi=n=>{process.stderr.write(n+`
17
- `)}});var q,Td=Y(()=>{"use strict";q={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 Ue}from"zod";var Kh,Sk,Jh,Yh,Vh,fu=Y(()=>{"use strict";Kh=Ue.object({protocolVersion:Ue.number().optional(),clientCapabilities:Ue.record(Ue.unknown()).optional(),clientInfo:Ue.object({name:Ue.string(),version:Ue.string().optional()}).optional()}),Sk=Ue.enum(["full","pending_only","none","after_message"]),Jh=Ue.object({cwd:Ue.string(),mcpServers:Ue.array(Ue.unknown()).optional(),_meta:Ue.record(Ue.unknown()).optional()}),Yh=Ue.object({upstreamSessionId:Ue.string(),agentId:Ue.string(),cwd:Ue.string(),title:Ue.string().optional(),agentArgs:Ue.array(Ue.string()).optional()}),Vh=Ue.object({sessionId:Ue.string(),historyPolicy:Sk.default("full"),afterMessageId:Ue.string().optional(),clientId:Ue.string().optional(),clientInfo:Ue.object({name:Ue.string(),version:Ue.string().optional()}).optional(),_meta:Ue.record(Ue.unknown()).optional()})});import{z as pe}from"zod";function Ed(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function Xh(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:aa(n._meta,Ed(n))};return n.title!==void 0&&(e.title=n.title),e}var Qh,Gh,pu,EM,kk,PM,hu=Y(()=>{"use strict";Pd();Qh=pe.object({sessionId:pe.string()}),Gh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),pu=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),EM=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:pu.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),kk=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),PM=pe.object({sessions:pe.array(kk),nextCursor:pe.string().optional()})});function Ik(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function an(n){if(!n)return{};let e=n[Mt];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=Yh.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=pu.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let 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(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Ik(t.env);r!==void 0&&(s.env=r)}return s}function aa(n,e){return{...n??{},[Mt]:e}}var Mt,Pd=Y(()=>{"use strict";fu();hu();Mt="hydra-acp"});import{z as ne}from"zod";var Zh,Md,em,LM,BM,NM,tm,DM,nm,HM,sm,UM,jM,rm=Y(()=>{"use strict";Zh=ne.object({sessionId:ne.string(),prompt:ne.array(ne.unknown()),_meta:ne.record(ne.unknown()).optional()}),Md=ne.object({sessionId:ne.string()}),em=ne.object({clientId:ne.string(),name:ne.string().optional(),version:ne.string().optional()}),LM=ne.object({sessionId:ne.string(),messageId:ne.string(),originator:em,prompt:ne.array(ne.unknown()),position:ne.number().int().nonnegative(),queueDepth:ne.number().int().positive(),enqueuedAt:ne.number()}),BM=ne.object({sessionId:ne.string(),messageId:ne.string(),prompt:ne.array(ne.unknown())}),NM=ne.object({sessionId:ne.string(),messageId:ne.string(),reason:ne.enum(["started","cancelled","abandoned"])}),tm=ne.object({sessionId:ne.string(),messageId:ne.string()}),DM=ne.object({cancelled:ne.boolean(),reason:ne.enum(["ok","not_found","already_running"])}),nm=ne.object({sessionId:ne.string(),messageId:ne.string(),prompt:ne.array(ne.unknown())}),HM=ne.object({updated:ne.boolean(),reason:ne.enum(["ok","not_found","already_running"])}),sm=ne.object({sessionId:ne.string(),targetMessageId:ne.string(),prompt:ne.array(ne.unknown()),replaceQueue:ne.boolean().optional(),onTargetCompleted:ne.enum(["reject","send_anyway"]).optional()}),UM=ne.object({amended:ne.boolean(),reason:ne.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ne.string().optional()}),jM=ne.object({sessionId:ne.string(),cancelledMessageId:ne.string(),newMessageId:ne.string(),prompt:ne.array(ne.unknown()),originator:em,amendedAt:ne.number()})});import{z as tr}from"zod";var im,_d,Oi,om=Y(()=>{"use strict";im=tr.object({agentId:tr.string(),version:tr.string(),source:tr.enum(["binary","npm"]),phase:tr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:tr.number().optional(),totalBytes:tr.number().optional(),packageSpec:tr.string().optional()}),_d="hydra-acp/agents/install_progress",Oi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var _t=Y(()=>{"use strict";Td();fu();Pd();hu();rm();om()});import{nanoid as xk}from"nanoid";var mu,zt,jr=Y(()=>{"use strict";_t();mu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},zt=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new mu;let s=xk(),r={jsonrpc:"2.0",id:s,method:e,params:t},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,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:q.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??q.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}}});import*as dm from"os";function Li(){return dm.hostname()}function gu(){let n=new Set;n.add(Li());let e=process.env.HYDRA_ACP_LOCAL_HOSTS;if(e)for(let t of e.split(",")){let s=t.trim();s&&n.add(s)}return n}var Od=Y(()=>{"use strict"});async function Bi(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(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:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Ni(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var yu=Y(()=>{"use strict"});import*as lm from"fs/promises";function Lk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ek,Pk,Di,Mk,_k,$k,Fk,Ok,cm,Ld,um=Y(()=>{"use strict";Ek=64*1024*1024,Pk=1*1024*1024,Di=64*1024,Mk=6e4,_k=100,$k=1e3,Fk=64*1024,Ok=256*1024,cm=20;Ld=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??Ek,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Pk,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Di));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 t=Math.max(0,Math.min(e,Di)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Di)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Mk));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Lk(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??_k,$k)),f=Math.max(1,Math.min(e.maxBytes??Fk,Ok)),p=Math.max(0,Math.min(e.contextBefore??0,cm)),h=Math.max(0,Math.min(e.contextAfter??0,cm)),m=[],y=[],w=[],b=0,S=!1,k=0,A=0,E=(_,F)=>{for(let G of w)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:_,line:F}),G.remaining--,b+=F.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(d.test(F)!==l&&m.length<u){let G={cursor:_,line:F};if(p>0&&y.length>0){G.before=y.slice();for(let X of G.before)b+=X.line.length}b+=F.length,m.push(G),h>0&&w.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:_,line:F});y.length>p;)y.shift();let N=m.length>=u&&w.length===0,j=b>=f;return N||j};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let F=o.subarray(k,_).toString("utf8"),B=r+k;if(k=_+1,A=k,E(B,F)){S=!0;break}}if(!S&&k<o.length&&this.closed){let _=o.subarray(k).toString("utf8"),F=r+k;E(F,_)&&(S=!0),A=o.length}let P=Math.min(r+A,this.writeCursor),H={matches:m,truncated:S,nextCursor:P,scannedBytes:A};return i>0&&(H.gap=i),this.closed&&P>=this.writeCursor&&(H.eof=!0),H}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>lm.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Hi,f_,fm=Y(()=>{"use strict";Hi=[{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:"fork",name:"hydra fork",argsHint:"[verbatim]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass 'verbatim' to slice at the last completed turn instead)"},{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."}],f_=new Map(Hi.map(n=>[n.verb,n]))});function pm(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Ui(n,e){return wu(n,e.map(t=>t.modelId))}function wu(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=pm(n),s=e.filter(i=>pm(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}var Bd=Y(()=>{"use strict"});function hm(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=bu(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=t.get(l);u?u.push(...d.content):t.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=bu(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?Nk(r,i.outIndex,Bk(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&&t.has(u)?Dk(c,t.get(u)??[]):c;u!==void 0&&s.has(u)&&!Hk(f)&&(f=Uk(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 bu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Bk(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Nk(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Dk(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Hk(n){let t=bu(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Uk(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var mm=Y(()=>{"use strict"});function ji(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=Su(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=ku(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(vu(c))):d==="turn_complete"&&i()}return i(),Kk(s.join(`
18
- `),t)}function vu(n){let e=qk(n),t=Wk(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function qk(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Wk(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of jk){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${zk(r,200)}`)}return t}function Su(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function ku(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function zk(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Kk(n,e){if(n.length<=e)return n;let t=n.split(`
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);sa(n.host,n.port,w.fingerprint),f=w.fingerprint}else if(w.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${w.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${n.host}:${n.port}`,m=await t(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:yh()})});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(n.host,n.port,{token:y.session_token,expiresAt:y.expires_at,label:yh(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),mh(n,y.session_token)}async function qS(n,e){let t=await WS(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await Ql(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function WS(n,e,t=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:n,port:e,servername:n,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);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?gh(p.subject):void 0,issuer:p?.issuer?gh(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 gh(n){if(!n)return"";let e=[];for(let[t,s]of Object.entries(n)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${t}=${r}`)}return e.join(", ")}async function zS(n,e){let t=await ss(),r=t&&bn(t.pid)?t.loopbackPort:n.port,i=n.port===Ln?n.host:`${n.host}:${n.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 KS(n){return process.stdout.write(n),new Promise(e=>{let t="",s=r=>{t+=r.toString("utf8");let i=t.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=t.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function yh(){try{let n=wh.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function vh(n){return n.port===Ln?n.host:`${n.host}:${n.port}`}var Zl,Dr=Y(()=>{"use strict";Ge();Ps();ta();zl();Kl();na();Ei();ia();ta();Zl=class extends Error{host;port;constructor(e,t){let s=t===Ln?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${ns()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as JS,renameSync as YS,statSync as VS}from"fs";function Ih(n){kh=n}function ie(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?O.tuiLogFile():e;if(t.length!==0)try{QS(t);let s=JSON.stringify({t:new Date().toISOString(),...n});JS(t,`${s}
15
+ `)}catch{}}function QS(n){try{if(VS(n).size<kh)return;YS(n,`${n}.0`)}catch{}}var kh,Hr=Y(()=>{"use strict";be();kh=5*1024*1024});import*as Lh from"fs";import*as Nt from"fs/promises";import*as er from"path";import{spawn as Bh}from"child_process";import{Readable as nk}from"stream";function vn(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function iu(n,e=vn()){if(e)return n[e]}function ou(n){Pi=n??(e=>process.stderr.write(e+`
16
+ `))}async function Nh(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${vn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=vn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=O.agentInstallDir(n.agentId,e,n.version),s=er.resolve(t,n.target.cmd);if(await ru(s))return s;if(await sk({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await ru(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Nt.chmod(s,493).catch(()=>{}),s}async function sk(n){await Nt.mkdir(er.dirname(n.installDir),{recursive:!0});let e=await Nt.mkdtemp(`${n.installDir}.partial-`);try{Pi(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await rk({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Pi(`hydra-acp: extracting ${n.agentId}`),Mi(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await ok(t,e),await Nt.unlink(t).catch(()=>{});try{await Nt.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await ru(n.installDir)){await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Mi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Pi(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Mi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Mi(n,e){if(n)try{n(e)}catch{}}async function rk(n){let e=ik(n.url),t=er.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Lh.createWriteStream(t),o=nk.fromWeb(s.body);Mi(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.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,Mi(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Pi(Oh(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),Pi(Oh(n.agentId,a,r,!0)),Mi(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Oh(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function ik(n){let e=new URL(n);return er.posix.basename(e.pathname)||"archive"}async function ok(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await su("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ak("unzip")){await su("unzip",["-q",n,"-d",e]);return}await su("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function su(n,e){return new Promise((t,s)=>{let r=Bh(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function ak(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Bh(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function ru(n){try{return await Nt.access(n),!0}catch{return!1}}var Pi,_i=Y(()=>{"use strict";be();Pi=n=>{process.stderr.write(n+`
17
+ `)}});var q,Td=Y(()=>{"use strict";q={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 Ue}from"zod";var Kh,Ik,Jh,Yh,Vh,fu=Y(()=>{"use strict";Kh=Ue.object({protocolVersion:Ue.number().optional(),clientCapabilities:Ue.record(Ue.unknown()).optional(),clientInfo:Ue.object({name:Ue.string(),version:Ue.string().optional()}).optional()}),Ik=Ue.enum(["full","pending_only","none","after_message"]),Jh=Ue.object({cwd:Ue.string(),mcpServers:Ue.array(Ue.unknown()).optional(),_meta:Ue.record(Ue.unknown()).optional()}),Yh=Ue.object({upstreamSessionId:Ue.string(),agentId:Ue.string(),cwd:Ue.string(),title:Ue.string().optional(),agentArgs:Ue.array(Ue.string()).optional()}),Vh=Ue.object({sessionId:Ue.string(),historyPolicy:Ik.default("full"),afterMessageId:Ue.string().optional(),clientId:Ue.string().optional(),clientInfo:Ue.object({name:Ue.string(),version:Ue.string().optional()}).optional(),_meta:Ue.record(Ue.unknown()).optional()})});import{z as pe}from"zod";function Ed(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function Xh(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:aa(n._meta,Ed(n))};return n.title!==void 0&&(e.title=n.title),e}var Qh,Gh,pu,$M,xk,FM,hu=Y(()=>{"use strict";Pd();Qh=pe.object({sessionId:pe.string()}),Gh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),pu=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),$M=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:pu.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),xk=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),FM=pe.object({sessions:pe.array(xk),nextCursor:pe.string().optional()})});function Ak(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function an(n){if(!n)return{};let e=n[Mt];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=Yh.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=pu.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let 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(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Ak(t.env);r!==void 0&&(s.env=r)}return s}function aa(n,e){return{...n??{},[Mt]:e}}var Mt,Pd=Y(()=>{"use strict";fu();hu();Mt="hydra-acp"});import{z as ne}from"zod";var Zh,Md,em,HM,UM,jM,tm,qM,nm,WM,sm,zM,KM,rm=Y(()=>{"use strict";Zh=ne.object({sessionId:ne.string(),prompt:ne.array(ne.unknown()),_meta:ne.record(ne.unknown()).optional()}),Md=ne.object({sessionId:ne.string()}),em=ne.object({clientId:ne.string(),name:ne.string().optional(),version:ne.string().optional()}),HM=ne.object({sessionId:ne.string(),messageId:ne.string(),originator:em,prompt:ne.array(ne.unknown()),position:ne.number().int().nonnegative(),queueDepth:ne.number().int().positive(),enqueuedAt:ne.number()}),UM=ne.object({sessionId:ne.string(),messageId:ne.string(),prompt:ne.array(ne.unknown())}),jM=ne.object({sessionId:ne.string(),messageId:ne.string(),reason:ne.enum(["started","cancelled","abandoned"])}),tm=ne.object({sessionId:ne.string(),messageId:ne.string()}),qM=ne.object({cancelled:ne.boolean(),reason:ne.enum(["ok","not_found","already_running"])}),nm=ne.object({sessionId:ne.string(),messageId:ne.string(),prompt:ne.array(ne.unknown())}),WM=ne.object({updated:ne.boolean(),reason:ne.enum(["ok","not_found","already_running"])}),sm=ne.object({sessionId:ne.string(),targetMessageId:ne.string(),prompt:ne.array(ne.unknown()),replaceQueue:ne.boolean().optional(),onTargetCompleted:ne.enum(["reject","send_anyway"]).optional()}),zM=ne.object({amended:ne.boolean(),reason:ne.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ne.string().optional()}),KM=ne.object({sessionId:ne.string(),cancelledMessageId:ne.string(),newMessageId:ne.string(),prompt:ne.array(ne.unknown()),originator:em,amendedAt:ne.number()})});import{z as tr}from"zod";var im,_d,Oi,om=Y(()=>{"use strict";im=tr.object({agentId:tr.string(),version:tr.string(),source:tr.enum(["binary","npm"]),phase:tr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:tr.number().optional(),totalBytes:tr.number().optional(),packageSpec:tr.string().optional()}),_d="hydra-acp/agents/install_progress",Oi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var _t=Y(()=>{"use strict";Td();fu();Pd();hu();rm();om()});import{nanoid as Ck}from"nanoid";var mu,zt,jr=Y(()=>{"use strict";_t();mu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},zt=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new mu;let s=Ck(),r={jsonrpc:"2.0",id:s,method:e,params:t},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,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:q.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??q.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}}});import*as dm from"os";function Li(){return dm.hostname()}function gu(){let n=new Set;n.add(Li());let e=process.env.HYDRA_ACP_LOCAL_HOSTS;if(e)for(let t of e.split(",")){let s=t.trim();s&&n.add(s)}return n}var Od=Y(()=>{"use strict"});async function Bi(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(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:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Ni(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var yu=Y(()=>{"use strict"});import*as lm from"fs/promises";function Nk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Mk,_k,Di,$k,Fk,Ok,Lk,Bk,cm,Ld,um=Y(()=>{"use strict";Mk=64*1024*1024,_k=1*1024*1024,Di=64*1024,$k=6e4,Fk=100,Ok=1e3,Lk=64*1024,Bk=256*1024,cm=20;Ld=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??Mk,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(_k,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Di));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 t=Math.max(0,Math.min(e,Di)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Di)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,$k));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Nk(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Fk,Ok)),f=Math.max(1,Math.min(e.maxBytes??Lk,Bk)),p=Math.max(0,Math.min(e.contextBefore??0,cm)),h=Math.max(0,Math.min(e.contextAfter??0,cm)),m=[],y=[],w=[],b=0,S=!1,k=0,A=0,E=(_,F)=>{for(let G of w)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:_,line:F}),G.remaining--,b+=F.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(d.test(F)!==l&&m.length<u){let G={cursor:_,line:F};if(p>0&&y.length>0){G.before=y.slice();for(let X of G.before)b+=X.line.length}b+=F.length,m.push(G),h>0&&w.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:_,line:F});y.length>p;)y.shift();let N=m.length>=u&&w.length===0,j=b>=f;return N||j};for(let _=0;_<o.length;_++){if(o[_]!==10)continue;let F=o.subarray(k,_).toString("utf8"),B=r+k;if(k=_+1,A=k,E(B,F)){S=!0;break}}if(!S&&k<o.length&&this.closed){let _=o.subarray(k).toString("utf8"),F=r+k;E(F,_)&&(S=!0),A=o.length}let P=Math.min(r+A,this.writeCursor),H={matches:m,truncated:S,nextCursor:P,scannedBytes:A};return i>0&&(H.gap=i),this.closed&&P>=this.writeCursor&&(H.eof=!0),H}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>lm.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Hi,g_,fm=Y(()=>{"use strict";Hi=[{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:"fork",name:"hydra fork",argsHint:"[verbatim]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass 'verbatim' to slice at the last completed turn instead)"},{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."}],g_=new Map(Hi.map(n=>[n.verb,n]))});function pm(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Ui(n,e){return wu(n,e.map(t=>t.modelId))}function wu(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=pm(n),s=e.filter(i=>pm(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}var Bd=Y(()=>{"use strict"});function hm(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=bu(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=t.get(l);u?u.push(...d.content):t.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=bu(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?Hk(r,i.outIndex,Dk(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&&t.has(u)?Uk(c,t.get(u)??[]):c;u!==void 0&&s.has(u)&&!jk(f)&&(f=qk(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 bu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Dk(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Hk(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Uk(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function jk(n){let t=bu(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function qk(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var mm=Y(()=>{"use strict"});function ji(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=Su(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=ku(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(vu(c))):d==="turn_complete"&&i()}return i(),Yk(s.join(`
18
+ `),t)}function vu(n){let e=zk(n),t=Kk(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function zk(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Kk(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Wk){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Jk(r,200)}`)}return t}function Su(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function ku(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Jk(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Yk(n,e){if(n.length<=e)return n;let t=n.split(`
19
19
  `);for(;t.length>0;){let s=gm+t.join(`
20
- `);if(s.length<=e)return s;t.shift()}return gm}var gm,jk,Nd=Y(()=>{"use strict";gm=`[older history truncated]
21
- `,jk=["file_path","filePath","path","command","pattern","query"]});function Iu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??ym}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let o=da("Open threads",t.open_threads);o.length>0&&e.push(o);let a=da("Decisions",t.decisions);a.length>0&&e.push(a);let c=da("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let d=da("Unresolved errors",t.unresolved_errors);d.length>0&&e.push(d);let l=da("Tool state",t.tool_state);l.length>0&&e.push(l);let u=wm(t.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=wm(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??ym}`);let{closedText:s,openText:r,keptCount:i}=Jk(n.tail,n.tailK,n.watermark??0,n.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(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
20
+ `);if(s.length<=e)return s;t.shift()}return gm}var gm,Wk,Nd=Y(()=>{"use strict";gm=`[older history truncated]
21
+ `,Wk=["file_path","filePath","path","command","pattern","query"]});function Iu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??ym}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let o=da("Open threads",t.open_threads);o.length>0&&e.push(o);let a=da("Decisions",t.decisions);a.length>0&&e.push(a);let c=da("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let d=da("Unresolved errors",t.unresolved_errors);d.length>0&&e.push(d);let l=da("Tool state",t.tool_state);l.length>0&&e.push(l);let u=wm(t.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=wm(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??ym}`);let{closedText:s,openText:r,keptCount:i}=Vk(n.tail,n.tailK,n.watermark??0,n.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(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
22
22
  `)}function da(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
23
- `)}`}function wm(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Jk(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Yk(n),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=t).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?bm(a):"",d=i?bm([i]):"";return{closedText:c,openText:d,keptCount:o}}function bm(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
24
- `)}function Yk(n){let e=[],t=null;for(let r=0;r<n.length;r++){let i=n[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")t!==null&&t.user.length>0&&e.push(t),t={user:Su(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&t!==null){let d=ku(a.content);d.length>0&&(t.agent+=d)}else c==="tool_call"&&t!==null?t.tools.push(vu(a)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}var ym,vm=Y(()=>{"use strict";Nd();ym="(untitled)"});import*as rs from"fs/promises";async function ca(n,e){let t=O.queueFile(n);if(e.length===0){await rs.unlink(t).catch(()=>{});return}await rs.mkdir(O.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
23
+ `)}`}function wm(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Vk(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Qk(n),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=t).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?bm(a):"",d=i?bm([i]):"";return{closedText:c,openText:d,keptCount:o}}function bm(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
24
+ `)}function Qk(n){let e=[],t=null;for(let r=0;r<n.length;r++){let i=n[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")t!==null&&t.user.length>0&&e.push(t),t={user:Su(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&t!==null){let d=ku(a.content);d.length>0&&(t.agent+=d)}else c==="tool_call"&&t!==null?t.tools.push(vu(a)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}var ym,vm=Y(()=>{"use strict";Nd();ym="(untitled)"});import*as is from"fs/promises";async function ca(n,e){let t=O.queueFile(n);if(e.length===0){await is.unlink(t).catch(()=>{});return}await is.mkdir(O.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
25
25
  `)+`
26
- `;await rs.writeFile(t,s,"utf8")}async function Sm(n){let e=O.queueFile(n),t;try{t=await rs.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
27
- `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function km(n){let e=O.queueFile(n);await rs.unlink(e).catch(()=>{})}var xu=Y(()=>{"use strict";be()});import{customAlphabet as Cm}from"nanoid";import*as Em from"fs/promises";function sr(){return`m_${Tm()}`}function pt(n){return n.startsWith(Dt)?n.slice(Dt.length):n}function dn(n,e){return n.code=e,n}function Im(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&eI.has(s)}function tI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function nI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function sI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Wi(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function la(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function rI(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function iI(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.chunks.push(i.text),n.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.thinkingChars+=i.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function oI(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function aI(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:sr()}}}function Hd(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function xm(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function dI(n){let e=cI(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=lI(n.resolver),t}function cI(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function lI(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function qi(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Cu(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function uI(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Am(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
26
+ `;await is.writeFile(t,s,"utf8")}async function Sm(n){let e=O.queueFile(n),t;try{t=await is.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
27
+ `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function km(n){let e=O.queueFile(n);await is.unlink(e).catch(()=>{})}var xu=Y(()=>{"use strict";be()});import{customAlphabet as Cm}from"nanoid";import*as Em from"fs/promises";function sr(){return`m_${Tm()}`}function pt(n){return n.startsWith(Dt)?n.slice(Dt.length):n}function dn(n,e){return n.code=e,n}function Im(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&nI.has(s)}function sI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function rI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function iI(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Wi(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function la(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function oI(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function aI(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.chunks.push(i.text),n.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.thinkingChars+=i.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function dI(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function cI(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:sr()}}}function Hd(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function xm(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function lI(n){let e=uI(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=fI(n.resolver),t}function uI(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function fI(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function qi(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Cu(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function pI(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Am(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
28
28
  ${s.join(`
29
- `)}`}function Ru(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Rm,Tm,Au,Vk,Qk,Gk,Dt,Xk,Dd,Zk,zi,eI,is=Y(()=>{"use strict";yu();um();fm();Bd();mm();vm();xu();_t();Rm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tm=Cm(Rm,16),Au=Cm(Rm,16),Vk=20,Qk=20,Gk=5,Dt="hydra_session_";Xk=1e3,Dd=300*1e3,Zk=64,zi=class n{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;forkHook;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??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Dt}${Tm()}`,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(t=>t.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.forkHook=e.forkHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Xk,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){iI(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=xm(s.shortCircuit?t: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(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,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(t.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Au()}`,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,w=new Set(t),b=r;await new Promise(S=>{let k=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([...w,u.name]),m+1,b).then(()=>S()).catch(()=>S()))},Dd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:k,transformerName:u.name,method:b,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),t.add(u.name)}if(r!=="session/update")return;let c=oI(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=rI(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 t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.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 Ni({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Bi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let m=Iu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let b=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...w!==void 0?{previousSummarizedThroughEntry:w}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await b.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
29
+ `)}`}function Ru(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Rm,Tm,Au,Gk,Xk,Zk,Dt,eI,Dd,tI,zi,nI,os=Y(()=>{"use strict";yu();um();fm();Bd();mm();vm();xu();_t();Rm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tm=Cm(Rm,16),Au=Cm(Rm,16),Gk=20,Xk=20,Zk=5,Dt="hydra_session_";eI=1e3,Dd=300*1e3,tI=64,zi=class n{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;forkHook;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??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Dt}${Tm()}`,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(t=>t.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.forkHook=e.forkHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??eI,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){aI(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=xm(s.shortCircuit?t: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(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,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(t.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Au()}`,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,w=new Set(t),b=r;await new Promise(S=>{let k=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([...w,u.name]),m+1,b).then(()=>S()).catch(()=>S()))},Dd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:k,transformerName:u.name,method:b,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),t.add(u.name)}if(r!=="session/update")return;let c=dI(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=oI(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 t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.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 Ni({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Bi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let m=Iu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let b=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...w!==void 0?{previousSummarizedThroughEntry:w}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await b.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
30
30
  Switched to ${r}.
31
31
  `:`
32
32
  Compaction completed.
33
- `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await Ni({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Bi({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=Vk){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,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(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(r=>r.entry):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw dn(new Error("session is closed"),q.SessionNotFound);if(this.clients.has(e.clientId))throw dn(new Error(`client ${e.clientId} is already attached`),q.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:hm(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Im(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Hd(i,t.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=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw dn(new Error("client not attached"),q.SessionNotFound);if(this.closing)throw dn(new Error("session is closing; new prompts cannot be accepted"),q.SessionClosing);let r=sr();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(an((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=qi(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:sr()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Zk;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw dn(new Error("client not attached"),q.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let 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,t,s,r){let i=sr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=sr(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw dn(new Error("client not attached"),q.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Au()}`,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??Cu(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 w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:Cu(e))))},Dd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,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_${Au()}`,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??uI(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 w=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},Dd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(d,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Dd,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:Cu(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=sr(),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 t=e;if(t.sessionId===this.sessionId)return{...t,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 t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=qi((e??{}).prompt),r=Ru(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=Wi(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=Wi(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=la(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=Wi(o.options);if(c.length>0){let d=la(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 t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let 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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(tI(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(nI(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),sI(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of Hi){if(t.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&&t.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,t=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of Hi)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,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(Hi.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();case"fork":return a?this.runForkCommandInline(o,t):this.runForkCommand(o);default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=q.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,t):this.runExtensionCommand(c,o);let d=Hi.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=q.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(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,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
33
+ `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await Ni({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Bi({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=Gk){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,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(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(r=>r.entry):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw dn(new Error("session is closed"),q.SessionNotFound);if(this.clients.has(e.clientId))throw dn(new Error(`client ${e.clientId} is already attached`),q.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:hm(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Im(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Hd(i,t.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=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw dn(new Error("client not attached"),q.SessionNotFound);if(this.closing)throw dn(new Error("session is closing; new prompts cannot be accepted"),q.SessionClosing);let r=sr();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(an((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=qi(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:sr()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>tI;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw dn(new Error("client not attached"),q.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let 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,t,s,r){let i=sr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=sr(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw dn(new Error("client not attached"),q.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Au()}`,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??Cu(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 w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:Cu(e))))},Dd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,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_${Au()}`,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??pI(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 w=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},Dd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(d,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Dd,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:Cu(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=sr(),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 t=e;if(t.sessionId===this.sessionId)return{...t,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 t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=qi((e??{}).prompt),r=Ru(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=Wi(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=Wi(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=la(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=Wi(o.options);if(c.length>0){let d=la(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 t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let 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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(sI(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(rI(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),iI(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of Hi){if(t.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&&t.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,t=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of Hi)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,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(Hi.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();case"fork":return a?this.runForkCommandInline(o,t):this.runForkCommand(o);default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=q.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,t):this.runExtensionCommand(c,o);let d=Hi.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=q.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(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,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
34
34
  ${e}
35
35
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",c=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${c}`});e=`Sessions (${t.length}):
36
36
  ${s.join(`
@@ -71,8 +71,8 @@ ${h}:
71
71
  `)}
72
72
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw dn(new Error("/hydra agent requires an agent id"),q.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw dn(new Error(`already on agent ${r}`),q.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 dn(new Error("agent restart not configured for this session"),q.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),t=this._summarizedThroughEntry;if(e==null&&t==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
73
73
  `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}runForkCommand(e){return this.enqueuePrompt(()=>this.runForkCommandInline(e,void 0))}async findMessageIdBefore(e){if(!this.historyStore)return;let t=await this.historyStore.load(this.sessionId),s;for(let r of t){if(r.method!=="session/update")continue;let o=r.params?.update?.messageId;if(typeof o=="string"){if(o===e)return s;s=o}}}async runForkCommandInline(e,t){if(!this.forkHook)return this.emitExtensionReply("Fork not configured for this session."),{stopReason:"end_turn"};let s=(e??"").trim(),r;if(s==="verbatim")r="verbatim";else if(s==="synthesis"||s==="")r=void 0;else return this.emitExtensionReply(`Unknown fork argument: \`${s}\`. Use \`/hydra fork\` or \`/hydra fork verbatim\`.`),{stopReason:"end_turn"};try{let i={};if(r&&(i.mode=r),t&&this.historyStore){let c=await this.findMessageIdBefore(t).catch(()=>{});c&&(i.forkAt=c)}let a=(await this.forkHook(Object.keys(i).length>0?i:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(`Forked to [\`${a}\`](hydra://sessions/${a}).`)}catch(i){this.emitExtensionReply(`Fork failed: ${i instanceof Error?i.message:String(i)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw dn(new Error("session is closing"),q.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let 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=qi(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=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
74
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=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=Iu({synopsis:e,title:t,tail:s,tailK:Qk,tailFloor:Gk,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,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,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 Ld(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Di,Di)),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,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=q.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(()=>km(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(()=>Em.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,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:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(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 t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.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 t=[...this.idleHandlers];for(let s of t){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 t=e.update;if(!t||typeof t!="object")return;let s=t,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,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!Im(e,r),o=i?aI(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 t=[...this.clients.values()];if(t.length===0)throw dn(new Error("no clients attached to handle permission request"),q.PermissionDenied);let s=this.rewriteForClient(e),r=xm(s),i=sr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===q.MethodNotFound;function w(b){if(l)return;let S=b.connection.request("session/request_permission",s);u.push({client:b}),f++,S.then(k=>{f--,m(()=>{let A=dI({toolCallId:r,result:k,resolver:b});for(let E of u)E.client.clientId!==b.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:A}).catch(()=>{});c(k)})}).catch(k=>{if(f--,y(k)||(p=k),f===0&&!l){let A=p??dn(new Error("no client handled permission request"),q.PermissionDenied);m(()=>d(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,w);for(let b of t)w(b)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:sr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,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 t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ca(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=qi(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
- `)&&t.startsWith("/")?t.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(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(i){let c=t.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(t,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)}};eI=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 Ki}from"zod";var fI,Pm,Mm=Y(()=>{"use strict";fI=Ki.object({source:Ki.string(),reason:Ki.string(),raisedAt:Ki.number(),payload:Ki.unknown()}),Pm=Ki.array(fI)});import{z as je}from"zod";function Fm(n){let e=n.trim();if(e.length===0)return;let t=Ji(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=Ji(e.slice(i,o+1)))}if(t===void 0){let i=Lm(e);i!==void 0&&(t=Ji(i))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,$m))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=ua.safeParse(s.synopsis);i.success&&pI(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Om(n){let e=n.trim();if(e.length===0)return;let t=Ji(e);if(t===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(t=Ji(e.slice(d,l+1)))}if(t===void 0){let d=Lm(e);d!==void 0&&(t=Ji(d))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,$m))}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=je.array(je.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 Ji(n){try{return JSON.parse(n)}catch{return}}function Lm(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function pI(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var _m,ua,$m,Tu,Eu,Ud=Y(()=>{"use strict";_m=je.object({status:je.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:je.number(),iter:je.number().int().nonnegative().optional(),attempts:je.number().int().nonnegative().optional(),lastError:je.string().optional(),worker:je.object({upstreamSessionId:je.string(),pid:je.number().int().nonnegative()}).optional()}),ua=je.object({goal:je.string().optional(),outcome:je.string().optional(),files_touched:je.array(je.string()).optional(),tools_used:je.array(je.string()).optional(),rejected_approaches:je.array(je.string()).optional(),open_threads:je.array(je.string()).optional(),decisions:je.array(je.string()).optional(),file_edit_intentions:je.array(je.string()).optional(),unresolved_errors:je.array(je.string()).optional(),tool_state:je.array(je.string()).optional()}),$m=200,Tu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
74
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=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=Iu({synopsis:e,title:t,tail:s,tailK:Xk,tailFloor:Zk,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,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 Ld(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Di,Di)),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,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=q.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(()=>km(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(()=>Em.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,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:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(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 t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.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 t=[...this.idleHandlers];for(let s of t){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 t=e.update;if(!t||typeof t!="object")return;let s=t,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,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!Im(e,r),o=i?cI(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 t=[...this.clients.values()];if(t.length===0)throw dn(new Error("no clients attached to handle permission request"),q.PermissionDenied);let s=this.rewriteForClient(e),r=xm(s),i=sr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===q.MethodNotFound;function w(b){if(l)return;let S=b.connection.request("session/request_permission",s);u.push({client:b}),f++,S.then(k=>{f--,m(()=>{let A=lI({toolCallId:r,result:k,resolver:b});for(let E of u)E.client.clientId!==b.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:A}).catch(()=>{});c(k)})}).catch(k=>{if(f--,y(k)||(p=k),f===0&&!l){let A=p??dn(new Error("no client handled permission request"),q.PermissionDenied);m(()=>d(A))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,w);for(let b of t)w(b)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:sr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,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 t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ca(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=qi(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
+ `)&&t.startsWith("/")?t.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(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(i){let c=t.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(t,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)}};nI=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 Ki}from"zod";var hI,Pm,Mm=Y(()=>{"use strict";hI=Ki.object({source:Ki.string(),reason:Ki.string(),raisedAt:Ki.number(),payload:Ki.unknown()}),Pm=Ki.array(hI)});import{z as je}from"zod";function Fm(n){let e=n.trim();if(e.length===0)return;let t=Ji(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=Ji(e.slice(i,o+1)))}if(t===void 0){let i=Lm(e);i!==void 0&&(t=Ji(i))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,$m))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=ua.safeParse(s.synopsis);i.success&&mI(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Om(n){let e=n.trim();if(e.length===0)return;let t=Ji(e);if(t===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(t=Ji(e.slice(d,l+1)))}if(t===void 0){let d=Lm(e);d!==void 0&&(t=Ji(d))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,$m))}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=je.array(je.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 Ji(n){try{return JSON.parse(n)}catch{return}}function Lm(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function mI(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var _m,ua,$m,Tu,Eu,Ud=Y(()=>{"use strict";_m=je.object({status:je.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:je.number(),iter:je.number().int().nonnegative().optional(),attempts:je.number().int().nonnegative().optional(),lastError:je.string().optional(),worker:je.object({upstreamSessionId:je.string(),pid:je.number().int().nonnegative()}).optional()}),ua=je.object({goal:je.string().optional(),outcome:je.string().optional(),files_touched:je.array(je.string()).optional(),tools_used:je.array(je.string()).optional(),rejected_approaches:je.array(je.string()).optional(),open_threads:je.array(je.string()).optional(),decisions:je.array(je.string()).optional(),file_edit_intentions:je.array(je.string()).optional(),unresolved_errors:je.array(je.string()).optional(),tool_state:je.array(je.string()).optional()}),$m=200,Tu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
76
76
  {
77
77
  "title": "short summary, max 80 chars",
78
78
  "synopsis": {
@@ -94,63 +94,63 @@ Use empty arrays/strings where a field doesn't apply.`;Eu=`Reply with ONLY a JSO
94
94
  "unresolved_errors": ["errors left open at session end"],
95
95
  "tool_state": ["runtime state relevant for recall"]
96
96
  }
97
- Use empty arrays/strings where a field doesn't apply.`});import*as Yi from"fs/promises";import*as O_ from"path";import{customAlphabet as hI}from"nanoid";import{z as se}from"zod";function fa(){return`${yI}${gI()}`}function SI(n){if(!Pu.test(n))throw new Error(`unsafe session id: ${n}`)}function Ou(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}var mI,gI,yI,Mu,_u,wI,$u,Fu,bI,vI,Pu,jd,Lu=Y(()=>{"use strict";be();Or();Mm();Ud();mI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gI=hI(mI,16),yI="hydra_lineage_";Mu=se.object({name:se.string(),description:se.string().optional()}),_u=se.object({id:se.string(),name:se.string().optional(),description:se.string().optional()}),wI=se.object({modelId:se.string(),name:se.string().optional(),description:se.string().optional()}),$u=se.object({used:se.number().optional(),size:se.number().optional(),costAmount:se.number().optional(),costCurrency:se.string().optional(),cumulativeCost:se.number().optional()}),Fu=se.object({name:se.string(),version:se.string().optional()}),bI=se.object({previousUpstreamSessionId:se.string(),previousSummarizedThroughEntry:se.number().int().nonnegative().optional()}),vI=se.object({version:se.literal(1),sessionId:se.string(),lineageId:se.string().optional(),upstreamSessionId:se.string(),importedFromSessionId:se.string().optional(),importedFromUpstreamSessionId:se.string().optional(),importedFromMachine:se.string().optional(),agentId:se.string(),cwd:se.string(),title:se.string().optional(),synopsis:ua.optional(),compactionState:_m.optional(),rollbackBreadcrumb:bI.optional(),summarizedThroughEntry:se.number().int().nonnegative().optional(),agentArgs:se.array(se.string()).optional(),currentModel:se.string().optional(),currentMode:se.string().optional(),currentUsage:$u.optional(),agentCommands:se.array(Mu).optional(),agentModes:se.array(_u).optional(),agentModels:se.array(wI).optional(),pendingHistorySync:se.boolean().optional(),pendingAgentSwap:se.string().optional(),parentSessionId:se.string().optional(),forkedFromSessionId:se.string().optional(),forkedFromMessageId:se.string().optional(),forkSynthesisState:se.enum(["running","failed"]).optional(),originatingClient:Fu.optional(),interactive:se.boolean().optional(),priority:se.number().int().nonnegative().optional(),forwardedEnv:se.record(se.string(),se.string()).optional(),attentionFlags:Pm.default([]).optional(),extensionState:se.record(se.string(),se.record(se.string(),se.unknown())).default({}).optional(),createdAt:se.string(),updatedAt:se.string()}),Pu=/^[A-Za-z0-9_-]+$/;jd=class{async write(e){SI(e.sessionId);let t={version:1,...e};await rn(O.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Pu.test(e))return;let t=await wn(O.sessionFile(e));if(t!==void 0)try{return vI.parse(t)}catch{return}}async delete(e){if(Pu.test(e)){try{await Yi.unlink(O.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Yi.rmdir(O.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Yi.readdir(O.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}}});import{fileURLToPath as II}from"url";import*as pa from"path";import*as Wd from"fs";function xI(){try{let n=pa.dirname(II(import.meta.url));for(let e=0;e<8;e+=1){let t=pa.join(n,"package.json");if(Wd.existsSync(t)){let r=JSON.parse(Wd.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=pa.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var ve,qr,cn=Y(()=>{"use strict";ve=xI(),qr="hydra-acp-cat"});function Bu(n){let e=new Map;for(let t of Km(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function qm(n){return Bu(n).map(e=>e.name)}function Nu(n){let e=new Map;for(let t of Km(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Wm(n){return Nu(n).map(e=>e.path)}function zm(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Km(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,d=e.get(c);d===void 0?(d={toolName:Um(i),paths:new Set},e.set(c,d)):d.toolName=Um(i);for(let l of jm(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 jm(i.rawInput,i.locations))a.paths.add(c)}return e}function Um(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function jm(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Du=Y(()=>{"use strict"});import{promises as ha}from"fs";import*as Ku from"path";async function ma(n){let e;try{e=await ha.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return WI(e)}function WI(n){let e=[];for(let t of n.split(`
97
+ Use empty arrays/strings where a field doesn't apply.`});import*as Yi from"fs/promises";import*as D_ from"path";import{customAlphabet as gI}from"nanoid";import{z as se}from"zod";function fa(){return`${bI}${wI()}`}function II(n){if(!Pu.test(n))throw new Error(`unsafe session id: ${n}`)}function Ou(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}var yI,wI,bI,Mu,_u,vI,$u,Fu,SI,kI,Pu,jd,Lu=Y(()=>{"use strict";be();Or();Mm();Ud();yI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wI=gI(yI,16),bI="hydra_lineage_";Mu=se.object({name:se.string(),description:se.string().optional()}),_u=se.object({id:se.string(),name:se.string().optional(),description:se.string().optional()}),vI=se.object({modelId:se.string(),name:se.string().optional(),description:se.string().optional()}),$u=se.object({used:se.number().optional(),size:se.number().optional(),costAmount:se.number().optional(),costCurrency:se.string().optional(),cumulativeCost:se.number().optional()}),Fu=se.object({name:se.string(),version:se.string().optional()}),SI=se.object({previousUpstreamSessionId:se.string(),previousSummarizedThroughEntry:se.number().int().nonnegative().optional()}),kI=se.object({version:se.literal(1),sessionId:se.string(),lineageId:se.string().optional(),upstreamSessionId:se.string(),importedFromSessionId:se.string().optional(),importedFromUpstreamSessionId:se.string().optional(),importedFromMachine:se.string().optional(),agentId:se.string(),cwd:se.string(),title:se.string().optional(),synopsis:ua.optional(),compactionState:_m.optional(),rollbackBreadcrumb:SI.optional(),summarizedThroughEntry:se.number().int().nonnegative().optional(),agentArgs:se.array(se.string()).optional(),currentModel:se.string().optional(),currentMode:se.string().optional(),currentUsage:$u.optional(),agentCommands:se.array(Mu).optional(),agentModes:se.array(_u).optional(),agentModels:se.array(vI).optional(),pendingHistorySync:se.boolean().optional(),pendingAgentSwap:se.string().optional(),parentSessionId:se.string().optional(),forkedFromSessionId:se.string().optional(),forkedFromMessageId:se.string().optional(),forkSynthesisState:se.enum(["running","failed"]).optional(),originatingClient:Fu.optional(),interactive:se.boolean().optional(),priority:se.number().int().nonnegative().optional(),forwardedEnv:se.record(se.string(),se.string()).optional(),attentionFlags:Pm.default([]).optional(),extensionState:se.record(se.string(),se.record(se.string(),se.unknown())).default({}).optional(),createdAt:se.string(),updatedAt:se.string()}),Pu=/^[A-Za-z0-9_-]+$/;jd=class{async write(e){II(e.sessionId);let t={version:1,...e};await rn(O.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Pu.test(e))return;let t=await wn(O.sessionFile(e));if(t!==void 0)try{return kI.parse(t)}catch{return}}async delete(e){if(Pu.test(e)){try{await Yi.unlink(O.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Yi.rmdir(O.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Yi.readdir(O.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}}});import{fileURLToPath as AI}from"url";import*as pa from"path";import*as Wd from"fs";function CI(){try{let n=pa.dirname(AI(import.meta.url));for(let e=0;e<8;e+=1){let t=pa.join(n,"package.json");if(Wd.existsSync(t)){let r=JSON.parse(Wd.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=pa.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var ve,qr,cn=Y(()=>{"use strict";ve=CI(),qr="hydra-acp-cat"});function Bu(n){let e=new Map;for(let t of Km(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function qm(n){return Bu(n).map(e=>e.name)}function Nu(n){let e=new Map;for(let t of Km(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Wm(n){return Nu(n).map(e=>e.path)}function zm(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Km(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,d=e.get(c);d===void 0?(d={toolName:Um(i),paths:new Set},e.set(c,d)):d.toolName=Um(i);for(let l of jm(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 jm(i.rawInput,i.locations))a.paths.add(c)}return e}function Um(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function jm(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Du=Y(()=>{"use strict"});import{promises as ha}from"fs";import*as Ku from"path";async function ma(n){let e;try{e=await ha.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return KI(e)}function KI(n){let e=[];for(let t of n.split(`
98
98
  `))if(t.length!==0)try{let s=JSON.parse(t);typeof s=="string"&&e.push(s)}catch{}return e}function ga(n,e,t=sg){let s=e.replace(/\n+$/,"");if(s.length===0||n.length>0&&n[n.length-1]===s)return n;let r=n.concat(s);return r.length>t?r.slice(r.length-t):r}async function Wr(n,e){await ha.mkdir(Ku.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await ha.writeFile(n,t.length>0?t.join(`
99
99
  `)+`
100
100
  `:"")}async function rg(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await ha.mkdir(Ku.dirname(n),{recursive:!0}),await ha.appendFile(n,JSON.stringify(t)+`
101
- `,{encoding:"utf8"}))}function Yd(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function Ju(n,e,t=sg){if(e.length===0)return n;let s=new Set(n),r=n;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=ga(r,o,t)))}return r}var sg,Vd=Y(()=>{"use strict";sg=500});import{z as Me}from"zod";function ya(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function Nn(n){return JI.parse(n)}var zI,KI,JI,zr=Y(()=>{"use strict";Lu();Ud();zI=Me.object({method:Me.string(),params:Me.unknown(),recordedAt:Me.number()}),KI=Me.object({sessionId:Me.string(),lineageId:Me.string(),upstreamSessionId:Me.string().optional(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),synopsis:ua.optional(),summarizedThroughEntry:Me.number().int().nonnegative().optional(),currentModel:Me.string().optional(),currentMode:Me.string().optional(),currentUsage:$u.optional(),agentCommands:Me.array(Mu).optional(),agentModes:Me.array(_u).optional(),interactive:Me.boolean().optional(),originatingClient:Fu.optional(),priority:Me.number().int().nonnegative().optional(),createdAt:Me.string(),updatedAt:Me.string()}),JI=Me.object({version:Me.literal(1),exportedAt:Me.string(),exportedFrom:Me.object({hydraVersion:Me.string(),machine:Me.string(),hydraHost:Me.string().optional()}),session:KI,history:Me.array(zI),promptHistory:Me.array(Me.string()).optional(),toolBlobs:Me.record(Me.string()).optional()})});import{createHash as dx}from"crypto";function sf(n){if(Array.isArray(n))return n.map(sf);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=sf(n[t]);return e}return n}function ir(n){let{tui:e,...t}=n,s=JSON.stringify(sf(t));return dx("sha256").update(s).digest("hex").slice(0,16)}var xa=Y(()=>{"use strict";Ge()});function rf(n){return Math.floor(n/4)}function Ig(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=rf(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}function xg(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var of=Y(()=>{"use strict"});function Aa(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Ag=Y(()=>{"use strict"});import{posix as vx}from"path";import Sx from"strip-ansi";function wt(n){return Sx(n).replace(kx,"")}function Te(n){return wt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ds(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Tx(t);case"agent_thought_chunk":case"agent_thought":return Ex(t);case"user_message_chunk":return Px(t);case"prompt_received":return Mx(t);case"tool_call":return _x(t,e);case"tool_call_update":return Bx(t,e);case"plan":return Hx(t);case"current_mode_update":return Ux(t);case"current_model_update":return jx(t);case"turn_complete":return qx(t);case"usage_update":return Rx(t);case"available_commands_update":return Ax(t);case"available_modes_update":return Cx(t);case"session_info_update":return xx(t);case"config_option_update":return Ix(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function Ix(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function xx(n){let e=lt(n,"title"),t=e!==void 0?Te(e):void 0,s=n._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(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function fc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Te(r)};typeof s.description=="string"&&(i.description=Te(s.description)),e.push(i)}return e}function Ax(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:fc(e)}:null}function Cx(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:Te(r.id)};typeof r.name=="string"&&(i.name=Te(r.name)),typeof r.description=="string"&&(i.description=Te(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Rx(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function Tx(n){let e=Ca(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Aa(n)}}function Ex(n){let e=typeof n.text=="string"?wt(n.text):Ca(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Aa(n)}}function Px(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=Ca(n.content);return t===null?null:{kind:"user-text",text:t}}function Mx(n){let e=Wx(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Tg(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Cg(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function pc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Cg(r.oldText),o=Cg(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Eg(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:wt(t)}function _x(n,e={}){let t=lt(n,"toolCallId")??lt(n,"id");if(!t)return null;let s=lt(n,"title")??lt(n,"name")??lt(n,"label")??"tool call",r=lt(n,"name")??lt(n,"title");if(Tg(r)){let h=Eg(n);if(h!==null){let m=lt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=_g(Te(s),n,e),o=lt(n,"status"),a=lt(n,"kind"),c={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=pc(n);d!==null&&(c.editDiff=d);let l=Mg(n);l!==void 0&&(c.detail=l);let u=af(n);u!==void 0&&(c.detailFull=u);let f=Pg(n);f!==void 0&&(c.locations=f);let p=Aa(n);return p!==void 0&&(c.workerTaskId=p),c}function Pg(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}function Mg(n){let e=af(n);if(e===void 0)return;let t=Te(e),s=n.rawInput;return s&&typeof s.command=="string"?Ox(t,Rg):Lx(t,Rg)}function af(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return wt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return ct(Te(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return ct(Te(s))}}}function Fx(n){for(let e of $x)if(n.startsWith(e))return!0;return!1}function _g(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return ct(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return ct(o)}return Fx(n)?ct(`/${n}`):t.cwd&&t.cwd.length>0?ct(vx.resolve(t.cwd,n)):n}function Ox(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Lx(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Bx(n,e={}){let t=lt(n,"toolCallId")??lt(n,"id");if(!t)return null;let s=lt(n,"title"),r=s!==void 0?_g(Te(s),n,e):void 0,i=lt(n,"status"),o=pc(n),a=Mg(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=lt(n,"name")??s;if(Tg(d)){let h={kind:"exit-plan-mode",toolCallId:t},m=Eg(n);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=af(n);u!==void 0&&(l.detailFull=u);let f=Pg(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=Nx(n);h!==null&&(l.errorText=h),Dx(n,h)&&(l.upstreamInterrupted=!0)}let p=Aa(n);return p!==void 0&&(l.workerTaskId=p),l}function Nx(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Ca(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return wt(s)}return null}function Dx(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Hx(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?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),t.push(o)}return{kind:"plan",entries:t}}function Ux(n){let e=lt(n,"currentModeId")??lt(n,"currentMode")??lt(n,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function jx(n){let e=lt(n,"currentModel")??lt(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Te(e),...s&&s.length>0?{availableModels:s}:{}}}function qx(n){let e=lt(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Ca(n){if(typeof n=="string")return wt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?wt(e.text):null}function Wx(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=Ca(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function lt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var kx,Rg,$x,or=Y(()=>{"use strict";be();Ag();kx=/[\x00-\x08\x0b-\x1f\x7f]/g;Rg=64;$x=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Gi(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=Kx(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)zx(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Xi(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function zx(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Kx(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let 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=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let 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=pc(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var hc=Y(()=>{"use strict";or()});function cs(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let 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:q.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{n.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var no=Y(()=>{"use strict";_t()});import{spawn as pC}from"child_process";import{dirname as hC,resolve as mC}from"path";import{fileURLToPath as gC}from"url";import{setTimeout as yC}from"timers/promises";async function Sy(){let n=await Ms();if(n&&Ln(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function wC(n){let e=await Jr(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===ir(n)?"match":"mismatch":"missing"}async function cr(n){let e=await wC(n);if(e!=="match"){if(e==="mismatch"){let t=ns();throw new Error(`config changed since daemon started \u2014 run \`${t} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
102
- `),Ec(),await Pc(n)}}async function Tc(n){let e=await Sy();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Jr(n,e=1e3){let t=await Sy();if(t)try{let s=await fetch(t,{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 Ec(){let n=hC(gC(import.meta.url)),e=mC(n,"./daemon.js");pC(process.execPath,[e],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Pc(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Tc(n))return;await yC(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Yr=Y(()=>{"use strict";na();xa();Ei()});import*as ky from"fs";import*as io from"fs/promises";async function oo(n,e,t){let s=vC(e),r;try{r=await io.stat(n)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${t} (${n})
103
- `),process.exit(1);return}throw c}let i=await bC(n,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${n} --
104
- `);let o=!1,a=ky.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await io.stat(n);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await io.open(n,"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 bC(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await io.open(n,"r");try{let i=e,o="",a=0;for(;i>0&&a<=t;){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(`
101
+ `,{encoding:"utf8"}))}function Yd(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function Ju(n,e,t=sg){if(e.length===0)return n;let s=new Set(n),r=n;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=ga(r,o,t)))}return r}var sg,Vd=Y(()=>{"use strict";sg=500});import{z as Me}from"zod";function ya(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function Nn(n){return VI.parse(n)}var JI,YI,VI,zr=Y(()=>{"use strict";Lu();Ud();JI=Me.object({method:Me.string(),params:Me.unknown(),recordedAt:Me.number()}),YI=Me.object({sessionId:Me.string(),lineageId:Me.string(),upstreamSessionId:Me.string().optional(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),synopsis:ua.optional(),summarizedThroughEntry:Me.number().int().nonnegative().optional(),currentModel:Me.string().optional(),currentMode:Me.string().optional(),currentUsage:$u.optional(),agentCommands:Me.array(Mu).optional(),agentModes:Me.array(_u).optional(),interactive:Me.boolean().optional(),originatingClient:Fu.optional(),priority:Me.number().int().nonnegative().optional(),createdAt:Me.string(),updatedAt:Me.string()}),VI=Me.object({version:Me.literal(1),exportedAt:Me.string(),exportedFrom:Me.object({hydraVersion:Me.string(),machine:Me.string(),hydraHost:Me.string().optional()}),session:YI,history:Me.array(JI),promptHistory:Me.array(Me.string()).optional(),toolBlobs:Me.record(Me.string()).optional()})});import{createHash as lx}from"crypto";function sf(n){if(Array.isArray(n))return n.map(sf);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=sf(n[t]);return e}return n}function ir(n){let{tui:e,...t}=n,s=JSON.stringify(sf(t));return lx("sha256").update(s).digest("hex").slice(0,16)}var xa=Y(()=>{"use strict";Ge()});function rf(n){return Math.floor(n/4)}function Ig(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=rf(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}function xg(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var of=Y(()=>{"use strict"});function Aa(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Ag=Y(()=>{"use strict"});import{posix as kx}from"path";import Ix from"strip-ansi";function wt(n){return Ix(n).replace(xx,"")}function Te(n){return wt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function cs(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Px(t);case"agent_thought_chunk":case"agent_thought":return Mx(t);case"user_message_chunk":return _x(t);case"prompt_received":return $x(t);case"tool_call":return Fx(t,e);case"tool_call_update":return Dx(t,e);case"plan":return jx(t);case"current_mode_update":return qx(t);case"current_model_update":return Wx(t);case"turn_complete":return zx(t);case"usage_update":return Ex(t);case"available_commands_update":return Rx(t);case"available_modes_update":return Tx(t);case"session_info_update":return Cx(t);case"config_option_update":return Ax(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function Ax(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Cx(n){let e=lt(n,"title"),t=e!==void 0?Te(e):void 0,s=n._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(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function fc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Te(r)};typeof s.description=="string"&&(i.description=Te(s.description)),e.push(i)}return e}function Rx(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:fc(e)}:null}function Tx(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:Te(r.id)};typeof r.name=="string"&&(i.name=Te(r.name)),typeof r.description=="string"&&(i.description=Te(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Ex(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function Px(n){let e=Ca(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Aa(n)}}function Mx(n){let e=typeof n.text=="string"?wt(n.text):Ca(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Aa(n)}}function _x(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=Ca(n.content);return t===null?null:{kind:"user-text",text:t}}function $x(n){let e=Kx(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Tg(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Cg(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function pc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Cg(r.oldText),o=Cg(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Eg(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:wt(t)}function Fx(n,e={}){let t=lt(n,"toolCallId")??lt(n,"id");if(!t)return null;let s=lt(n,"title")??lt(n,"name")??lt(n,"label")??"tool call",r=lt(n,"name")??lt(n,"title");if(Tg(r)){let h=Eg(n);if(h!==null){let m=lt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=_g(Te(s),n,e),o=lt(n,"status"),a=lt(n,"kind"),c={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=pc(n);d!==null&&(c.editDiff=d);let l=Mg(n);l!==void 0&&(c.detail=l);let u=af(n);u!==void 0&&(c.detailFull=u);let f=Pg(n);f!==void 0&&(c.locations=f);let p=Aa(n);return p!==void 0&&(c.workerTaskId=p),c}function Pg(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}function Mg(n){let e=af(n);if(e===void 0)return;let t=Te(e),s=n.rawInput;return s&&typeof s.command=="string"?Bx(t,Rg):Nx(t,Rg)}function af(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return wt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return ct(Te(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return ct(Te(s))}}}function Lx(n){for(let e of Ox)if(n.startsWith(e))return!0;return!1}function _g(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return ct(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return ct(o)}return Lx(n)?ct(`/${n}`):t.cwd&&t.cwd.length>0?ct(kx.resolve(t.cwd,n)):n}function Bx(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Nx(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Dx(n,e={}){let t=lt(n,"toolCallId")??lt(n,"id");if(!t)return null;let s=lt(n,"title"),r=s!==void 0?_g(Te(s),n,e):void 0,i=lt(n,"status"),o=pc(n),a=Mg(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=lt(n,"name")??s;if(Tg(d)){let h={kind:"exit-plan-mode",toolCallId:t},m=Eg(n);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=af(n);u!==void 0&&(l.detailFull=u);let f=Pg(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=Hx(n);h!==null&&(l.errorText=h),Ux(n,h)&&(l.upstreamInterrupted=!0)}let p=Aa(n);return p!==void 0&&(l.workerTaskId=p),l}function Hx(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Ca(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return wt(s)}return null}function Ux(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function jx(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?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),t.push(o)}return{kind:"plan",entries:t}}function qx(n){let e=lt(n,"currentModeId")??lt(n,"currentMode")??lt(n,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function Wx(n){let e=lt(n,"currentModel")??lt(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Te(e),...s&&s.length>0?{availableModels:s}:{}}}function zx(n){let e=lt(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Ca(n){if(typeof n=="string")return wt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?wt(e.text):null}function Kx(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=Ca(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function lt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var xx,Rg,Ox,or=Y(()=>{"use strict";be();Ag();xx=/[\x00-\x08\x0b-\x1f\x7f]/g;Rg=64;Ox=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Gi(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=Yx(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)Jx(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Xi(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Jx(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Yx(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let 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=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let 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=pc(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var hc=Y(()=>{"use strict";or()});function ls(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let 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:q.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{n.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var no=Y(()=>{"use strict";_t()});import{spawn as mC}from"child_process";import{dirname as gC,resolve as yC}from"path";import{fileURLToPath as wC}from"url";import{setTimeout as Sy}from"timers/promises";async function ky(){let n=await ss();if(n&&bn(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function bC(n){let e=await Jr(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===ir(n)?"match":"mismatch":"missing"}async function cr(n,e){let t=await bC(n);if(t==="mismatch"){let s=ns();throw new Error(`config changed since daemon started \u2014 run \`${s} daemon restart\` to apply.`)}if(t==="missing"&&(process.stderr.write(`hydra-acp: daemon not running; starting it...
102
+ `),Ec(),await Pc(n)),e!==void 0){let s=await ss();if(s&&bn(s.pid)){let r=`http://127.0.0.1:${s.loopbackPort}`;e.baseUrl=r,e.wsUrl=`ws://127.0.0.1:${s.loopbackPort}/acp`}await SC(`${e.baseUrl}/v1/health`)}}async function Tc(n){let e=await ky();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Jr(n,e=1e3){let t=await ky();if(t)try{let s=await fetch(t,{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 Ec(){let n=gC(wC(import.meta.url)),e=yC(n,"./daemon.js");mC(process.execPath,[e],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function vC(n,e=500){try{return(await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}})).ok}catch{return!1}}async function SC(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await vC(n))return;await Sy(150)}throw new Error(`hydra-acp daemon did not answer ${n} within ${e}ms`)}async function Pc(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Tc(n))return;await Sy(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Yr=Y(()=>{"use strict";na();xa();Ei()});import*as Iy from"fs";import*as io from"fs/promises";async function oo(n,e,t){let s=IC(e),r;try{r=await io.stat(n)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${t} (${n})
103
+ `),process.exit(1);return}throw c}let i=await kC(n,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${n} --
104
+ `);let o=!1,a=Iy.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await io.stat(n);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await io.open(n,"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 kC(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await io.open(n,"r");try{let i=e,o="",a=0;for(;i>0&&a<=t;){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(`
105
105
  `).slice(-t-1);process.stdout.write(d.join(`
106
106
  `)),o.endsWith(`
107
107
  `)||process.stdout.write(`
108
- `)}finally{await r.close()}return e}function Mc(n){let e=new Set(["--tail","-n"]),t,s=[],r=0;for(;r<n.length;){let i=n[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<n.length){let o=n[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(t===void 0){t=i,r+=1;continue}s.push(i),r+=1}return{name:t,rest:s}}function vC(n){let e=50,t=!1,s=0;for(;s<n.length;){let r=n[s];if(r==="--tail"||r==="-n"){let i=n[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
108
+ `)}finally{await r.close()}return e}function Mc(n){let e=new Set(["--tail","-n"]),t,s=[],r=0;for(;r<n.length;){let i=n[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<n.length){let o=n[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(t===void 0){t=i,r+=1;continue}s.push(i),r+=1}return{name:t,rest:s}}function IC(n){let e=50,t=!1,s=0;for(;s<n.length;){let r=n[s];if(r==="--tail"||r==="-n"){let i=n[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
109
109
  `),process.exit(2)),e=o,s+=2;continue}if(r==="--follow"||r==="-f"){t=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
110
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var Ea=Y(()=>{"use strict"});import{WebSocket as IC}from"ws";async function Vr(n,e,t=xC){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=ra(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 IC(n,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new gf(n,Date.now()-a))},t),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 xC,gf,Pa=Y(()=>{"use strict";ia();xC=1e4,gf=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}}});import*as _c from"fs/promises";function AC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function co(){let n=await Ms();if(n&&Ln(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await Ie();return Ey(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Ey(n,e,t){return`${t?"https":"http"}://${AC(n)}:${e}`}async function Oe(n,e={}){let t=await Fr(),s=await co(),r=n.startsWith("http")?n:`${s}${n}`,i={Authorization:`Bearer ${t}`},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}
110
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var Ea=Y(()=>{"use strict"});import{WebSocket as CC}from"ws";async function Vr(n,e,t=RC){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=ra(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 CC(n,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new gf(n,Date.now()-a))},t),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 RC,gf,Pa=Y(()=>{"use strict";ia();RC=1e4,gf=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}}});import*as _c from"fs/promises";function TC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function co(){let n=await ss();if(n&&bn(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await Ie();return Py(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Py(n,e,t){return`${t?"https":"http"}://${TC(n)}:${e}`}async function Oe(n,e={}){let t=await Fr(),s=await co(),r=n.startsWith("http")?n:`${s}${n}`,i={Authorization:`Bearer ${t}`},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}
111
111
  `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let 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}
112
112
  `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function lo(n){let e;n instanceof Date?e=n.getTime():typeof n=="string"?e=Date.parse(n):e=n;let t=Math.max(0,Date.now()-e),s=Math.floor(t/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 $c(n,e){let t=e!=="agent",s=t?[]:void 0,r=[],i={},o=!0,a=0;for(;a<n.length;){let c=n[a];if(c==="--command"){let d=n[a+1];d===void 0&&(process.stderr.write(`--command requires a value
113
- `),process.exit(2)),s=t?CC(d):d,a+=2;continue}if(c==="--args"){let d=n[a+1];d===void 0&&(process.stderr.write(`--args requires a value
113
+ `),process.exit(2)),s=t?EC(d):d,a+=2;continue}if(c==="--args"){let d=n[a+1];d===void 0&&(process.stderr.write(`--args requires a value
114
114
  `),process.exit(2)),r=d.split(",").filter(l=>l.length>0),a+=2;continue}if(c==="--env"){let d=n[a+1];d===void 0&&(process.stderr.write(`--env requires KEY=VALUE
115
115
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
116
116
  `),process.exit(2)),i[d.slice(0,l)]=d.slice(l+1),a+=2;continue}if(c==="--disabled"&&e!=="agent"){o=!1,a+=1;continue}process.stderr.write(`Unknown flag: ${c}
117
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function CC(n){return n.split(/\s+/).filter(e=>e.length>0)}async function uo(){let n=await _c.readFile(O.config(),"utf8");return JSON.parse(n)}async function yf(n){await _c.writeFile(O.config(),JSON.stringify(n,null,2)+`
118
- `,{encoding:"utf8",mode:384})}var lr=Y(()=>{"use strict";Ge();Es();be();Ei();Pa()});async function un(n,e={},t=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()},t);try{return await s(n,{...e,signal:r.signal})}catch(c){throw o?new wf(n,t):c}finally{clearTimeout(a)}}async function Dn(n,e={},t=fetch){let s=new URL(`${n.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 un(s.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);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 Py(n,e=fetch){let t=await un(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 un(`${n.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Qr(n,e=fetch){let t=await un(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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(n,e,t={},s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},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 us(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function My(n,e,t,s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function _y(n,e,t,s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function $y(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);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 Fy(n,e,t={},s=fetch){let r={q:e};t.sessionIds&&t.sessionIds.length>0&&(r.sessionIds=t.sessionIds);let i=await un(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Oy(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Oc(n,e){let t=n.filter(i=>i.cwd===e);if(t.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...t].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var wf,Ma=Y(()=>{"use strict";wf=class extends Error{constructor(t,s){super(`daemon did not respond within ${s}ms (${t})`);this.url=t;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function bf(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function Ly(n,e){let t=n??"?",s=bf(e);return s?`${t}${RC}${s}`:t}function By(n){return n??"?"}function Ny(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:vf(e,t)}function vf(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var RC,Sf=Y(()=>{"use strict";RC="\u2022"});function Dy(n){let e=n.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,s=[];for(let r of e){if(!Bc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Bc.join(", ")})`);if(t.has(r))throw new Error(`--columns: duplicate column "${r}"`);t.add(r),s.push(r)}return s}function ho(n,e=Date.now()){return{session:pt(n.sessionId),upstream:PC(n.upstreamSessionId,n.importedFromMachine),host:n.importedFromMachine??"-",state:MC(n.status,n.busy,n.awaitingInput,EC(n.compactionState),n.forkSynthesisState),agent:By(n.agentId),model:bf(n.currentModel)??"-",age:_C(n.updatedAt,e),title:n.title??"-",cwd:ct(n.cwd),cost:Ny(n.currentUsage)}}function EC(n){if(n==null||typeof n!="object")return!1;let e=n.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function PC(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function MC(n,e,t,s,r){return n==="cold"?"COLD":t?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 mo(n,e={}){let t=e.columns??fo,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 t)s[r]=$C(po[r],n.map(i=>i[r]));return s}function _C(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let s=Math.max(0,e-t),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 $C(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function ur(n,e,t,s={}){let r=s.columns??fo,i=s.cwdMaxWidth??TC,o=b=>b==="age"?n[b].padStart(e[b]):n[b].padEnd(e[b]);if(t===void 0)return r.map((S,k)=>k===r.length-1?n[S]:o(S)).join(Lc);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>kf.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Lc);return b.length>t?b.slice(0,t):b}let d=r.filter(b=>!kf.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),u=t-d-l*Lc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:S}of a){if(S===c)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],A=Math.min(k,Math.max(0,p-1));f.set(S,A),p=Math.max(0,p-A)}f.set(c,Math.max(0,p));let h=r.length-1,m=(b,S,k)=>{if(b==="cwd")return _a(n[b],S).padEnd(S);let A=FC(n[b],S);return k?A:A.padEnd(S)},w=r.map((b,S)=>kf.has(b)?m(b,f.get(S)??0,S===h):o(b)).join(Lc);return w.length>t?w.slice(0,t):w}function FC(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function _a(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),s=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-s)}var Bc,fo,kf,po,Lc,TC,Nc=Y(()=>{"use strict";Sf();be();is();Bc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],fo=["session","state","age","cwd","title","agent","cost"],kf=new Set(["cwd","title"]),po={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Lc=" ",TC=32});import{spawn as WC}from"child_process";import{Writable as zC}from"stream";function Dc(n={}){let e=n.isTTY??process.stdout.isTTY===!0;if(n.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let t=n.env??process.env,s=KC(t);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=n.spawn??WC,i={...t};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
119
- `)});let c=new zC({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}
120
- `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function KC(n){let e=n.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let t=n.PAGER;return t!==void 0?t.length===0?null:t:"less"}var If=Y(()=>{"use strict"});import JC from"chalk";import{highlight as YC,supportsLanguage as Hc}from"cli-highlight";import jc from"string-width";function pr(n,e={}){switch(n.kind){case"user-text":{let t=xf(n.text,"\u258E ","user",void 0,n.sentBy,!0);if(n.attachments&&n.attachments.length>0)for(let s of n.attachments)t.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return t}case"agent-text":return xf(n.text," ","agent");case"agent-thought":return xf(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return wR(n,e.maxPlanItems??gR);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${n.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 Af(n,e){return fr(n,e).styled}function fr(n,e){let t=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.italicReset??"^:",o=e?.linkOpen??"^C^_",a=e?.linkReset??"^:",c="",d=0,l=!1,u=[],f=0;for(;f<n.length;){let p=n[f];if(p==="\\"&&f+1<n.length){let h=n[f+1];if(h==="*"||h==="_"||h==="`"||h==="["||h==="]"||h==="\\"){c+=h,d+=1,f+=2;continue}}if(p==="^"){c+="^^",d+=1,f+=1;continue}if(p==="*"&&n[f+1]==="*"){let h=n.indexOf("**",f+2);if(h!==-1&&h>f+2){let m=n.slice(f+2,h),y=fr(m,e),w=d;c+=`^+${y.styled}${r}`;for(let b of y.links)u.push({start:w+b.start,end:w+b.end,url:b.url});d+=y.cleanLength,y.ansi&&(l=!0),f=h+2;continue}}if(p==="*"&&n[f+1]!=="*"){let h=f>0?n[f-1]:"",m=n[f+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
117
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function EC(n){return n.split(/\s+/).filter(e=>e.length>0)}async function uo(){let n=await _c.readFile(O.config(),"utf8");return JSON.parse(n)}async function yf(n){await _c.writeFile(O.config(),JSON.stringify(n,null,2)+`
118
+ `,{encoding:"utf8",mode:384})}var lr=Y(()=>{"use strict";Ge();Ps();be();Ei();Pa()});async function un(n,e={},t=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()},t);try{return await s(n,{...e,signal:r.signal})}catch(c){throw o?new wf(n,t):c}finally{clearTimeout(a)}}async function Dn(n,e={},t=fetch){let s=new URL(`${n.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 un(s.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);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 My(n,e=fetch){let t=await un(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 un(`${n.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Qr(n,e=fetch){let t=await un(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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(n,e,t={},s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},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 fs(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function _y(n,e,t,s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function $y(n,e,t,s=fetch){let r=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Fy(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);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 Oy(n,e,t={},s=fetch){let r={q:e};t.sessionIds&&t.sessionIds.length>0&&(r.sessionIds=t.sessionIds);let i=await un(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Ly(n,e,t=fetch){let s=await un(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Oc(n,e){let t=n.filter(i=>i.cwd===e);if(t.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...t].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var wf,Ma=Y(()=>{"use strict";wf=class extends Error{constructor(t,s){super(`daemon did not respond within ${s}ms (${t})`);this.url=t;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function bf(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function By(n,e){let t=n??"?",s=bf(e);return s?`${t}${PC}${s}`:t}function Ny(n){return n??"?"}function Dy(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:vf(e,t)}function vf(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var PC,Sf=Y(()=>{"use strict";PC="\u2022"});function Hy(n){let e=n.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,s=[];for(let r of e){if(!Bc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Bc.join(", ")})`);if(t.has(r))throw new Error(`--columns: duplicate column "${r}"`);t.add(r),s.push(r)}return s}function ho(n,e=Date.now()){return{session:pt(n.sessionId),upstream:$C(n.upstreamSessionId,n.importedFromMachine),host:n.importedFromMachine??"-",state:FC(n.status,n.busy,n.awaitingInput,_C(n.compactionState),n.forkSynthesisState),agent:Ny(n.agentId),model:bf(n.currentModel)??"-",age:OC(n.updatedAt,e),title:n.title??"-",cwd:ct(n.cwd),cost:Dy(n.currentUsage)}}function _C(n){if(n==null||typeof n!="object")return!1;let e=n.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function $C(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function FC(n,e,t,s,r){return n==="cold"?"COLD":t?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 mo(n,e={}){let t=e.columns??fo,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 t)s[r]=LC(po[r],n.map(i=>i[r]));return s}function OC(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let s=Math.max(0,e-t),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 LC(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function ur(n,e,t,s={}){let r=s.columns??fo,i=s.cwdMaxWidth??MC,o=b=>b==="age"?n[b].padStart(e[b]):n[b].padEnd(e[b]);if(t===void 0)return r.map((S,k)=>k===r.length-1?n[S]:o(S)).join(Lc);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>kf.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Lc);return b.length>t?b.slice(0,t):b}let d=r.filter(b=>!kf.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),u=t-d-l*Lc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:S}of a){if(S===c)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],A=Math.min(k,Math.max(0,p-1));f.set(S,A),p=Math.max(0,p-A)}f.set(c,Math.max(0,p));let h=r.length-1,m=(b,S,k)=>{if(b==="cwd")return _a(n[b],S).padEnd(S);let A=BC(n[b],S);return k?A:A.padEnd(S)},w=r.map((b,S)=>kf.has(b)?m(b,f.get(S)??0,S===h):o(b)).join(Lc);return w.length>t?w.slice(0,t):w}function BC(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function _a(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),s=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-s)}var Bc,fo,kf,po,Lc,MC,Nc=Y(()=>{"use strict";Sf();be();os();Bc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],fo=["session","state","age","cwd","title","agent","cost"],kf=new Set(["cwd","title"]),po={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Lc=" ",MC=32});import{spawn as JC}from"child_process";import{Writable as YC}from"stream";function Dc(n={}){let e=n.isTTY??process.stdout.isTTY===!0;if(n.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let t=n.env??process.env,s=VC(t);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=n.spawn??JC,i={...t};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
119
+ `)});let c=new YC({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}
120
+ `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function VC(n){let e=n.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let t=n.PAGER;return t!==void 0?t.length===0?null:t:"less"}var If=Y(()=>{"use strict"});import QC from"chalk";import{highlight as GC,supportsLanguage as Hc}from"cli-highlight";import jc from"string-width";function pr(n,e={}){switch(n.kind){case"user-text":{let t=xf(n.text,"\u258E ","user",void 0,n.sentBy,!0);if(n.attachments&&n.attachments.length>0)for(let s of n.attachments)t.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return t}case"agent-text":return xf(n.text," ","agent");case"agent-thought":return xf(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return SR(n,e.maxPlanItems??bR);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${n.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 Af(n,e){return fr(n,e).styled}function fr(n,e){let t=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.italicReset??"^:",o=e?.linkOpen??"^C^_",a=e?.linkReset??"^:",c="",d=0,l=!1,u=[],f=0;for(;f<n.length;){let p=n[f];if(p==="\\"&&f+1<n.length){let h=n[f+1];if(h==="*"||h==="_"||h==="`"||h==="["||h==="]"||h==="\\"){c+=h,d+=1,f+=2;continue}}if(p==="^"){c+="^^",d+=1,f+=1;continue}if(p==="*"&&n[f+1]==="*"){let h=n.indexOf("**",f+2);if(h!==-1&&h>f+2){let m=n.slice(f+2,h),y=fr(m,e),w=d;c+=`^+${y.styled}${r}`;for(let b of y.links)u.push({start:w+b.start,end:w+b.end,url:b.url});d+=y.cleanLength,y.ansi&&(l=!0),f=h+2;continue}}if(p==="*"&&n[f+1]!=="*"){let h=f>0?n[f-1]:"",m=n[f+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
121
121
  `&&!/[A-Za-z0-9]/.test(h)){let w=-1;for(let b=f+1;b<n.length;b++){let S=n[b];if(S===`
122
122
  `)break;if(S!=="*"||n[b+1]==="*")continue;let k=n[b-1],A=n[b+1]??"";if(!(k===" "||k===" "||k==="*")&&!/[A-Za-z0-9]/.test(A)){w=b;break}}if(w!==-1&&w>f+1){let b=n.slice(f+1,w),S=fr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)u.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),f=w+1;continue}}}if(p==="_"){let h=f>0?n[f-1]:"",m=n[f+1]??"";if(m!==""&&m!==" "&&m!==" "&&m!==`
123
123
  `&&m!=="_"&&!/[A-Za-z0-9_]/.test(h)){let w=-1;for(let b=f+1;b<n.length;b++){let S=n[b];if(S===`
124
- `)break;if(S!=="_")continue;let k=n[b-1],A=n[b+1]??"";if(!(k===" "||k===" "||k==="_")&&!/[A-Za-z0-9_]/.test(A)){w=b;break}}if(w!==-1&&w>f+1){let b=n.slice(f+1,w),S=fr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)u.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),f=w+1;continue}}}if(p==="`"){let h=n.indexOf("`",f+1);if(h!==-1&&h>f+1){let m=n.slice(f+1,h),y=m.replace(/\^/g,"^^");c+=`${t}${y}${s}`,d+=m.length,f=h+1;continue}}if(p==="["){let h=n.indexOf("]",f+1);if(h!==-1&&n[h+1]==="("&&h>f+1){let m=-1;{let y=1,w=h+2;for(;w<n.length;){let b=n[w];if(b==="\\"&&w+1<n.length){w+=2;continue}if(b==="(")y+=1;else if(b===")"&&(y-=1,y===0)){m=w;break}w+=1}}if(m!==-1&&m>h+2){let y=n.slice(f+1,h),w=n.slice(h+2,m),b=fr(y,e),S=d,k=w.startsWith("file://"),A=VC.test(w),E=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(w),P=!k&&!A&&!E;k||P||A?c+=`${o}${b.styled}${a}`:(c+=`\x1B]8;;${w}\x1B\\${o}${b.styled}${a}\x1B]8;;\x1B\\`,l=!0);for(let H of b.links)u.push({start:S+H.start,end:S+H.end,url:H.url});d+=b.cleanLength,(k||A||P)&&u.push({start:S,end:d,url:w}),f=m+1;continue}}}c+=p,d+=1,f+=1}return{styled:c,links:u,cleanLength:d,ansi:l}}function QC(n){switch(n){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",italicReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",italicReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",italicReset:"^:^Y",codeReset:"^:^Y"}}}function Gy(n){switch(n){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",italicReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",italicReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",italicReset:"^:^+",codeReset:"^:^+"}}}function Xy(n,e){let{proseStyle:t,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=n.replace(/^\s+/,"").split(`
125
- `),l=!1,u="",f=[],p=i!==" ",h=(w,b,S=" ",k,A,E)=>{let P={prefix:S,body:w,bodyStyle:b};r!==void 0&&(P.prefixStyle=r),k&&k.length>0&&(P.links=k),A&&(P.ansi=!0),E!==void 0&&E>0&&(P.hangingIndent=E),c.push(P)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let w=ew(u,f);for(let b of w){let S={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),b.ansi&&(S.ansi=!0),c.push(S)}}else for(let w of f)h(w.replace(/\^/g,"^^"),t);f=[],u=""}};for(let w=0;w<d.length;w++){let b=d[w],S=b.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(b);continue}let k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let F=k[1].length,B=k[2]??"",N=s?F===1?"heading-1":F===2?"heading-2":"heading-3":t,j=s?Gy(N):o;h(Af(B,j),N,m());continue}let A=d[w+1];if(b.includes("|")&&A!==void 0&&GC(A)&&$a(b).length===$a(A).length){let F=$a(b),B=[],N=w+2;for(;N<d.length&&d[N].includes("|");)B.push($a(d[N])),N++;let j=rR(F,B,a);for(let G of j)r!==void 0&&(G.prefixStyle=r),c.push(G);w=N-1;continue}let E=b.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let F=E[1]??"",B=E[2]??"",N=fr(B,o),j=F.length+2,G=N.links.map(X=>({start:X.start+j,end:X.end+j,url:X.url}));h(`${F}\u2022 ${N.styled}`,t,m(),G,N.ansi,F.length+2);continue}let P=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(P){let F=P[1]??"",B=P[2]??"",N=P[3]??"",j=fr(N,o),G=F.length+B.length+2,X=j.links.map(V=>({start:V.start+G,end:V.end+G,url:V.url}));h(`${F}${B}. ${j.styled}`,t,m(),X,j.ansi,F.length+B.length+2);continue}let H=b.trim()==="",_=fr(b,o);h(_.styled,t,H?" ":m(),_.links,_.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function hr(n,e){return Xy(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function go(n){return Xy(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function $a(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],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){t.push(s.trim()),s="";continue}s+=o}return t.push(s.trim()),t}function GC(n){if(!n.includes("|"))return!1;let e=$a(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Uc(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return jc(e)}function eR(n){let e=[],t=0;for(;t<n.length;){let s=n[t];if(s===" "||s===" "){let o=t;for(;o<n.length&&(n[o]===" "||n[o]===" ");)o++;let a=n.slice(t,o);e.push({text:a,isWS:!0,width:jc(a)}),t=o;continue}let r="",i=t;for(;i<n.length;){let o=n[i];if(o===" "||o===" ")break;if(n[i]==="*"&&n[i+1]==="*"){let a=n.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=n.slice(i,a+2),i=a+2);continue}if(o==="*"&&n[i+1]!=="*"){let a=r.length>0?r[r.length-1]:i>0?n[i-1]:"",c=n[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let u=i+1;u<n.length;u++){if(n[u]!=="*"||n[u+1]==="*")continue;let p=n[u-1],h=n[u+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(h)){l=u;break}}if(l!==-1&&l>i+1){r+=n.slice(i,l+1),i=l+1;continue}}}if(o==="_"){let a=r.length>0?r[r.length-1]:i>0?n[i-1]:"",c=n[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let u=i+1;u<n.length;u++){if(n[u]!=="_")continue;let p=n[u-1],h=n[u+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(h)){l=u;break}}if(l!==-1&&l>i+1){r+=n.slice(i,l+1),i=l+1;continue}}}if(o==="`"){let a=n.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=n.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:Uc(r)}),t=i}return e}function tR(n,e){let t=[],s="",r=0;for(let i of n){let o=jc(i);r>0&&r+o>e?(t.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&t.push(s),t}function nR(n,e){if(e<=0)return n.length===0?[""]:[n.map(o=>o.text).join("")];let t=[],s="",r=0,i=()=>{t.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of n){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`")||o.text.includes("*")||o.text.includes("_"))t.push(o.text);else{let c=tR(o.text,e);for(let l=0;l<c.length-1;l++)t.push(c[l]);let d=c[c.length-1]??"";s=d,r=jc(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||t.length===0)&&i(),t}function sR(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let r=n.map(l=>Math.min(l,Zy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=n.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<t;f++){let p=n[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function rR(n,e,t){let s=n.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Uc(n[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Uc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(t!==void 0){let d=Math.max(s*Zy,t-XC-(s-1)*ZC);i=sR(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",w=i[m],b=nR(eR(y),w);f.push(b),b.length>p&&(p=b.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let w=0;w<s;w++){let b=f[w][m]??"",S=i[w],k=Uc(b),A=Af(b,u);y.push(A+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(n,"heading-3",Gy("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 ew(n,e){if(n.length===0||!Hc(n))return e.map(a=>({body:a,ansi:!1}));let t=e.join(`
126
- `),s=`${n}\0${t}`,r=Gr.get(s),i;if(r!==void 0)Gr.delete(s),Gr.set(s,r),i=r;else{let a;try{a=YC(t,{language:n,theme:iR,ignoreIllegals:!0})}catch{return e.map(c=>({body:c,ansi:!1}))}if(i=a.replace(/\x1b\[39m/g,"\x1B[37m"),Gr.size>=oR){let c=Gr.keys().next().value;c!==void 0&&Gr.delete(c)}Gr.set(s,i)}let o=i.split(`
127
- `);return o.length!==e.length?e.map(a=>({body:a,ansi:!1})):o.map((a,c)=>({body:a,ansi:a!==e[c]}))}function dR(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Hc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Hc("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let s=e.slice(t),r=aR[s];return r&&Hc(r)?r:""}function xf(n,e,t,s,r,i){let o=n.replace(/^\s+/,"").split(`
128
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??t,body:c,bodyStyle:t};i&&(d.fillRow=!0),a.push(d)}return a}function cR(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function fs(n){let e=Math.floor(n/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;if(t<60)return s===0?`${t}m`:`${t}m ${s}s`;let r=Math.floor(t/60),i=t%60;return i===0?`${r}h`:`${r}h ${i}m`}function tw(n){if(n.length<=4096&&n.split(`
124
+ `)break;if(S!=="_")continue;let k=n[b-1],A=n[b+1]??"";if(!(k===" "||k===" "||k==="_")&&!/[A-Za-z0-9_]/.test(A)){w=b;break}}if(w!==-1&&w>f+1){let b=n.slice(f+1,w),S=fr(b,e),k=d;c+=`^_${S.styled}${i}`;for(let A of S.links)u.push({start:k+A.start,end:k+A.end,url:A.url});d+=S.cleanLength,S.ansi&&(l=!0),f=w+1;continue}}}if(p==="`"){let h=n.indexOf("`",f+1);if(h!==-1&&h>f+1){let m=n.slice(f+1,h),y=m.replace(/\^/g,"^^");c+=`${t}${y}${s}`,d+=m.length,f=h+1;continue}}if(p==="["){let h=n.indexOf("]",f+1);if(h!==-1&&n[h+1]==="("&&h>f+1){let m=-1;{let y=1,w=h+2;for(;w<n.length;){let b=n[w];if(b==="\\"&&w+1<n.length){w+=2;continue}if(b==="(")y+=1;else if(b===")"&&(y-=1,y===0)){m=w;break}w+=1}}if(m!==-1&&m>h+2){let y=n.slice(f+1,h),w=n.slice(h+2,m),b=fr(y,e),S=d,k=w.startsWith("file://"),A=XC.test(w),E=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(w),P=!k&&!A&&!E;k||P||A?c+=`${o}${b.styled}${a}`:(c+=`\x1B]8;;${w}\x1B\\${o}${b.styled}${a}\x1B]8;;\x1B\\`,l=!0);for(let H of b.links)u.push({start:S+H.start,end:S+H.end,url:H.url});d+=b.cleanLength,(k||A||P)&&u.push({start:S,end:d,url:w}),f=m+1;continue}}}c+=p,d+=1,f+=1}return{styled:c,links:u,cleanLength:d,ansi:l}}function ZC(n){switch(n){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",italicReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",italicReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",italicReset:"^:^Y",codeReset:"^:^Y"}}}function Xy(n){switch(n){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",italicReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",italicReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",italicReset:"^:^+",codeReset:"^:^+"}}}function Zy(n,e){let{proseStyle:t,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=n.replace(/^\s+/,"").split(`
125
+ `),l=!1,u="",f=[],p=i!==" ",h=(w,b,S=" ",k,A,E)=>{let P={prefix:S,body:w,bodyStyle:b};r!==void 0&&(P.prefixStyle=r),k&&k.length>0&&(P.links=k),A&&(P.ansi=!0),E!==void 0&&E>0&&(P.hangingIndent=E),c.push(P)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let w=tw(u,f);for(let b of w){let S={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),b.ansi&&(S.ansi=!0),c.push(S)}}else for(let w of f)h(w.replace(/\^/g,"^^"),t);f=[],u=""}};for(let w=0;w<d.length;w++){let b=d[w],S=b.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(b);continue}let k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let F=k[1].length,B=k[2]??"",N=s?F===1?"heading-1":F===2?"heading-2":"heading-3":t,j=s?Xy(N):o;h(Af(B,j),N,m());continue}let A=d[w+1];if(b.includes("|")&&A!==void 0&&eR(A)&&$a(b).length===$a(A).length){let F=$a(b),B=[],N=w+2;for(;N<d.length&&d[N].includes("|");)B.push($a(d[N])),N++;let j=aR(F,B,a);for(let G of j)r!==void 0&&(G.prefixStyle=r),c.push(G);w=N-1;continue}let E=b.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let F=E[1]??"",B=E[2]??"",N=fr(B,o),j=F.length+2,G=N.links.map(X=>({start:X.start+j,end:X.end+j,url:X.url}));h(`${F}\u2022 ${N.styled}`,t,m(),G,N.ansi,F.length+2);continue}let P=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(P){let F=P[1]??"",B=P[2]??"",N=P[3]??"",j=fr(N,o),G=F.length+B.length+2,X=j.links.map(V=>({start:V.start+G,end:V.end+G,url:V.url}));h(`${F}${B}. ${j.styled}`,t,m(),X,j.ansi,F.length+B.length+2);continue}let H=b.trim()==="",_=fr(b,o);h(_.styled,t,H?" ":m(),_.links,_.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function hr(n,e){return Zy(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function go(n){return Zy(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function $a(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],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){t.push(s.trim()),s="";continue}s+=o}return t.push(s.trim()),t}function eR(n){if(!n.includes("|"))return!1;let e=$a(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Uc(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return jc(e)}function sR(n){let e=[],t=0;for(;t<n.length;){let s=n[t];if(s===" "||s===" "){let o=t;for(;o<n.length&&(n[o]===" "||n[o]===" ");)o++;let a=n.slice(t,o);e.push({text:a,isWS:!0,width:jc(a)}),t=o;continue}let r="",i=t;for(;i<n.length;){let o=n[i];if(o===" "||o===" ")break;if(n[i]==="*"&&n[i+1]==="*"){let a=n.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=n.slice(i,a+2),i=a+2);continue}if(o==="*"&&n[i+1]!=="*"){let a=r.length>0?r[r.length-1]:i>0?n[i-1]:"",c=n[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let u=i+1;u<n.length;u++){if(n[u]!=="*"||n[u+1]==="*")continue;let p=n[u-1],h=n[u+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(h)){l=u;break}}if(l!==-1&&l>i+1){r+=n.slice(i,l+1),i=l+1;continue}}}if(o==="_"){let a=r.length>0?r[r.length-1]:i>0?n[i-1]:"",c=n[i+1]??"";if(c!==""&&c!==" "&&c!==" "&&c!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let u=i+1;u<n.length;u++){if(n[u]!=="_")continue;let p=n[u-1],h=n[u+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(h)){l=u;break}}if(l!==-1&&l>i+1){r+=n.slice(i,l+1),i=l+1;continue}}}if(o==="`"){let a=n.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=n.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:Uc(r)}),t=i}return e}function rR(n,e){let t=[],s="",r=0;for(let i of n){let o=jc(i);r>0&&r+o>e?(t.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&t.push(s),t}function iR(n,e){if(e<=0)return n.length===0?[""]:[n.map(o=>o.text).join("")];let t=[],s="",r=0,i=()=>{t.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of n){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`")||o.text.includes("*")||o.text.includes("_"))t.push(o.text);else{let c=rR(o.text,e);for(let l=0;l<c.length-1;l++)t.push(c[l]);let d=c[c.length-1]??"";s=d,r=jc(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||t.length===0)&&i(),t}function oR(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let r=n.map(l=>Math.min(l,ew)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=n.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<t;f++){let p=n[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function aR(n,e,t){let s=n.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Uc(n[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Uc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(t!==void 0){let d=Math.max(s*ew,t-tR-(s-1)*nR);i=oR(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",w=i[m],b=iR(sR(y),w);f.push(b),b.length>p&&(p=b.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let w=0;w<s;w++){let b=f[w][m]??"",S=i[w],k=Uc(b),A=Af(b,u);y.push(A+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(n,"heading-3",Xy("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 tw(n,e){if(n.length===0||!Hc(n))return e.map(a=>({body:a,ansi:!1}));let t=e.join(`
126
+ `),s=`${n}\0${t}`,r=Gr.get(s),i;if(r!==void 0)Gr.delete(s),Gr.set(s,r),i=r;else{let a;try{a=GC(t,{language:n,theme:dR,ignoreIllegals:!0})}catch{return e.map(c=>({body:c,ansi:!1}))}if(i=a.replace(/\x1b\[39m/g,"\x1B[37m"),Gr.size>=cR){let c=Gr.keys().next().value;c!==void 0&&Gr.delete(c)}Gr.set(s,i)}let o=i.split(`
127
+ `);return o.length!==e.length?e.map(a=>({body:a,ansi:!1})):o.map((a,c)=>({body:a,ansi:a!==e[c]}))}function uR(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Hc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Hc("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let s=e.slice(t),r=lR[s];return r&&Hc(r)?r:""}function xf(n,e,t,s,r,i){let o=n.replace(/^\s+/,"").split(`
128
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??t,body:c,bodyStyle:t};i&&(d.fillRow=!0),a.push(d)}return a}function fR(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function ps(n){let e=Math.floor(n/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;if(t<60)return s===0?`${t}m`:`${t}m ${s}s`;let r=Math.floor(t/60),i=t%60;return i===0?`${r}h`:`${r}h ${i}m`}function nw(n){if(n.length<=4096&&n.split(`
129
129
  `).length<=40)return{text:n,truncated:!1};let s=n.slice(0,4096),r=n.length>4096,i=s.split(`
130
130
  `);return i.length>40&&(s=i.slice(0,40).join(`
131
- `),r=!0),{text:s,truncated:r}}function Fa(n,e=Date.now()){let t=n.initialTitle,s=n.latestTitle,r=t.toLowerCase(),i=s.toLowerCase(),o;s===t||i.includes(r)?o=s:r.includes(i)?o=t:o=`${t} \xB7 ${s}`;let a=[];if(n.detail){let l=n.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||n.detailFull!==void 0&&o.includes(n.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=n.locations?.[0]?.path??n.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(n.startedAt!==void 0){let l=n.endedAt??e;o=`${o} \xB7 ${fs(l-n.startedAt)}`}let c={prefix:` ${pR(n.status)} `,prefixStyle:hR(n.status),body:o,bodyStyle:bR(n.status)};a.length>0&&(c.links=a);let d=[c];return n.status==="failed"&&n.errorText&&d.push({prefix:" ",body:Te(n.errorText),bodyStyle:"tool-status-fail"}),d}function nw(n){if(n.editDiff!==void 0)return[];let e=[],t=n.detailFull??n.detail;if(t)for(let s of t.split(`
131
+ `),r=!0),{text:s,truncated:r}}function Fa(n,e=Date.now()){let t=n.initialTitle,s=n.latestTitle,r=t.toLowerCase(),i=s.toLowerCase(),o;s===t||i.includes(r)?o=s:r.includes(i)?o=t:o=`${t} \xB7 ${s}`;let a=[];if(n.detail){let l=n.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||n.detailFull!==void 0&&o.includes(n.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=n.locations?.[0]?.path??n.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(n.startedAt!==void 0){let l=n.endedAt??e;o=`${o} \xB7 ${ps(l-n.startedAt)}`}let c={prefix:` ${gR(n.status)} `,prefixStyle:yR(n.status),body:o,bodyStyle:kR(n.status)};a.length>0&&(c.links=a);let d=[c];return n.status==="failed"&&n.errorText&&d.push({prefix:" ",body:Te(n.errorText),bodyStyle:"tool-status-fail"}),d}function sw(n){if(n.editDiff!==void 0)return[];let e=[],t=n.detailFull??n.detail;if(t)for(let s of t.split(`
132
132
  `))e.push({prefix:" ",body:Te(s),bodyStyle:"dim"});if(n.status==="failed"&&n.errorText&&e.push({prefix:" ",body:Te(n.errorText),bodyStyle:"tool-status-fail"}),n.resultText){let s=n.resultText.split(`
133
- `),r=n.locations?.[0]?.path??n.detailFull??n.detail,i=dR(r);if(i.length>0){let o=ew(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"});n.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function rw(n){sw=n>=0?n:0}function Cf(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let d=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${cR(d)})`}else{let d=uR(n),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(ct(n.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return n.path&&s.push(o(!1)),s;if(r)return n.path&&(s.push(o(!0)),s.push(t.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=Rf(n,{maxLines:1/0});if(a.length===0)return n.path&&s.push(o(!1)),s;n.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...hr(c)),s.length>0&&s.unshift({body:""}),s}function iw(n){let e=wt(n.oldText).split(`
133
+ `),r=n.locations?.[0]?.path??n.detailFull??n.detail,i=uR(r);if(i.length>0){let o=tw(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"});n.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function iw(n){rw=n>=0?n:0}function Cf(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let d=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${fR(d)})`}else{let d=hR(n),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(ct(n.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return n.path&&s.push(o(!1)),s;if(r)return n.path&&(s.push(o(!0)),s.push(t.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=Rf(n,{maxLines:1/0});if(a.length===0)return n.path&&s.push(o(!1)),s;n.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...hr(c)),s.length>0&&s.unshift({body:""}),s}function ow(n){let e=wt(n.oldText).split(`
134
134
  `),t=wt(n.newText).split(`
135
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),t.length>0&&t[t.length-1]===""&&t.pop(),{oldLines:e,newLines:t}}function uR(n){let{oldLines:e,newLines:t}=iw(n),s=0,r=0;for(let i of ow(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Qy(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function Rf(n,e={}){let t=e.maxLines??lR,s=e.contextLines??sw,{oldLines:r,newLines:i}=iw(n),o=ow(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(Qy(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(Qy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=t-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(`
136
- `)}function ow(n,e){let t=0,s=Math.min(n.length,e.length);for(;t<s&&n[t]===e[t];)t++;let r=n.length,i=e.length;for(;r>t&&i>t&&n[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<t;a++)o.push({op:"=",text:n[a]});o.push(...fR(n.slice(t,r),e.slice(t,i)));for(let a=r;a<n.length;a++)o.push({op:"=",text:n[a]});return o}function fR(n,e){let t=n.length,s=e.length;if(t===0||s===0){let c=[];for(let d of n)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c--)for(let d=s-1;d>=0;d--)n[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<t&&a<s;)n[o]===e[a]?(i.push({op:"=",text:n[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:n[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<t;)i.push({op:"-",text:n[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Tf(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function pR(n){switch(n){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 hR(n){switch(n){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 aw(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...hr(n.plan));let t=n.status;if(t!==void 0){let s=mR(t);s!==null&&e.push(s)}return e}function mR(n){switch(n){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 yR(n,e){let t=n.length;if(e<=0||t<=e)return{start:0,end:t};let s=n.findIndex(d=>(d.status??"pending")==="in_progress"),r=n.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:t-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(t,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function wR(n,e){let t=n.stopped===!0,r=n.amended===!0?"tool-status-cancelled":"tool-status-fail",o=n.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":t?r:"plan",a=n.entries.length,{start:c,end:d}=yR(n.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of n.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=n.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",w=m==="completed"?"plan-done":m==="in_progress"?t?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Af(b,QC(w));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:w})}return f}function bR(n){switch(n){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 VC,Zy,XC,ZC,ut,iR,oR,Gr,aR,lR,sw,gR,yo=Y(()=>{"use strict";be();or();VC=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;Zy=6,XC=2,ZC=3;ut=new JC.Instance({level:3}),iR={keyword:ut.blueBright,built_in:ut.cyan,type:ut.cyanBright,literal:ut.blue,number:ut.greenBright,string:ut.yellow,regexp:ut.red,comment:ut.gray,function:ut.yellow,title:ut.yellow,class:ut.yellowBright,attr:ut.cyan,attribute:ut.cyan,variable:ut.white,params:ut.white,meta:ut.magenta,symbol:ut.magenta,addition:ut.greenBright,deletion:ut.redBright,section:ut.cyan,tag:ut.cyan,name:ut.cyanBright},oR=512,Gr=new Map;aR={".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"};lR=40,sw=Number.POSITIVE_INFINITY;gR=5});import{highlight as vR,supportsLanguage as SR}from"cli-highlight";async function cw(n,e={}){n||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
135
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),t.length>0&&t[t.length-1]===""&&t.pop(),{oldLines:e,newLines:t}}function hR(n){let{oldLines:e,newLines:t}=ow(n),s=0,r=0;for(let i of aw(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Gy(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function Rf(n,e={}){let t=e.maxLines??pR,s=e.contextLines??rw,{oldLines:r,newLines:i}=ow(n),o=aw(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(Gy(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(Gy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=t-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(`
136
+ `)}function aw(n,e){let t=0,s=Math.min(n.length,e.length);for(;t<s&&n[t]===e[t];)t++;let r=n.length,i=e.length;for(;r>t&&i>t&&n[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<t;a++)o.push({op:"=",text:n[a]});o.push(...mR(n.slice(t,r),e.slice(t,i)));for(let a=r;a<n.length;a++)o.push({op:"=",text:n[a]});return o}function mR(n,e){let t=n.length,s=e.length;if(t===0||s===0){let c=[];for(let d of n)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c--)for(let d=s-1;d>=0;d--)n[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<t&&a<s;)n[o]===e[a]?(i.push({op:"=",text:n[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:n[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<t;)i.push({op:"-",text:n[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Tf(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function gR(n){switch(n){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 yR(n){switch(n){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 dw(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...hr(n.plan));let t=n.status;if(t!==void 0){let s=wR(t);s!==null&&e.push(s)}return e}function wR(n){switch(n){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 vR(n,e){let t=n.length;if(e<=0||t<=e)return{start:0,end:t};let s=n.findIndex(d=>(d.status??"pending")==="in_progress"),r=n.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:t-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(t,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function SR(n,e){let t=n.stopped===!0,r=n.amended===!0?"tool-status-cancelled":"tool-status-fail",o=n.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":t?r:"plan",a=n.entries.length,{start:c,end:d}=vR(n.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of n.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=n.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",w=m==="completed"?"plan-done":m==="in_progress"?t?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Af(b,ZC(w));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:w})}return f}function kR(n){switch(n){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 XC,ew,tR,nR,ut,dR,cR,Gr,lR,pR,rw,bR,yo=Y(()=>{"use strict";be();or();XC=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;ew=6,tR=2,nR=3;ut=new QC.Instance({level:3}),dR={keyword:ut.blueBright,built_in:ut.cyan,type:ut.cyanBright,literal:ut.blue,number:ut.greenBright,string:ut.yellow,regexp:ut.red,comment:ut.gray,function:ut.yellow,title:ut.yellow,class:ut.yellowBright,attr:ut.cyan,attribute:ut.cyan,variable:ut.white,params:ut.white,meta:ut.magenta,symbol:ut.magenta,addition:ut.greenBright,deletion:ut.redBright,section:ut.cyan,tag:ut.cyan,name:ut.cyanBright},cR=512,Gr=new Map;lR={".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"};pR=40,rw=Number.POSITIVE_INFINITY;bR=5});import{highlight as IR,supportsLanguage as xR}from"cli-highlight";async function lw(n,e={}){n||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
137
137
  `),process.exit(2));let t=e.fold===!0?"?fold=true":"",s=await Oe(`/v1/sessions/${encodeURIComponent(n)}/diff${t}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Oe(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,l;try{l=Nn(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
138
138
  `),process.exit(1)}let u=Gi(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:Xi(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
139
139
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
140
140
  `);return}let i=Dc({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Ef(r,a)),await i.flush()}function Ef(n,e){if(n.length===0)return`No file edits found in this session.
141
- `;let t=[],s=[...n].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=xR(r,e);i!==null&&t.push(i)}return t.length===0?`No file edits found in this session.
142
- `:t.join("")}function kR(n){let e=[];for(let t of n.hunks){let s=Rf(t,{maxLines:1/0});IR(s)&&e.push({body:s,oldCount:dw(t.oldText),newCount:dw(t.newText)})}return e}function IR(n){if(n.length===0)return!1;for(let e of n.split(`
143
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function xR(n,e){let t=kR(n);if(t.length===0)return null;let s=[];s.push(`diff --hydra a/${n.path} b/${n.path}`),n.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${n.path}`)):(s.push(`--- a/${n.path}`),s.push(`+++ b/${n.path}`));let r=t.length;t.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(`
141
+ `;let t=[],s=[...n].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=RR(r,e);i!==null&&t.push(i)}return t.length===0?`No file edits found in this session.
142
+ `:t.join("")}function AR(n){let e=[];for(let t of n.hunks){let s=Rf(t,{maxLines:1/0});CR(s)&&e.push({body:s,oldCount:cw(t.oldText),newCount:cw(t.newText)})}return e}function CR(n){if(n.length===0)return!1;for(let e of n.split(`
143
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function RR(n,e){let t=AR(n);if(t.length===0)return null;let s=[];s.push(`diff --hydra a/${n.path} b/${n.path}`),n.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${n.path}`)):(s.push(`--- a/${n.path}`),s.push(`+++ b/${n.path}`));let r=t.length;t.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
144
144
  `)+`
145
145
 
146
- `;return!e||!SR("diff")?i:vR(i,{language:"diff"})}function dw(n){if(n.length===0)return 0;let e=n.split(`
147
- `);return e[e.length-1]===""&&e.pop(),e.length}var Pf=Y(()=>{"use strict";lr();zr();hc();yo();If()});async function lw(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
146
+ `;return!e||!xR("diff")?i:IR(i,{language:"diff"})}function cw(n){if(n.length===0)return 0;let e=n.split(`
147
+ `);return e[e.length-1]===""&&e.pop(),e.length}var Pf=Y(()=>{"use strict";lr();zr();hc();yo();If()});async function uw(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
148
148
  `),process.exit(2));let t=await Oe(`/v1/sessions/${encodeURIComponent(n)}`,{expectStatus:[200,404]}),s=t.status===200?t.body.status:void 0,i=(await Oe(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,o;try{o=Nn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
149
149
  `),process.exit(1)}let a=$f(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Gi(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:Xi(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
150
150
  `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=Dc({disabled:e.noPager===!0});f.stream.write(qc(a,e.verbose===!0)),f.stream.write(`
151
- `),f.stream.write(Ef(d??[],u)),await f.flush();return}process.stdout.write(qc(a,e.verbose===!0))}function $f(n,e){let t=n.session,s=n.history,r=zm(s),i=Bu(s),o=Nu(s),a=t.currentUsage,c=Date.parse(t.createdAt),d=Date.parse(t.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:t.sessionId,...t.upstreamSessionId!==void 0?{upstreamSessionId:t.upstreamSessionId}:{},...t.title!==void 0?{title:t.title}:{},cwd:t.cwd,agentId:t.agentId,...t.currentModel!==void 0?{currentModel:t.currentModel}:{},status:e,createdAt:t.createdAt,updatedAt:t.updatedAt,synopsis:t.synopsis??null,summarizedThroughEntry:t.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 qc(n,e){let t=[],s=a=>a.padEnd(14);t.push(`${s("Session:")}${n.sessionId}`),n.upstreamSessionId&&t.push(`${s("Upstream:")}${n.upstreamSessionId}`),n.title&&t.push(`${s("Title:")}${n.title}`),t.push(`${s("Cwd:")}${n.cwd}`);let r=n.currentModel?` \xB7 ${n.currentModel}`:"";t.push(`${s("Agent:")}${n.agentId}${r}`),t.push(`${s("Status:")}${n.status}`),t.push(`${s("Created:")}${n.createdAt}`),t.push(`${s("Last active:")}${n.updatedAt}`),n.duration.totalMs!==null&&t.push(`${s("Duration:")}${CR(n.duration.totalMs)}`),t.push(`${s("Turns:")}${n.turns}`);let i=[];if(n.cost.amount!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.amount.toFixed(4)}`)}else if(n.cost.cumulative!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.cumulative.toFixed(4)} (cumulative)`)}if(n.cost.inputTokens!==null||n.cost.outputTokens!==null){let a=[];n.cost.inputTokens!==null&&a.push(`${n.cost.inputTokens.toLocaleString()} in`),n.cost.outputTokens!==null&&a.push(`${n.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&t.push(`${s("Cost:")}${i.join(" | ")}`),n.synopsis){t.push(""),t.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(n.synopsis.goal&&t.push(`${a}${c("Goal:")}${n.synopsis.goal}`),n.synopsis.outcome&&t.push(`${a}${c("Outcome:")}${n.synopsis.outcome}`),n.synopsis.rejected_approaches&&n.synopsis.rejected_approaches.length>0){t.push(`${a}${c("Rejected approaches:")}`);for(let d of n.synopsis.rejected_approaches)t.push(`${a} - ${d}`)}if(n.synopsis.open_threads&&n.synopsis.open_threads.length>0){t.push(`${a}${c("Open threads:")}`);for(let d of n.synopsis.open_threads)t.push(`${a} - ${d}`)}if(n.synopsis.files_touched&&n.synopsis.files_touched.length>0){t.push(`${a}${c("Files touched:")}`);for(let d of n.synopsis.files_touched)t.push(`${a} - ${d}`)}if(n.synopsis.tools_used&&n.synopsis.tools_used.length>0){t.push(`${a}${c("Tools used:")}`);for(let d of n.synopsis.tools_used)t.push(`${a} - ${d}`)}}else t.push(""),t.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(n.tools.length>0){t.push("");let a=n.tools.reduce((l,u)=>l+u.count,0);t.push(`Tools (${a} calls):`);let c=e?n.tools:n.tools.slice(0,Mf),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)t.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&n.tools.length>Mf&&t.push(` ... ${n.tools.length-Mf} more (use --verbose to see all)`)}let o=e?n.files:n.files.map(a=>{let c=a.byTool.filter(l=>AR.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){t.push("");let a=e?"Files touched":"Files edited";t.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,_f),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(", ");t.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else t.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>_f&&t.push(` ... ${o.length-_f} more (use --verbose to see all)`)}return t.join(`
151
+ `),f.stream.write(Ef(d??[],u)),await f.flush();return}process.stdout.write(qc(a,e.verbose===!0))}function $f(n,e){let t=n.session,s=n.history,r=zm(s),i=Bu(s),o=Nu(s),a=t.currentUsage,c=Date.parse(t.createdAt),d=Date.parse(t.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:t.sessionId,...t.upstreamSessionId!==void 0?{upstreamSessionId:t.upstreamSessionId}:{},...t.title!==void 0?{title:t.title}:{},cwd:t.cwd,agentId:t.agentId,...t.currentModel!==void 0?{currentModel:t.currentModel}:{},status:e,createdAt:t.createdAt,updatedAt:t.updatedAt,synopsis:t.synopsis??null,summarizedThroughEntry:t.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 qc(n,e){let t=[],s=a=>a.padEnd(14);t.push(`${s("Session:")}${n.sessionId}`),n.upstreamSessionId&&t.push(`${s("Upstream:")}${n.upstreamSessionId}`),n.title&&t.push(`${s("Title:")}${n.title}`),t.push(`${s("Cwd:")}${n.cwd}`);let r=n.currentModel?` \xB7 ${n.currentModel}`:"";t.push(`${s("Agent:")}${n.agentId}${r}`),t.push(`${s("Status:")}${n.status}`),t.push(`${s("Created:")}${n.createdAt}`),t.push(`${s("Last active:")}${n.updatedAt}`),n.duration.totalMs!==null&&t.push(`${s("Duration:")}${ER(n.duration.totalMs)}`),t.push(`${s("Turns:")}${n.turns}`);let i=[];if(n.cost.amount!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.amount.toFixed(4)}`)}else if(n.cost.cumulative!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.cumulative.toFixed(4)} (cumulative)`)}if(n.cost.inputTokens!==null||n.cost.outputTokens!==null){let a=[];n.cost.inputTokens!==null&&a.push(`${n.cost.inputTokens.toLocaleString()} in`),n.cost.outputTokens!==null&&a.push(`${n.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&t.push(`${s("Cost:")}${i.join(" | ")}`),n.synopsis){t.push(""),t.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(n.synopsis.goal&&t.push(`${a}${c("Goal:")}${n.synopsis.goal}`),n.synopsis.outcome&&t.push(`${a}${c("Outcome:")}${n.synopsis.outcome}`),n.synopsis.rejected_approaches&&n.synopsis.rejected_approaches.length>0){t.push(`${a}${c("Rejected approaches:")}`);for(let d of n.synopsis.rejected_approaches)t.push(`${a} - ${d}`)}if(n.synopsis.open_threads&&n.synopsis.open_threads.length>0){t.push(`${a}${c("Open threads:")}`);for(let d of n.synopsis.open_threads)t.push(`${a} - ${d}`)}if(n.synopsis.files_touched&&n.synopsis.files_touched.length>0){t.push(`${a}${c("Files touched:")}`);for(let d of n.synopsis.files_touched)t.push(`${a} - ${d}`)}if(n.synopsis.tools_used&&n.synopsis.tools_used.length>0){t.push(`${a}${c("Tools used:")}`);for(let d of n.synopsis.tools_used)t.push(`${a} - ${d}`)}}else t.push(""),t.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(n.tools.length>0){t.push("");let a=n.tools.reduce((l,u)=>l+u.count,0);t.push(`Tools (${a} calls):`);let c=e?n.tools:n.tools.slice(0,Mf),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)t.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&n.tools.length>Mf&&t.push(` ... ${n.tools.length-Mf} more (use --verbose to see all)`)}let o=e?n.files:n.files.map(a=>{let c=a.byTool.filter(l=>TR.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){t.push("");let a=e?"Files touched":"Files edited";t.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,_f),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(", ");t.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else t.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>_f&&t.push(` ... ${o.length-_f} more (use --verbose to see all)`)}return t.join(`
152
152
  `)+`
153
- `}function CR(n){if(n<0)return"0s";let e=Math.floor(n/1e3),t=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return t>0&&o.push(`${t}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 Mf,_f,AR,Ff=Y(()=>{"use strict";lr();zr();Du();hc();If();Pf();Mf=10,_f=15,AR=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Pw={};Ll(Pw,{assertKnownAgent:()=>Jc,canonicalAgentId:()=>Oa,resolveAgentIdOrExit:()=>Yc,runAgentsAdd:()=>jf,runAgentsInstall:()=>Bf,runAgentsList:()=>Lf,runAgentsLogs:()=>Df,runAgentsPin:()=>Uf,runAgentsRefresh:()=>Vc,runAgentsRemove:()=>qf,runAgentsSet:()=>Hf,runAgentsSync:()=>Nf,runAgentsUninstall:()=>Wf,runRegistryPin:()=>Qc});import*as Kc from"fs/promises";import*as Tw from"path";async function Lf(){let e=(await Oe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
153
+ `}function ER(n){if(n<0)return"0s";let e=Math.floor(n/1e3),t=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return t>0&&o.push(`${t}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 Mf,_f,TR,Ff=Y(()=>{"use strict";lr();zr();Du();hc();If();Pf();Mf=10,_f=15,TR=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Mw={};Ll(Mw,{assertKnownAgent:()=>Jc,canonicalAgentId:()=>Oa,resolveAgentIdOrExit:()=>Yc,runAgentsAdd:()=>jf,runAgentsInstall:()=>Bf,runAgentsList:()=>Lf,runAgentsLogs:()=>Df,runAgentsPin:()=>Uf,runAgentsRefresh:()=>Vc,runAgentsRemove:()=>qf,runAgentsSet:()=>Hf,runAgentsSync:()=>Nf,runAgentsUninstall:()=>Wf,runRegistryPin:()=>Qc});import*as Kc from"fs/promises";import*as Ew from"path";async function Lf(){let e=(await Oe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
154
154
  `);return}let t=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:Fs(s.id,t.map(a=>a.id)),name:Fs(s.name,t.map(a=>a.name)),version:Fs(s.version,t.map(a=>a.version)),source:Fs(s.source,t.map(a=>a.source)),distributions:Fs(s.distributions,t.map(a=>a.distributions)),installed:Fs(s.installed,t.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
155
155
  `);for(let a of t)process.stdout.write(i(a)+`
156
156
  `);let o=e.fetchedAt!==void 0?` (synced ${lo(e.fetchedAt)})`:"";process.stdout.write(`
@@ -170,13 +170,13 @@ Registry version: ${e.version}${o}
170
170
  `);process.stdout.write(`
171
171
  Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
172
172
  `)}async function Df(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
173
- `),process.exit(2);return}let t=O.agentLogFile(n);await oo(t,e,"No log file (agent never ran?)")}async function Hf(n,e){let t=await Ie();if(!n){let c=await Rw()??Of(await uo());process.stdout.write(`${Cw(c)}
173
+ `),process.exit(2);return}let t=O.agentLogFile(n);await oo(t,e,"No log file (agent never ran?)")}async function Hf(n,e){let t=await Ie();if(!n){let c=await Tw()??Of(await uo());process.stdout.write(`${Rw(c)}
174
174
  `);return}let s;try{let a=await Oe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(t.agents[n]!==void 0)&&s!==void 0&&!s.includes(n)){let a=n.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)n=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${n}' is ambiguous (matches ${c.join(", ")}).
175
175
  `),process.exit(1);return}else{process.stderr.write(`hydra agent set: '${n}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
176
176
  `),process.exit(1);return}}e!==void 0?await th(n,e):await Ri(n);let i=Of(await uo());e!==void 0&&n!==i.agent&&process.stdout.write(`Default model for ${n} is now ${e}.
177
- `),process.stdout.write(`${Cw(i)}
178
- `);let o=await Rw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Ew(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
179
- `))}function Cw(n){return`Default agent is ${Ew(n)}`}function Ew(n){return n.model!==void 0?`${n.agent} with ${n.model}`:n.agent}function Of(n){let e=typeof n.defaultAgent=="string"?n.defaultAgent:"(unset)",s=(n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Rw(){try{let n=await Oe("/v1/config",{rethrowNetworkError:!0});return n.ok?Of(n.body):void 0}catch{return}}async function Vc(){let e=(await Oe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
177
+ `),process.stdout.write(`${Rw(i)}
178
+ `);let o=await Tw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Pw(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
179
+ `))}function Rw(n){return`Default agent is ${Pw(n)}`}function Pw(n){return n.model!==void 0?`${n.agent} with ${n.model}`:n.agent}function Of(n){let e=typeof n.defaultAgent=="string"?n.defaultAgent:"(unset)",s=(n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Tw(){try{let n=await Oe("/v1/config",{rethrowNetworkError:!0});return n.ok?Of(n.body):void 0}catch{return}}async function Vc(){let e=(await Oe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
180
180
  `)}async function Uf(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
181
181
  `),process.exit(2);return}await nh(n,e),e===void 0?process.stdout.write(`Cleared version pin for ${n}.
182
182
  `):process.stdout.write(`Pinned ${n} to ${e}.
@@ -186,51 +186,51 @@ Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
186
186
  `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function qf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent remove <id>
187
187
  `),process.exit(2);return}await Ul(n,void 0),process.stdout.write(`Removed local agent ${n}.
188
188
  `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Wf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
189
- `),process.exit(2);return}let e=await Yc(n,"hydra agent uninstall"),t=bn();if(t===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
190
- `),process.exit(1);return}let s=Tw.join(O.agentsDir(),t,e),r=!1;try{await Kc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
189
+ `),process.exit(2);return}let e=await Yc(n,"hydra agent uninstall"),t=vn();if(t===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
190
+ `),process.exit(1);return}let s=Ew.join(O.agentsDir(),t,e),r=!1;try{await Kc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
191
191
  `);return}await Kc.rm(s,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${t}). Next session using it will re-install.
192
192
  `)}async function Qc(n){await sh(n),process.stdout.write(n?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
193
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Fs(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}var Gc=Y(()=>{"use strict";Ge();be();_i();Ea();lr()});var Xc,Os,bo,La,Mw,Ba,zf,Zc,ei,_w,ti,$w,ni,Fw,si,vo,So,Ow,ko,Lw,Bw,Nw,Kf,Dw,el,tl,Na,Hw,Uw,Da=Y(()=>{"use strict";Xc="\x1B[?2004h",Os="\x1B[?2004l",bo="\x1B[200~",La="\x1B[201~",Mw="\x1B[?1049l",Ba="\x1B[?7h",zf="\x1B[?7l",Zc="\x1B[?25h",ei="\x1B[?1l",_w="\x1B[>1u",ti="\x1B[<u",$w="\x1B[>4;2m",ni="\x1B[>4;0m",Fw="\x1B[>5;1m",si="\x1B[>5;0m",vo="\x1B[?1000l",So="\x1B[?1002l",Ow="\x1B[?1003l",ko="\x1B[?1006l",Lw="\x1B[?1015l",Bw="\x1B[?w",Nw="\x1B[=24;1w",Kf="\x1B[=0;0w",Dw="\x1B]22;pointer\x07",el="\x1B]22;default\x07",tl="\x1B[?1004h",Na="\x1B[?1004l",Hw="\x1B[?2026h",Uw="\x1B[?2026l"});function Hn(){process.stdout.write(ti),process.stdout.write(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(vo),process.stdout.write(So),process.stdout.write(ko),process.stdout.write(ei),process.stdout.write("\x1B>")}function Jt(n){return n.width??80}function Ls(n){return n.height??24}function Un(n,e){let t=Jt(n),s=Ls(n),r=e.contentWidth??TR,i=Math.max(10,t-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((t-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=jw.repeat(a-2),p=$R(f,e.title);n.moveTo(l,u),n.dim.noFormat(ER),FR(n,p),n.dim.noFormat(PR);for(let h=1;h<=c;h++)n.moveTo(l,u+h),n.dim.noFormat(qw),e.overlay&&n.noFormat(" ".repeat(o)),n.moveTo(l+a-1,u+h),n.dim.noFormat(qw);return n.moveTo(l,u+d-1),n.dim.noFormat(MR+jw.repeat(a-2)+_R),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function $R(n,e){if(!e)return{dashes:n};let t=` ${e} `;if(t.length+4>n.length)return{dashes:n};let s=2;return{dashes:n.slice(0,s)+" ".repeat(t.length)+n.slice(s+t.length),title:{offset:s,text:t}}}function FR(n,e){if(!e.title){n.dim.noFormat(e.dashes);return}n.dim.noFormat(e.dashes.slice(0,e.title.offset)),n.brightCyan.noFormat(e.title.text),n.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function Xe(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function Ha(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function ps(n){let{term:e,render:t,onKey:s,onResize:r,onMouse:i}=n,o=n.hideCursor!==!1;return t(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??t)()},l=(h,m,y)=>{c||s(h,m,y,p)},u=(h,m)=>{c||!i||i(h,m,p)},f=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",u),e.grabInput(!1),ie({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),n.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{f(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",u)):e.grabInput({}),ie({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var TR,jw,qw,ER,PR,MR,_R,ri=Y(()=>{"use strict";Hr();Da();TR=64,jw="\u2500",qw="\u2502",ER="\u250C",PR="\u2510",MR="\u2514",_R="\u2518"});function Ww(n){let e=(n.name&&n.name.length>0?n.name:void 0)??(n.description&&n.description.length>0?n.description:void 0);return e?`${e} (${n.id})`:n.id}function BR(n,e,t){let s={title:`Agent "${n}" needs to be set up`,description:e?.description??OR,footer:LR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),t&&t.length>0){s.authMethods=t;let r=t.map((c,d)=>({index:d,label:`[${d+1}] ${Ww(c)}`,method:c}));s.methodLines=r;let i=Math.min(t.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=t.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function NR(n,e,t=0){if(n==="CTRL_C"||n==="CTRL_D")return{kind:"cancel"};if(n==="ESCAPE")return{kind:"back"};if(n==="ENTER"||n==="KP_ENTER")return t===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(n)){let s=Number(n)-1;return s<t?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&n.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function DR(n){return typeof n!="object"||n===null?!1:n.code===q.AuthRequired}function zw(n){if(typeof n!="object"||n===null)return;let e=n.data;if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let s=t[Mt];if(!(typeof s!="object"||s===null))return s}function HR(n){let e=zw(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function UR(n){let e=zw(n);if(!e)return;let t=e.authMethods;if(!Array.isArray(t))return;let s=[];for(let r of t){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 Kw(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!DR(e))throw e;let t=HR(e)??n.fallbackAgentId??"",s=UR(e),r=await n.resolveOnboarding(t),i=await n.showBanner(t,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function jR(n,e,t){n.grabInput(!1),ie({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Hn(),n.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
193
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Fs(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}var Gc=Y(()=>{"use strict";Ge();be();_i();Ea();lr()});var Xc,Os,bo,La,_w,Ba,zf,Zc,ei,$w,ti,Fw,ni,Ow,si,vo,So,Lw,ko,Bw,Nw,Dw,Kf,Hw,el,tl,Na,Uw,jw,Da=Y(()=>{"use strict";Xc="\x1B[?2004h",Os="\x1B[?2004l",bo="\x1B[200~",La="\x1B[201~",_w="\x1B[?1049l",Ba="\x1B[?7h",zf="\x1B[?7l",Zc="\x1B[?25h",ei="\x1B[?1l",$w="\x1B[>1u",ti="\x1B[<u",Fw="\x1B[>4;2m",ni="\x1B[>4;0m",Ow="\x1B[>5;1m",si="\x1B[>5;0m",vo="\x1B[?1000l",So="\x1B[?1002l",Lw="\x1B[?1003l",ko="\x1B[?1006l",Bw="\x1B[?1015l",Nw="\x1B[?w",Dw="\x1B[=24;1w",Kf="\x1B[=0;0w",Hw="\x1B]22;pointer\x07",el="\x1B]22;default\x07",tl="\x1B[?1004h",Na="\x1B[?1004l",Uw="\x1B[?2026h",jw="\x1B[?2026l"});function Hn(){process.stdout.write(ti),process.stdout.write(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(vo),process.stdout.write(So),process.stdout.write(ko),process.stdout.write(ei),process.stdout.write("\x1B>")}function Jt(n){return n.width??80}function Ls(n){return n.height??24}function Un(n,e){let t=Jt(n),s=Ls(n),r=e.contentWidth??MR,i=Math.max(10,t-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((t-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=qw.repeat(a-2),p=LR(f,e.title);n.moveTo(l,u),n.dim.noFormat(_R),BR(n,p),n.dim.noFormat($R);for(let h=1;h<=c;h++)n.moveTo(l,u+h),n.dim.noFormat(Ww),e.overlay&&n.noFormat(" ".repeat(o)),n.moveTo(l+a-1,u+h),n.dim.noFormat(Ww);return n.moveTo(l,u+d-1),n.dim.noFormat(FR+qw.repeat(a-2)+OR),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function LR(n,e){if(!e)return{dashes:n};let t=` ${e} `;if(t.length+4>n.length)return{dashes:n};let s=2;return{dashes:n.slice(0,s)+" ".repeat(t.length)+n.slice(s+t.length),title:{offset:s,text:t}}}function BR(n,e){if(!e.title){n.dim.noFormat(e.dashes);return}n.dim.noFormat(e.dashes.slice(0,e.title.offset)),n.brightCyan.noFormat(e.title.text),n.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function Xe(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function Ha(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function hs(n){let{term:e,render:t,onKey:s,onResize:r,onMouse:i}=n,o=n.hideCursor!==!1;return t(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??t)()},l=(h,m,y)=>{c||s(h,m,y,p)},u=(h,m)=>{c||!i||i(h,m,p)},f=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",u),e.grabInput(!1),ie({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),n.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{f(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",u)):e.grabInput({}),ie({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var MR,qw,Ww,_R,$R,FR,OR,ri=Y(()=>{"use strict";Hr();Da();MR=64,qw="\u2500",Ww="\u2502",_R="\u250C",$R="\u2510",FR="\u2514",OR="\u2518"});function zw(n){let e=(n.name&&n.name.length>0?n.name:void 0)??(n.description&&n.description.length>0?n.description:void 0);return e?`${e} (${n.id})`:n.id}function HR(n,e,t){let s={title:`Agent "${n}" needs to be set up`,description:e?.description??NR,footer:DR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),t&&t.length>0){s.authMethods=t;let r=t.map((c,d)=>({index:d,label:`[${d+1}] ${zw(c)}`,method:c}));s.methodLines=r;let i=Math.min(t.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=t.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function UR(n,e,t=0){if(n==="CTRL_C"||n==="CTRL_D")return{kind:"cancel"};if(n==="ESCAPE")return{kind:"back"};if(n==="ENTER"||n==="KP_ENTER")return t===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(n)){let s=Number(n)-1;return s<t?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&n.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function jR(n){return typeof n!="object"||n===null?!1:n.code===q.AuthRequired}function Kw(n){if(typeof n!="object"||n===null)return;let e=n.data;if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let s=t[Mt];if(!(typeof s!="object"||s===null))return s}function qR(n){let e=Kw(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function WR(n){let e=Kw(n);if(!e)return;let t=e.authMethods;if(!Array.isArray(t))return;let s=[];for(let r of t){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 Jw(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!jR(e))throw e;let t=qR(e)??n.fallbackAgentId??"",s=WR(e),r=await n.resolveOnboarding(t),i=await n.showBanner(t,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function zR(n,e,t){n.grabInput(!1),ie({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Hn(),n.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
194
194
  `);let r=t?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{n.grabInput({}),ie({src:"grab",site:"runTerminalAuthSpawn.reGrab",on:!0})}catch{}};try{let a=r(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",c=>{o(),i({exitCode:c})}),a.on("error",c=>{o(),process.stdout.write(`
195
195
  failed to spawn ${e.command}: ${c.message}
196
196
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
197
197
  failed to spawn ${e.command}: ${a.message}
198
- `),i({exitCode:-1})}})}function qR(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function Jf(n,e){let t;try{t=await e.authenticate(n.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(qR(t)){let s={command:t.command,args:t.args,env:t.env,cwd:t.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Jw(n,e,t,s,r){Hn();let i=BR(e,t,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=Un(n,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(n.moveTo(f.contentX,f.contentY+h),n.brightYellow.noFormat(Xe(` ${a}`,p)),h++),c&&(n.moveTo(f.contentX,f.contentY+h),n.brightRed.noFormat(Xe(` ${c}`,p)),h++),n.moveTo(f.contentX,f.contentY+h),n.brightWhite.bold.noFormat(Xe(` ${i.title}`,p)),h+=2,n.moveTo(f.contentX,f.contentY+h),n.noFormat(Xe(` ${i.description}`,p)),h++,i.command&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Run: "),n.brightWhite.noFormat(Xe(i.command,p-7)),h++),i.url&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Docs: "),n.brightWhite.noFormat(Xe(i.url,p-7)),h++),i.methodLines){n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" "),n.noFormat(Xe(m.label,p-3)),h++}return h++,n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return ps({term:n,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=NR(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 ${Ww(y)}\u2026`,d();let w=r.runTerminalAuth??(b=>jR(n,b));(async()=>{let b=await Jf(y,{authenticate:r.authenticate,runTerminalAuth:w});if(b.kind==="terminal-completed"){h("terminal-completed");return}if(b.kind==="retry"){h("retry");return}if(b.kind==="error"){c=b.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var OR,LR,Yf=Y(()=>{"use strict";Hr();Td();Pd();ri();OR="This agent requires authentication before use.",LR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Xw}from"timers/promises";function XR(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var YR,VR,QR,GR,xo,Vf=Y(()=>{"use strict";Pa();no();YR=200,VR=5e3,QR=2,GR=60,xo=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 t=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(t,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(t),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),Xw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=YR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Vr(s,this.opts.subprotocols);this.bindStream(cs(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>=GR)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 ${t}ms`),await Xw(t),this.destroyed)return;t=Math.min(t*QR,VR)}}bindStream(e){this.current=e,e.onMessage(t=>{if(XR(t)&&t.id!==null){let s=this.pendingRequests.get(t.id);s&&(this.pendingRequests.delete(t.id),s.resolve(t))}for(let s of this.messageHandlers)s(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=t??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}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(t){this.scheduleReconnect(t);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(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let s of this.closeHandlers)s(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
199
- `)}}});function Zw(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let i of e){let o=t.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=t.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function ii(n){return{outcome:{outcome:"selected",optionId:Zw(n,["allow_once","allow_always"])}}}function eb(n){return{outcome:{outcome:"selected",optionId:Zw(n,["reject_once","reject_always"])}}}function rl(n){return n&&typeof n=="object"?n:void 0}function Ua(n){return typeof n=="string"&&n.length>0?n:void 0}function tb(n){let e=rl(n),t=rl(e?.toolCall),s={paths:[]};if(!t)return s;let r=Ua(t.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Ua(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let d of a)o(rl(d)?.path);let c=rl(t.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Ua(c.command);d&&(s.command=d);let l=Ua(c.url);l&&(s.url=l);let u=Ua(c.description);u&&(s.description=u)}return s}function nb(n){let e=[];return n.command?e.push(`$ ${n.command}`):n.url?e.push(n.url):n.paths.length===1?e.push(n.paths[0]):n.paths.length>1?e.push(`${n.paths[0]} (+${n.paths.length-1} more)`):n.description&&e.push(n.description),e.join(" ").replace(/\s+/g," ").trim()}var il=Y(()=>{"use strict"});function G0(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Sb(n){let t=(n.split("-",1)[0]??n).split("."),s=Number(t[0]),r=Number(t[1]),i=Number(t[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function X0(n,e){let t=Sb(n),s=Sb(e);if(!t||!s)return n!==e;for(let r=0;r<3;r++){let i=t[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function ja(){if(gr!==void 0)return gr;if(G0())return gr=null,gr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:kb,version:ve}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&X0(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}gr={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{t.config?.set?.("update",void 0)}catch{}gr=null}}catch{gr=null}return gr}function qa(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${kb}`}var kb,gr,Xf=Y(()=>{"use strict";cn();kb="@hydra-acp/cli"});import*as Wa from"fs/promises";import*as Zf from"path";async function za(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Zf.resolve(tt(e)),s;try{s=await Wa.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return s.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function Ib(n){let e=[],t=new Set,s=r=>{t.has(r)||(t.add(r),e.push(r))};s(n),n.startsWith("/Users/")?s("/home/"+n.slice(7)):n.startsWith("/home/")&&s("/Users/"+n.slice(6));for(let r of e)try{if((await Wa.stat(r)).isDirectory())return r}catch{}return null}async function xb(n){let e=n.lastIndexOf("/"),t,s,r;e===-1?(t="",s=n,r="."):(t=n.slice(0,e+1),s=n.slice(e+1),r=e===0?"/":t);let i=Zf.resolve(tt(r)),o;try{o=(await Wa.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,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:t,basePrefix:s,matches:c}}var ep=Y(()=>{"use strict";Ge()});var Ab,Cb,Rb,Tb=Y(()=>{"use strict";Ab="hydra-acp/question/list",Cb="hydra-acp/question/answer",Rb="hydra-acp/question/dismiss"});import{EventEmitter as Z0}from"events";import{WebSocket as eT}from"ws";function tT(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=ra(s.hostname);r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(t.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(t.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new eT(n,e,t),o=()=>{i.off("error",a),s(cs(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Eb(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??tT,c=["acp.v1",`hydra-acp-token.${n.token}`],d=await a(n.wsUrl,c),l=new zt(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=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Fc(n,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 tp(l,d,u,n,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(()=>{}),us(n,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[Mt]:{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 tp,Pb=Y(()=>{"use strict";ia();Ma();jr();no();_t();tp=class extends Z0{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,s,r,i){super(),this._conn=e,this._stream=t,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(()=>{}),us(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,t){return super.once(e,t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}}});var np,ll,Mb=Y(()=>{"use strict";yo();or();np=class{_listeners=new Map;on(e,t){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},ll=class extends np{_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 t=ds(e);if(!t)return 0;switch(t.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),t.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),t.kind){case"agent-text":{let s=t.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=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=go(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=go(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(s.detail=t.detail),this._toolStates.set(t.toolCallId,s);let r=Fa(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(t.toolCallId);if(!s)return 0;t.title!==void 0&&(s.latestTitle=t.title),t.status!==void 0&&(s.status=t.status),t.detail!==void 0&&(s.detail=t.detail),t.errorText!==void 0&&(s.errorText=t.errorText);let r=Fa(s),i=this._toolRanges.get(t.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(t.toolCallId,i,r),r.length}default:{let s=pr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return hr(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t,s){let r=s.length-t.length;if(this._lines.splice(t.start,t.length,...s),t.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>t.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.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 t=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function iT(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Ka(n,e,t,s){Hn();let r=iT(e,t??nT),i=0,o=null,a=null,c=()=>{let E=Ls(n)-8;return Math.max(1,Math.min(sT,e.length,E))},d=()=>{let E=c(),P=Math.max(0,e.length-E);i>P&&(i=P),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},u=null,f=0,p=(E,P)=>{if(E<i||E>=i+f)return;let H=e[E];if(!H)return;let _=P.contentW,F=P.contentY+2+(E-i);n.moveTo(P.contentX,F);let B=E===r?"\u276F":" ",N=H.description??H.name,j=` ${B} ${H.id}`;if(E===r){let G=`${j} ${N}`;n.brightWhite.bgBlue.noFormat(Ha(Xe(G,_),_))}else{let G=_-j.length-2,X=G>1?` ${Xe(N,G)}`:"";n.noFormat(j),X.length>0&&n.dim.noFormat(X);let V=j.length+X.length;V<_&&n.noFormat(" ".repeat(_-V))}},h=(E,P)=>{let H=E.contentY+2+f+1;n.moveTo(E.contentX,H);let F=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>P?` (${r+1}/${e.length})`:""}`,B=Ha(Xe(F,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{d();let E=c(),P=E+4,H=Math.min(rT,Math.max(40,Jt(n)-8)),_=Un(n,{contentHeight:P,contentWidth:H,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=_,u=_,f=Math.min(E,e.length-i),o=_.contentY+2,n.moveTo(_.contentX,_.contentY),n.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let F=Math.min(e.length,i+E);for(let B=i;B<F;B++)p(B,_);return h(_,E),_},y=()=>m(),w=E=>{let P=u;if(P===null){m();return}let H=c(),_=i;if(l(),i!==_){m();return}f=Math.min(H,e.length-i),E!==r&&(p(E,P),p(r,P)),h(P,H)},b=()=>{if(r<e.length-1){let E=r;r++,w(E)}},S=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=u;if(E===null){m();return}let P=c();d(),f=Math.min(P,e.length-i);let H=Math.min(e.length,i+P);for(let _=i;_<H;_++)p(_,E);for(let _=f;_<P;_++){let F=E.contentY+2+_;n.moveTo(E.contentX,F),n.noFormat(" ".repeat(E.contentW))}h(E,P)},A=E=>{let P=c(),H=Math.max(0,e.length-P);if(H===0)return;let _=Math.max(0,Math.min(H,i+E));_!==i&&(i=_,k())};return ps({term:n,render:y,overlay:s?.overlay===!0,onKey:(E,P,H,_)=>{if(E==="CTRL_C"||E==="CTRL_D"){_({kind:"cancel"});return}if(E==="ESCAPE"){_({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let F=e[r];F&&_({kind:"select",agentId:F.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){b();return}if(H?.isCharacter){let F=E.toLowerCase();if(F==="s"){let B=e[r];B&&_({kind:"select",agentId:B.id,persist:!0});return}if(F==="j"){b();return}if(F==="k"){S();return}}},onMouse:(E,P,H)=>{if(E==="MOUSE_WHEEL_UP"){A(-1);return}if(E==="MOUSE_WHEEL_DOWN"){A(1);return}if(E==="MOUSE_MOTION"){let G=P?.y;if(typeof G!="number"||o===null)return;let X=G-o;if(X<0||X>=f)return;let V=i+X;if(V<0||V>=e.length)return;if(V!==r){let ye=r;r=V,w(ye)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let _=P?.x,F=P?.y;if(a!==null&&typeof _=="number"&&typeof F=="number"&&(_<a.x||_>=a.x+a.w||F<a.y||F>=a.y+a.h)){H({kind:"back"});return}if(typeof F!="number"||o===null)return;let B=F-o;if(B<0||B>=f)return;let N=i+B;if(N<0||N>=e.length)return;let j=e[N];j&&H({kind:"select",agentId:j.id,persist:!1})}})}var nT,sT,rT,sp=Y(()=>{"use strict";ri();nT="opencode",sT=20,rT=88});import oT from"path";function Ja(n){return _b[oT.extname(n).toLowerCase()]??null}function aT(n){return Ja(n)!==null}function rp(n){let e=n.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let t=e[1].toLowerCase();if(!dT.has(t))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:t,data:s,sizeBytes:i}}function cT(n){return rp(n)!==null}function In(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function $b(n){let e=n.trim();if(e.length===0)return null;let t=[],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(!cT(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!aT(o))return null;t.push(o)}return t.length>0?t:null}var hs,_b,dT,ul=Y(()=>{"use strict";hs=10*1024*1024,_b={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};dT=new Set(Object.values(_b))});import{spawn as lT}from"child_process";import ip from"fs/promises";import uT from"os";import fT from"path";async function pl(n={}){let e={...op,...n};return e.platform==="darwin"?gT(e):e.platform==="linux"?yT(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Lb(n={}){let e={...op,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Ro(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Ro(e,"xclip"))t="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 Ya(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Bb(n,e={}){let{target:t="both",...s}=e,r={...op,...s},i=await pT(r,n,t);if(i.ok)return i;let o=hT(r,n,t);return o.ok||o.reason!==Nb?o:i}async function pT(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await fl(n.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let r=t==="clipboard"||t==="both",i=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await Ro(n,"wl-copy")?Ob(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await Ro(n,"xclip")?Ob(n,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 ${n.platform}`}}async function Ob(n,e,t,s,r,i,o){let a=t;if(i){try{await fl(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await fl(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await fl(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function hT(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Fb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Fb} bytes)`};let i=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${s}\x07`;return n.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??mT)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Nb}}function mT(n){let e=[process.stderr,process.stdout];for(let t of e)if(t&&t.isTTY)try{return t.write(n),!0}catch{}return!1}async function gT(n){let e=fT.join(n.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),t=["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 t)s.push("-e",r);try{await Db(n.spawn,"osascript",s);let r=await kT(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await ip.unlink(e).catch(()=>{})}try{let r=await Ya(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function yT(n){let e=await wT(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await ST(n,e),s=vT(t);if(s)try{let r=await Ya(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>hs?{ok:!1,reason:`clipboard image is ${In(r.length)}, max ${In(hs)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Ya(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function wT(n){return n.env.WAYLAND_DISPLAY&&await Ro(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Ro(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function vT(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of bT)if(e.has(t))return t;return null}async function ST(n,e){try{return(await Ya(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
198
+ `),i({exitCode:-1})}})}function KR(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function Jf(n,e){let t;try{t=await e.authenticate(n.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(KR(t)){let s={command:t.command,args:t.args,env:t.env,cwd:t.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Yw(n,e,t,s,r){Hn();let i=HR(e,t,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=Un(n,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(n.moveTo(f.contentX,f.contentY+h),n.brightYellow.noFormat(Xe(` ${a}`,p)),h++),c&&(n.moveTo(f.contentX,f.contentY+h),n.brightRed.noFormat(Xe(` ${c}`,p)),h++),n.moveTo(f.contentX,f.contentY+h),n.brightWhite.bold.noFormat(Xe(` ${i.title}`,p)),h+=2,n.moveTo(f.contentX,f.contentY+h),n.noFormat(Xe(` ${i.description}`,p)),h++,i.command&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Run: "),n.brightWhite.noFormat(Xe(i.command,p-7)),h++),i.url&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Docs: "),n.brightWhite.noFormat(Xe(i.url,p-7)),h++),i.methodLines){n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" "),n.noFormat(Xe(m.label,p-3)),h++}return h++,n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return hs({term:n,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=UR(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 ${zw(y)}\u2026`,d();let w=r.runTerminalAuth??(b=>zR(n,b));(async()=>{let b=await Jf(y,{authenticate:r.authenticate,runTerminalAuth:w});if(b.kind==="terminal-completed"){h("terminal-completed");return}if(b.kind==="retry"){h("retry");return}if(b.kind==="error"){c=b.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var NR,DR,Yf=Y(()=>{"use strict";Hr();Td();Pd();ri();NR="This agent requires authentication before use.",DR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Zw}from"timers/promises";function t0(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var GR,XR,ZR,e0,xo,Vf=Y(()=>{"use strict";Pa();no();GR=200,XR=5e3,ZR=2,e0=60,xo=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 t=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(t,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(t),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),Zw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=GR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Vr(s,this.opts.subprotocols);this.bindStream(ls(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>=e0)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 ${t}ms`),await Zw(t),this.destroyed)return;t=Math.min(t*ZR,XR)}}bindStream(e){this.current=e,e.onMessage(t=>{if(t0(t)&&t.id!==null){let s=this.pendingRequests.get(t.id);s&&(this.pendingRequests.delete(t.id),s.resolve(t))}for(let s of this.messageHandlers)s(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=t??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}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(t){this.scheduleReconnect(t);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(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let s of this.closeHandlers)s(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
199
+ `)}}});function eb(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let i of e){let o=t.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=t.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function ii(n){return{outcome:{outcome:"selected",optionId:eb(n,["allow_once","allow_always"])}}}function tb(n){return{outcome:{outcome:"selected",optionId:eb(n,["reject_once","reject_always"])}}}function rl(n){return n&&typeof n=="object"?n:void 0}function Ua(n){return typeof n=="string"&&n.length>0?n:void 0}function nb(n){let e=rl(n),t=rl(e?.toolCall),s={paths:[]};if(!t)return s;let r=Ua(t.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Ua(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let d of a)o(rl(d)?.path);let c=rl(t.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Ua(c.command);d&&(s.command=d);let l=Ua(c.url);l&&(s.url=l);let u=Ua(c.description);u&&(s.description=u)}return s}function sb(n){let e=[];return n.command?e.push(`$ ${n.command}`):n.url?e.push(n.url):n.paths.length===1?e.push(n.paths[0]):n.paths.length>1?e.push(`${n.paths[0]} (+${n.paths.length-1} more)`):n.description&&e.push(n.description),e.join(" ").replace(/\s+/g," ").trim()}var il=Y(()=>{"use strict"});function eT(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function kb(n){let t=(n.split("-",1)[0]??n).split("."),s=Number(t[0]),r=Number(t[1]),i=Number(t[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function tT(n,e){let t=kb(n),s=kb(e);if(!t||!s)return n!==e;for(let r=0;r<3;r++){let i=t[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function ja(){if(gr!==void 0)return gr;if(eT())return gr=null,gr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:Ib,version:ve}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&tT(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}gr={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{t.config?.set?.("update",void 0)}catch{}gr=null}}catch{gr=null}return gr}function qa(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${Ib}`}var Ib,gr,Xf=Y(()=>{"use strict";cn();Ib="@hydra-acp/cli"});import*as Wa from"fs/promises";import*as Zf from"path";async function za(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Zf.resolve(tt(e)),s;try{s=await Wa.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return s.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function xb(n){let e=[],t=new Set,s=r=>{t.has(r)||(t.add(r),e.push(r))};s(n),n.startsWith("/Users/")?s("/home/"+n.slice(7)):n.startsWith("/home/")&&s("/Users/"+n.slice(6));for(let r of e)try{if((await Wa.stat(r)).isDirectory())return r}catch{}return null}async function Ab(n){let e=n.lastIndexOf("/"),t,s,r;e===-1?(t="",s=n,r="."):(t=n.slice(0,e+1),s=n.slice(e+1),r=e===0?"/":t);let i=Zf.resolve(tt(r)),o;try{o=(await Wa.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,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:t,basePrefix:s,matches:c}}var ep=Y(()=>{"use strict";Ge()});var Cb,Rb,Tb,Eb=Y(()=>{"use strict";Cb="hydra-acp/question/list",Rb="hydra-acp/question/answer",Tb="hydra-acp/question/dismiss"});import{EventEmitter as nT}from"events";import{WebSocket as sT}from"ws";function rT(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=ra(s.hostname);r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(t.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(t.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new sT(n,e,t),o=()=>{i.off("error",a),s(ls(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Pb(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??rT,c=["acp.v1",`hydra-acp-token.${n.token}`],d=await a(n.wsUrl,c),l=new zt(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=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Fc(n,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 tp(l,d,u,n,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(()=>{}),fs(n,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[Mt]:{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 tp,Mb=Y(()=>{"use strict";ia();Ma();jr();no();_t();tp=class extends nT{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,s,r,i){super(),this._conn=e,this._stream=t,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(()=>{}),fs(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,t){return super.once(e,t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}}});var np,ll,_b=Y(()=>{"use strict";yo();or();np=class{_listeners=new Map;on(e,t){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},ll=class extends np{_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 t=cs(e);if(!t)return 0;switch(t.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),t.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),t.kind){case"agent-text":{let s=t.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=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=go(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=go(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(s.detail=t.detail),this._toolStates.set(t.toolCallId,s);let r=Fa(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(t.toolCallId);if(!s)return 0;t.title!==void 0&&(s.latestTitle=t.title),t.status!==void 0&&(s.status=t.status),t.detail!==void 0&&(s.detail=t.detail),t.errorText!==void 0&&(s.errorText=t.errorText);let r=Fa(s),i=this._toolRanges.get(t.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(t.toolCallId,i,r),r.length}default:{let s=pr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return hr(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t,s){let r=s.length-t.length;if(this._lines.splice(t.start,t.length,...s),t.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>t.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.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 t=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function dT(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Ka(n,e,t,s){Hn();let r=dT(e,t??iT),i=0,o=null,a=null,c=()=>{let E=Ls(n)-8;return Math.max(1,Math.min(oT,e.length,E))},d=()=>{let E=c(),P=Math.max(0,e.length-E);i>P&&(i=P),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},u=null,f=0,p=(E,P)=>{if(E<i||E>=i+f)return;let H=e[E];if(!H)return;let _=P.contentW,F=P.contentY+2+(E-i);n.moveTo(P.contentX,F);let B=E===r?"\u276F":" ",N=H.description??H.name,j=` ${B} ${H.id}`;if(E===r){let G=`${j} ${N}`;n.brightWhite.bgBlue.noFormat(Ha(Xe(G,_),_))}else{let G=_-j.length-2,X=G>1?` ${Xe(N,G)}`:"";n.noFormat(j),X.length>0&&n.dim.noFormat(X);let V=j.length+X.length;V<_&&n.noFormat(" ".repeat(_-V))}},h=(E,P)=>{let H=E.contentY+2+f+1;n.moveTo(E.contentX,H);let F=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>P?` (${r+1}/${e.length})`:""}`,B=Ha(Xe(F,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{d();let E=c(),P=E+4,H=Math.min(aT,Math.max(40,Jt(n)-8)),_=Un(n,{contentHeight:P,contentWidth:H,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=_,u=_,f=Math.min(E,e.length-i),o=_.contentY+2,n.moveTo(_.contentX,_.contentY),n.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let F=Math.min(e.length,i+E);for(let B=i;B<F;B++)p(B,_);return h(_,E),_},y=()=>m(),w=E=>{let P=u;if(P===null){m();return}let H=c(),_=i;if(l(),i!==_){m();return}f=Math.min(H,e.length-i),E!==r&&(p(E,P),p(r,P)),h(P,H)},b=()=>{if(r<e.length-1){let E=r;r++,w(E)}},S=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=u;if(E===null){m();return}let P=c();d(),f=Math.min(P,e.length-i);let H=Math.min(e.length,i+P);for(let _=i;_<H;_++)p(_,E);for(let _=f;_<P;_++){let F=E.contentY+2+_;n.moveTo(E.contentX,F),n.noFormat(" ".repeat(E.contentW))}h(E,P)},A=E=>{let P=c(),H=Math.max(0,e.length-P);if(H===0)return;let _=Math.max(0,Math.min(H,i+E));_!==i&&(i=_,k())};return hs({term:n,render:y,overlay:s?.overlay===!0,onKey:(E,P,H,_)=>{if(E==="CTRL_C"||E==="CTRL_D"){_({kind:"cancel"});return}if(E==="ESCAPE"){_({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let F=e[r];F&&_({kind:"select",agentId:F.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){b();return}if(H?.isCharacter){let F=E.toLowerCase();if(F==="s"){let B=e[r];B&&_({kind:"select",agentId:B.id,persist:!0});return}if(F==="j"){b();return}if(F==="k"){S();return}}},onMouse:(E,P,H)=>{if(E==="MOUSE_WHEEL_UP"){A(-1);return}if(E==="MOUSE_WHEEL_DOWN"){A(1);return}if(E==="MOUSE_MOTION"){let G=P?.y;if(typeof G!="number"||o===null)return;let X=G-o;if(X<0||X>=f)return;let V=i+X;if(V<0||V>=e.length)return;if(V!==r){let ye=r;r=V,w(ye)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let _=P?.x,F=P?.y;if(a!==null&&typeof _=="number"&&typeof F=="number"&&(_<a.x||_>=a.x+a.w||F<a.y||F>=a.y+a.h)){H({kind:"back"});return}if(typeof F!="number"||o===null)return;let B=F-o;if(B<0||B>=f)return;let N=i+B;if(N<0||N>=e.length)return;let j=e[N];j&&H({kind:"select",agentId:j.id,persist:!1})}})}var iT,oT,aT,sp=Y(()=>{"use strict";ri();iT="opencode",oT=20,aT=88});import cT from"path";function Ja(n){return $b[cT.extname(n).toLowerCase()]??null}function lT(n){return Ja(n)!==null}function rp(n){let e=n.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let t=e[1].toLowerCase();if(!uT.has(t))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:t,data:s,sizeBytes:i}}function fT(n){return rp(n)!==null}function xn(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function Fb(n){let e=n.trim();if(e.length===0)return null;let t=[],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(!fT(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!lT(o))return null;t.push(o)}return t.length>0?t:null}var ms,$b,uT,ul=Y(()=>{"use strict";ms=10*1024*1024,$b={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};uT=new Set(Object.values($b))});import{spawn as pT}from"child_process";import ip from"fs/promises";import hT from"os";import mT from"path";async function pl(n={}){let e={...op,...n};return e.platform==="darwin"?bT(e):e.platform==="linux"?vT(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Bb(n={}){let e={...op,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Ro(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Ro(e,"xclip"))t="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 Ya(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Nb(n,e={}){let{target:t="both",...s}=e,r={...op,...s},i=await gT(r,n,t);if(i.ok)return i;let o=yT(r,n,t);return o.ok||o.reason!==Db?o:i}async function gT(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await fl(n.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let r=t==="clipboard"||t==="both",i=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await Ro(n,"wl-copy")?Lb(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await Ro(n,"xclip")?Lb(n,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 ${n.platform}`}}async function Lb(n,e,t,s,r,i,o){let a=t;if(i){try{await fl(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await fl(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await fl(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function yT(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Ob)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Ob} bytes)`};let i=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${s}\x07`;return n.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??wT)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Db}}function wT(n){let e=[process.stderr,process.stdout];for(let t of e)if(t&&t.isTTY)try{return t.write(n),!0}catch{}return!1}async function bT(n){let e=mT.join(n.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),t=["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 t)s.push("-e",r);try{await Hb(n.spawn,"osascript",s);let r=await AT(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await ip.unlink(e).catch(()=>{})}try{let r=await Ya(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function vT(n){let e=await ST(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await xT(n,e),s=IT(t);if(s)try{let r=await Ya(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>ms?{ok:!1,reason:`clipboard image is ${xn(r.length)}, max ${xn(ms)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Ya(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ap(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function ST(n){return n.env.WAYLAND_DISPLAY&&await Ro(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Ro(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function IT(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of kT)if(e.has(t))return t;return null}async function xT(n,e){try{return(await Ya(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
200
200
  `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function ap(n){return n.replace(/\r\n?/g,`
201
- `)}async function Ro(n,e){try{return await Db(n.spawn,"which",[e]),!0}catch{return!1}}async function kT(n,e){try{let t=await ip.readFile(n);return e&&await ip.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>hs?{ok:!1,reason:`clipboard image is ${In(t.length)}, max ${In(hs)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ja(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Db(n,e,t){return new Promise((s,r)=>{let i=n(e,t);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 fl(n,e,t,s){return new Promise((r,i)=>{let o=n(e,t,{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 Ya(n,e,t){return new Promise((s,r)=>{let i=n(e,t),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 op,Fb,Nb,bT,hl=Y(()=>{"use strict";ul();op={platform:process.platform,env:process.env,spawn:lT,tmpdir:uT.tmpdir};Fb=74994;Nb="no TTY available for OSC 52 clipboard write";bT=["image/png","image/jpeg","image/gif","image/webp"]});function xT(n,e){return`[pasted #${n} +${e} lines]`}var IT,Va,dp,AT,Bs,cp=Y(()=>{"use strict";IT=/\[pasted #(\d+) \+\d+ lines\]/g,Va=/\[pasted #(\d+) \+\d+ lines\]$/,dp=/^\[pasted #(\d+) \+\d+ lines\]/;AT=500,Bs=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>AT&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,t,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,t=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...t],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 t=e.text.split(`
202
- `).length;if(this.collapsePastes&&t>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(xT(s,t))}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"alt-p":return[{type:"prev-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
203
- `)}expandPastes(e){return e.replace(IT,(t,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:t})}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(`
201
+ `)}async function Ro(n,e){try{return await Hb(n.spawn,"which",[e]),!0}catch{return!1}}async function AT(n,e){try{let t=await ip.readFile(n);return e&&await ip.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>ms?{ok:!1,reason:`clipboard image is ${xn(t.length)}, max ${xn(ms)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ja(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Hb(n,e,t){return new Promise((s,r)=>{let i=n(e,t);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 fl(n,e,t,s){return new Promise((r,i)=>{let o=n(e,t,{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 Ya(n,e,t){return new Promise((s,r)=>{let i=n(e,t),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 op,Ob,Db,kT,hl=Y(()=>{"use strict";ul();op={platform:process.platform,env:process.env,spawn:pT,tmpdir:hT.tmpdir};Ob=74994;Db="no TTY available for OSC 52 clipboard write";kT=["image/png","image/jpeg","image/gif","image/webp"]});function RT(n,e){return`[pasted #${n} +${e} lines]`}var CT,Va,dp,TT,Bs,cp=Y(()=>{"use strict";CT=/\[pasted #(\d+) \+\d+ lines\]/g,Va=/\[pasted #(\d+) \+\d+ lines\]$/,dp=/^\[pasted #(\d+) \+\d+ lines\]/;TT=500,Bs=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>TT&&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,t,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,t=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...t],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 t=e.text.split(`
202
+ `).length;if(this.collapsePastes&&t>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(RT(s,t))}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"alt-p":return[{type:"prev-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
203
+ `)}expandPastes(e){return e.replace(CT,(t,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:t})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
204
204
  `)){this.insertText(e);return}let t=this.currentLine();this.setCurrentLine(t.slice(0,this.col)+e+t.slice(this.col)),this.col+=e.length}insertText(e){let t=e.split(`
205
205
  `);if(t.length===1){this.insertChar(t[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=t[0]??"",a=t[t.length-1]??"",c=t.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=t.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),t=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(t),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(Va);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]??"",t=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+t}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(dp);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 t=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+t)}}killLine(){if(this.col>0){let t=this.currentLine();this.killBuffer=t.slice(0,this.col),this.setCurrentLine(t.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
206
206
  `,this.buffer.splice(this.row,1),this.row-=1,this.col=this.currentLine().length;return}let e=this.buffer[this.row-1]??"";this.killBuffer=e+`
207
207
  `,this.buffer.splice(this.row-1,1),this.row-=1}killToEnd(){let e=this.currentLine();if(this.col<e.length){this.killBuffer=e.slice(this.col),this.setCurrentLine(e.slice(0,this.col));return}if(this.row>=this.buffer.length-1)return;if(e.length===0){this.killBuffer=`
208
208
  `,this.buffer.splice(this.row,1);return}let t=this.buffer[this.row+1]??"";this.killBuffer=`
209
209
  `+t,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(Va);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Va);if(s!==null){this.killBuffer=s[0];let a=this.col-s[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let r=/[A-Za-z0-9_]/,i=this.col;for(;i>0&&!r.test(e[i-1]??"");)i-=1;for(;i>0&&r.test(e[i-1]??"");)i-=1;let o=e.slice(i,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let t=this.currentLine().slice(0,this.col).match(Va);if(t!==null){this.col-=t[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(dp);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(),t=this.col;for(;t>0&&/\s/.test(e[t-1]??"");)t-=1;let r=e.slice(0,t).match(Va);if(r!==null){this.col=t-r[0].length;return}for(;t>0&&!/\s/.test(e[t-1]??"");)t-=1;this.col=t}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 t=this.col;for(;t<e.length&&/\s/.test(e[t]??"");)t+=1;let r=e.slice(t).match(dp);if(r!==null){this.col=t+r[0].length;return}for(;t<e.length&&!/\s/.test(e[t]??"");)t+=1;this.col=t}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 t=this.findHistoryMatches(e);return t.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:t,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[t[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 t=this.findHistoryMatches(e);if(t.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=t,this.historySearch.cursor=0,this.loadEntry(this.history[t[0]]??""),[]}findHistoryMatches(e){let t=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&t.push(s)}return t}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
210
- `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:t,displayText:e,attachments:o}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=t.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:t,displayText:e,planMode:o,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,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,t=(this.buffer[e]??"").length;return this.row!==e||this.col!==t?(this.row=e,this.col=t,[]):[{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 To,ml,lp=Y(()=>{"use strict";To=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,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}paintRow(e,t,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==t&&(this.lastFrameRows.set(e,t),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},ml=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 CT from"string-width";function Hb(n,e){if(!n||e<=0)return 0;let t=0;for(let s of RT.segment(n)){let r=CT(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function Ub(n,e){if(e<=0)return 0;let t=0,s=0;for(let r of n)if(r.width>0&&e<t+r.width||(t+=r.width,s+=r.text.length,r.width>0&&e===t))return s;return s}var RT,jb=Y(()=>{"use strict";RT=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function TT(){Qa===0&&process.stdout.write(Hw),Qa++}function ET(){Qa!==0&&(Qa--,Qa===0&&process.stdout.write(Uw))}function Le(n){TT();try{n()}finally{ET()}}var Qa,up=Y(()=>{"use strict";Da();Qa=0});import{spawn as PT}from"child_process";import{statSync as qb}from"fs";import{homedir as Wb}from"os";import{isAbsolute as zb,resolve as MT}from"path";import Qe from"string-width";import _T from"wrap-ansi";function jT(n){let e=n.replace(/\r\n?$|\n$/,"");return UT.test(e)?e:null}function qT(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function WT(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function zT(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let t=n.iterm2Image,s=e.iterm2Image;if(t===void 0!=(s===void 0)||t&&s&&(t.data!==s.data||t.heightCells!==s.heightCells))return!1;let r=n.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 Jb(n,e,t,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!t)return`${n}|${e}|empty|${s??""}|${o}|${a}`;let c=t.iterm2Image?`i${t.iterm2Image.heightCells}:${t.iterm2Image.data.length}`:"";return`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function ms(n,e){let t=[];for(let s=0;s<n.length;s++){let r=n[s]??"";if(r.length===0){t.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){t.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),t.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function Ds(n,e,t){let s=0,r=0,i=-1;for(let c=0;c<n.length;c++){let d=n[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=n[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(t,Math.max(1,n.length)),a=0;return n.length>o&&(a=Math.max(0,Math.min(n.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 Yb(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Ns(n,e,t,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Ns(n,e.slice(c),t,o);return}d>c&&Ns(n,e.slice(c,d),t,o);let l=r!==null&&d===r;Ns(n,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Ga(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function Ns(n,e,t,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{n.noFormat(a)};switch(t){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),n.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),n.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),n.brightYellow.noFormat(e),o(i);return;case"tool":o(r),n.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),n.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);n.bgColorGrayscale(25)(a);return}case"code":{n.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}switch(t){case"user":n.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":n(e);return;case"thought":n.brightBlack(e);return;case"tool":n.brightBlue.noFormat(e);return;case"tool-status-ok":n.dim.noFormat(e);return;case"tool-status-fail":n.bold.red.noFormat(e);return;case"tool-status-pending":n.dim.noFormat(e);return;case"tool-status-running":n.brightYellow.noFormat(e);return;case"tool-status-cancelled":n.dim.noFormat(e);return;case"plan":n.brightYellow(e);return;case"plan-done":n.green(e);return;case"plan-pending":n.dim(e);return;case"system":n.brightYellow.noFormat(e);return;case"info":n.cyan.noFormat(e);return;case"dim":n.dim.noFormat(e);return;case"code":n.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":n.bold.brightYellow(e);return;case"heading-2":n.bold.brightCyan(e);return;case"heading-3":n.bold(e);return;case"search-highlight":n.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":n.inverse.noFormat(e);return;case"search-highlight-active":n.bgRed.brightWhite.noFormat(e);return;default:n.noFormat(e)}}}function KT(n,e){return e<=0?[n]:n.length===0?[""]:_T(n,e,{hard:!0,trim:!1}).split(`
211
- `)}function sv(n){nv=n}function rv(n,e){if(n==="wide")return!0;if(n==="narrow")return!1;let t=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(t)||e.TERM_PROGRAM==="Apple_Terminal")}function yr(n){return Qe(n,{ambiguousIsNarrow:!nv})}function YT(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function VT(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let r=n.charCodeAt(t);if(r<48||r>63)break;t+=1}for(;t<n.length;){let r=n.charCodeAt(t);if(r<32||r>47)break;t+=1}if(t>=n.length)return null;let s=n.charCodeAt(t);return s<64||s>126?null:n.slice(e,t+1)}function jn(n,e){if(n.charCodeAt(e)===27){let s=YT(n,e);if(s!==null)return{text:s,width:0};let r=VT(n,e);return r!==null?{text:r,width:0}:null}if(n.charCodeAt(e)!==94)return null;let t=n[e+1];if(t===void 0)return null;if(t==="^")return{text:"^^",width:1};if(t==="["){let s=n.indexOf("]",e+2);if(s!==-1)return{text:n.slice(e,s+1),width:0}}return JT.test(t)?{text:n.slice(e,e+2),width:0}:null}function vp(n){let e=new Array(n.length+1).fill(0),t="",s=0;for(;s<n.length;){e[s]=t.length;let r=jn(n,s);if(r){r.width>0&&(t+="^");for(let i=1;i<r.text.length;i++)e[s+i]=t.length;s+=r.text.length;continue}t+=n[s],s+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function Sp(n,e,t){let s=0,r=e;for(;r<t;){let i=jn(n,r);if(i){r+=i.text.length,i.width>0&&(s+=1);continue}s+=1,r+=1}return s}function kp(n,e,t){let s=e;for(;t>0&&s<n.length;){let r=jn(n,s);if(r){s+=r.text.length,r.width>0&&(t-=1);continue}s+=1,t-=1}return s}function Vb(n){if(!n.includes("^")&&!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let s=jn(n,t);if(s){s.width>0&&(e+="^"),t+=s.text.length;continue}e+=n[t],t+=1}return e}function QT(n){if(!n.includes("^")&&!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let s=jn(n,t);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}t+=s.text.length;continue}t+=1}return e}function iv(n){if(!n.includes("^")&&!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if(jn(n,e))return!0;return!1}function Qb(n,e){let t=n.indexOf("^",e),s=n.indexOf("\x1B",e);return t===-1?s:s===-1?t:Math.min(t,s)}function*xp(n){let e=0;for(;e<n.length;){let t=jn(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let s=n.length,r=Qb(n,e);for(;r!==-1&&r<n.length;){if(jn(n,r)){s=r;break}r=Qb(n,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Ip.segment(n.slice(e,s)))yield{text:i,width:yr(i)};e=s}}function GT(n,e,t){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${n}\x07`;return t?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function XT(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let s=t.stripMarkup===!0&&iv(n);return!s&&!tv.test(n)?ZT(n,e):eE(n,e,s)}function ZT(n,e){let t=[],s=n;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?(t.push(s.slice(0,e)),s=s.slice(e)):(t.push(s.slice(0,i)),s=s.slice(i+1))}return t.push(s),t}function eE(n,e,t){let s=[],r=t?[...xp(n)]:tE(n),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 tE(n){let e=[];for(let{segment:t}of Ip.segment(n))e.push({text:t,width:yr(t)});return e}function Rt(n,e,t={}){if(e<=0)return"";let s=t.stripMarkup===!0&&iv(n);if(!s&&n.length<=e&&!tv.test(n))return n;if(!s)return yr(n)<=e?n:e<=1?Gb(n,e):Gb(n,e-1)+"\u2026";let r=[...xp(n)],i=0;for(let o of r)i+=o.width;return i<=e?n:e<=1?Xb(r,e):Xb(r,e-1)+"\u2026"}function Gb(n,e){if(e<=0)return"";let t="",s=0;for(let{segment:r}of Ip.segment(n)){let i=yr(r);if(s+i>e)break;t+=r,s+=i}return t}function Xb(n,e){if(e<=0)return"";let t="",s=0;for(let r of n){if(s+r.width>e)break;t+=r.text,s+=r.width}return t}function nE(n){let e=n.indexOf(`
212
- `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function Zb(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${bl(n.used)}/${bl(n.size)}`):e.push(bl(n.used)):typeof n.size=="number"&&e.push(`/${bl(n.size)}`),typeof n.costAmount=="number"&&e.push(vf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function bl(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function Sl(n){switch(n){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_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function wr(){let n=[vo,So,Ow,ko,Lw,Kf,Os,ni,si,ti,ei,"\x1B>",Ba,Zc,el,"\x1B]9;4;0\x07",Mw].join("");try{process.stdout.write(n)}catch{}}function ov(n){let e=[["width",80],["height",24]];for(let[t,s]of e){let r=Object.getOwnPropertyDescriptor(n,t);if(r&&r.get)continue;let i=Symbol(`raw-${t}`),o=n;o[i]=r?r.value:void 0,Object.defineProperty(n,t,{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 ev(n,e){let t={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?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var fp,gl,yl,pp,hp,$T,Kb,FT,Ve,nt,OT,st,mp,gp,LT,BT,NT,yp,wp,bp,DT,HT,UT,vl,tv,Ip,nv,JT,wl,Ap=Y(()=>{"use strict";lp();Sf();be();is();ul();yo();jb();hl();up();Hr();Da();fp=500,gl=1,yl=/[A-Za-z0-9_\-]/,pp=/[A-Za-z0-9_./\-~+@]/,hp=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,$T=/[.,;:!?)\]}'"]/,Kb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,FT=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Ve=1,nt=0,OT=1,st=1,mp=8,gp=5,LT=12,BT=12,NT=30,yp=6,wp=4,bp=2,DT=1e3,HT=1e4,UT=/^(https?|ftp):\/\/\S+$/;vl=class n{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),t(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??DT,this.painter=new To(this.term),this.scheduler=new ml({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??HT,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(zf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),ie({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),ie({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(el),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Ba),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(wr(),this.term.fullscreen(!1),this.term(`
213
- `)))}installBracketedPaste(){process.stdout.write(Xc),process.stdout.write($w),process.stdout.write(Fw),process.stdout.write(_w),process.stdout.write(tl);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(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(ti),process.stdout.write(Na),process.stdout.write(ei),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write(Bw),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(Kf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>wr(),this.onProcessSignal=e=>{wr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{wr(),process.stderr.write(`
210
+ `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:t,displayText:e,attachments:o}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=t.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:t,displayText:e,planMode:o,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,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,t=(this.buffer[e]??"").length;return this.row!==e||this.col!==t?(this.row=e,this.col=t,[]):[{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 To,ml,lp=Y(()=>{"use strict";To=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,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}paintRow(e,t,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==t&&(this.lastFrameRows.set(e,t),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},ml=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 ET from"string-width";function Ub(n,e){if(!n||e<=0)return 0;let t=0;for(let s of PT.segment(n)){let r=ET(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function jb(n,e){if(e<=0)return 0;let t=0,s=0;for(let r of n)if(r.width>0&&e<t+r.width||(t+=r.width,s+=r.text.length,r.width>0&&e===t))return s;return s}var PT,qb=Y(()=>{"use strict";PT=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function MT(){Qa===0&&process.stdout.write(Uw),Qa++}function _T(){Qa!==0&&(Qa--,Qa===0&&process.stdout.write(jw))}function Le(n){MT();try{n()}finally{_T()}}var Qa,up=Y(()=>{"use strict";Da();Qa=0});import{spawn as $T}from"child_process";import{statSync as Wb}from"fs";import{homedir as zb}from"os";import{isAbsolute as Kb,resolve as FT}from"path";import Qe from"string-width";import OT from"wrap-ansi";function zT(n){let e=n.replace(/\r\n?$|\n$/,"");return WT.test(e)?e:null}function KT(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function JT(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function YT(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let t=n.iterm2Image,s=e.iterm2Image;if(t===void 0!=(s===void 0)||t&&s&&(t.data!==s.data||t.heightCells!==s.heightCells))return!1;let r=n.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 Yb(n,e,t,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!t)return`${n}|${e}|empty|${s??""}|${o}|${a}`;let c=t.iterm2Image?`i${t.iterm2Image.heightCells}:${t.iterm2Image.data.length}`:"";return`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function gs(n,e){let t=[];for(let s=0;s<n.length;s++){let r=n[s]??"";if(r.length===0){t.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){t.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),t.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function Ds(n,e,t){let s=0,r=0,i=-1;for(let c=0;c<n.length;c++){let d=n[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=n[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(t,Math.max(1,n.length)),a=0;return n.length>o&&(a=Math.max(0,Math.min(n.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 Vb(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Ns(n,e,t,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Ns(n,e.slice(c),t,o);return}d>c&&Ns(n,e.slice(c,d),t,o);let l=r!==null&&d===r;Ns(n,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Ga(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function Ns(n,e,t,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{n.noFormat(a)};switch(t){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),n.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),n.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),n.brightYellow.noFormat(e),o(i);return;case"tool":o(r),n.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),n.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);n.bgColorGrayscale(25)(a);return}case"code":{n.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}switch(t){case"user":n.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":n(e);return;case"thought":n.brightBlack(e);return;case"tool":n.brightBlue.noFormat(e);return;case"tool-status-ok":n.dim.noFormat(e);return;case"tool-status-fail":n.bold.red.noFormat(e);return;case"tool-status-pending":n.dim.noFormat(e);return;case"tool-status-running":n.brightYellow.noFormat(e);return;case"tool-status-cancelled":n.dim.noFormat(e);return;case"plan":n.brightYellow(e);return;case"plan-done":n.green(e);return;case"plan-pending":n.dim(e);return;case"system":n.brightYellow.noFormat(e);return;case"info":n.cyan.noFormat(e);return;case"dim":n.dim.noFormat(e);return;case"code":n.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":n.bold.brightYellow(e);return;case"heading-2":n.bold.brightCyan(e);return;case"heading-3":n.bold(e);return;case"search-highlight":n.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":n.inverse.noFormat(e);return;case"search-highlight-active":n.bgRed.brightWhite.noFormat(e);return;default:n.noFormat(e)}}}function VT(n,e){return e<=0?[n]:n.length===0?[""]:OT(n,e,{hard:!0,trim:!1}).split(`
211
+ `)}function rv(n){sv=n}function iv(n,e){if(n==="wide")return!0;if(n==="narrow")return!1;let t=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(t)||e.TERM_PROGRAM==="Apple_Terminal")}function yr(n){return Qe(n,{ambiguousIsNarrow:!sv})}function GT(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function XT(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let r=n.charCodeAt(t);if(r<48||r>63)break;t+=1}for(;t<n.length;){let r=n.charCodeAt(t);if(r<32||r>47)break;t+=1}if(t>=n.length)return null;let s=n.charCodeAt(t);return s<64||s>126?null:n.slice(e,t+1)}function jn(n,e){if(n.charCodeAt(e)===27){let s=GT(n,e);if(s!==null)return{text:s,width:0};let r=XT(n,e);return r!==null?{text:r,width:0}:null}if(n.charCodeAt(e)!==94)return null;let t=n[e+1];if(t===void 0)return null;if(t==="^")return{text:"^^",width:1};if(t==="["){let s=n.indexOf("]",e+2);if(s!==-1)return{text:n.slice(e,s+1),width:0}}return QT.test(t)?{text:n.slice(e,e+2),width:0}:null}function vp(n){let e=new Array(n.length+1).fill(0),t="",s=0;for(;s<n.length;){e[s]=t.length;let r=jn(n,s);if(r){r.width>0&&(t+="^");for(let i=1;i<r.text.length;i++)e[s+i]=t.length;s+=r.text.length;continue}t+=n[s],s+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function Sp(n,e,t){let s=0,r=e;for(;r<t;){let i=jn(n,r);if(i){r+=i.text.length,i.width>0&&(s+=1);continue}s+=1,r+=1}return s}function kp(n,e,t){let s=e;for(;t>0&&s<n.length;){let r=jn(n,s);if(r){s+=r.text.length,r.width>0&&(t-=1);continue}s+=1,t-=1}return s}function Qb(n){if(!n.includes("^")&&!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let s=jn(n,t);if(s){s.width>0&&(e+="^"),t+=s.text.length;continue}e+=n[t],t+=1}return e}function ZT(n){if(!n.includes("^")&&!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let s=jn(n,t);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}t+=s.text.length;continue}t+=1}return e}function ov(n){if(!n.includes("^")&&!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if(jn(n,e))return!0;return!1}function Gb(n,e){let t=n.indexOf("^",e),s=n.indexOf("\x1B",e);return t===-1?s:s===-1?t:Math.min(t,s)}function*xp(n){let e=0;for(;e<n.length;){let t=jn(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let s=n.length,r=Gb(n,e);for(;r!==-1&&r<n.length;){if(jn(n,r)){s=r;break}r=Gb(n,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Ip.segment(n.slice(e,s)))yield{text:i,width:yr(i)};e=s}}function eE(n,e,t){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${n}\x07`;return t?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function tE(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let s=t.stripMarkup===!0&&ov(n);return!s&&!nv.test(n)?nE(n,e):sE(n,e,s)}function nE(n,e){let t=[],s=n;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?(t.push(s.slice(0,e)),s=s.slice(e)):(t.push(s.slice(0,i)),s=s.slice(i+1))}return t.push(s),t}function sE(n,e,t){let s=[],r=t?[...xp(n)]:rE(n),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 rE(n){let e=[];for(let{segment:t}of Ip.segment(n))e.push({text:t,width:yr(t)});return e}function Rt(n,e,t={}){if(e<=0)return"";let s=t.stripMarkup===!0&&ov(n);if(!s&&n.length<=e&&!nv.test(n))return n;if(!s)return yr(n)<=e?n:e<=1?Xb(n,e):Xb(n,e-1)+"\u2026";let r=[...xp(n)],i=0;for(let o of r)i+=o.width;return i<=e?n:e<=1?Zb(r,e):Zb(r,e-1)+"\u2026"}function Xb(n,e){if(e<=0)return"";let t="",s=0;for(let{segment:r}of Ip.segment(n)){let i=yr(r);if(s+i>e)break;t+=r,s+=i}return t}function Zb(n,e){if(e<=0)return"";let t="",s=0;for(let r of n){if(s+r.width>e)break;t+=r.text,s+=r.width}return t}function iE(n){let e=n.indexOf(`
212
+ `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function ev(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${bl(n.used)}/${bl(n.size)}`):e.push(bl(n.used)):typeof n.size=="number"&&e.push(`/${bl(n.size)}`),typeof n.costAmount=="number"&&e.push(vf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function bl(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function Sl(n){switch(n){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_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function wr(){let n=[vo,So,Lw,ko,Bw,Kf,Os,ni,si,ti,ei,"\x1B>",Ba,Zc,el,"\x1B]9;4;0\x07",_w].join("");try{process.stdout.write(n)}catch{}}function av(n){let e=[["width",80],["height",24]];for(let[t,s]of e){let r=Object.getOwnPropertyDescriptor(n,t);if(r&&r.get)continue;let i=Symbol(`raw-${t}`),o=n;o[i]=r?r.value:void 0,Object.defineProperty(n,t,{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 tv(n,e){let t={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?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var fp,gl,yl,pp,hp,LT,Jb,BT,Ve,nt,NT,st,mp,gp,DT,HT,UT,yp,wp,bp,jT,qT,WT,vl,nv,Ip,sv,QT,wl,Ap=Y(()=>{"use strict";lp();Sf();be();os();ul();yo();qb();hl();up();Hr();Da();fp=500,gl=1,yl=/[A-Za-z0-9_\-]/,pp=/[A-Za-z0-9_./\-~+@]/,hp=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,LT=/[.,;:!?)\]}'"]/,Jb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,BT=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Ve=1,nt=0,NT=1,st=1,mp=8,gp=5,DT=12,HT=12,UT=30,yp=6,wp=4,bp=2,jT=1e3,qT=1e4,WT=/^(https?|ftp):\/\/\S+$/;vl=class n{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),t(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??jT,this.painter=new To(this.term),this.scheduler=new ml({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??qT,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(zf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),ie({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),ie({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(el),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Ba),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(wr(),this.term.fullscreen(!1),this.term(`
213
+ `)))}installBracketedPaste(){process.stdout.write(Xc),process.stdout.write(Fw),process.stdout.write(Ow),process.stdout.write($w),process.stdout.write(tl);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(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(ti),process.stdout.write(Na),process.stdout.write(ei),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write(Nw),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(Kf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>wr(),this.onProcessSignal=e=>{wr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{wr(),process.stderr.write(`
214
214
  uncaught: ${e.stack??e.message}
215
- `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write(Nw),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=t.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");ie({tag:"raw",bytes:s,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=t.indexOf("\x1B[I"),i=t.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()),t=t.slice(0,o)+t.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(bo)){this.handleRawStdinSegment(t);return}if(t.includes(`
215
+ `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write(Dw),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=t.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");ie({tag:"raw",bytes:s,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=t.indexOf("\x1B[I"),i=t.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()),t=t.slice(0,o)+t.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(bo)){this.handleRawStdinSegment(t);return}if(t.includes(`
216
216
  `)){let s=t.split(`
217
- `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:t.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(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=t.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=ev(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 t=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=t.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=ev(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 t=bo,s=La;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
218
- `);this.pasteBuffer="";let a=$b(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(t);if(r===-1){let i=jT(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+t.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 t=this.term.width;return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let s of e)t+=this.wrappedRowsOf(s);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let s of t)this.forgetLine(s);this.invalidateSelectionIfTouches(t);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let o of t)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=t.length-s.count,d=this.lines.slice(s.start,o),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=d[f],h=t[f];p!==void 0&&zT(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=t.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=t.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=c);i=this.wrappedRowsOfMany(t)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),i=this.wrappedRowsOfMany(t);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,s,r){if(e.length===0)return;let i=e.split(`
219
- `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let 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:t,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(t.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(),t=wl(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:t,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,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),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)),ie({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,t){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.sourceLineId),i=s<r||s===r&&e.offset<=t.offset,o=i?e:t,a=i?t: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 t=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.startLineId),i=this.lineIndexById(t.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,t.startOffset),c=o(s,e.offset,i,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(c>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-t.endOffset)>=d?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let c=(r.body??"").slice(o.start,o.end);(Ga(r.bodyStyle)||r.ansi)&&(c=Vb(c)),t.push(c)}return t.join(`
220
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(t===-1||s===-1)return null;let r=t,i=s,o=e.startOffset,a=e.endOffset;t>s&&(r=s,i=t,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 t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=t.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,c=Math.max(r.start,i),d=Math.min(r.end,a);if(d<=c)return null;let l,u;if(s.sourceColEnd!==void 0){let f=this.sourceBodyForId(s.sourceLineId);if(f===null)return null;let p=Sp(f,i,c),h=Sp(f,c,d);l=kp(e.body,o,p),u=kp(e.body,l,h)}else l=c-i+o,u=d-i+o;return{start:l,end:u,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,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 t of e){let s=this.lineIds.get(t);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 t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(t.start,s)),o=this.lines.splice(t.start,t.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>t.start&&(c.start-=t.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 t=e.start+e.count;if(t>=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>=t&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),i=this.lines.splice(t.start,t.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>t.start&&(o.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let s=[...t].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(!t.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,t,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=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(zf),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(t=>({...t}))}: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 t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!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},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let t=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){t=!1;break}if(t)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;t&&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 t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=t!==void 0&&t.start+t.count===this.lines.length,r=s?t.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(t.start,0,o),t.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,t){if(process.env.HYDRA_TUI_KEY_TRACE&&ie({tag:"key",name:e,isChar:!!t.isCharacter}),t.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=Sl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){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(t),a=WT(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)<=gl&&Math.abs(o.y-d.y)<=gl&&Date.now()-d.t<=fp||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,qT(t,"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,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=fp&&Math.abs(e.x-i.x)<=gl&&Math.abs(e.y-i.y)<=gl&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let u=e.y;for(;u>1&&this.keyAtRow(u-1)===l;)u-=1;let f=e.y-u;if(this.onBlockDoubleClick(l,f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&Kb.test(l)){let f=l.match(Kb)?.[1]??null;if(f&&this.onHydraLinkClick(f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let s=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&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 t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),c=Math.max(0,t-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>=t-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,t){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=t-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=t+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,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)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(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),!yl.test(r[a])&&!hp.test(r[a]))return null;let c=a;for(;c>0&&hp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&hp.test(r[d]);)d++;for(;d>c+1&&$T.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!yl.test(r[a]))return null;let u=a;for(;u>0&&yl.test(r[u-1]);)u--;let f=a+1;for(;f<r.length&&yl.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,u,f)}projectCleanRangeToRaw(e,t,s,r){let i=t,o=t;for(let a=0;a<e.length;a++)if(e[a]===s&&i===t&&(i=a),e[a]===r&&o===t){o=a;break}return{start:i,end:o}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(t.links){for(let p of t.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!pp.test(r[a]))return null;let c=a;for(;c>0&&pp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&pp.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))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 t=this.lineById(e.sourceLineId);if(t===null||t.ansi||!t.links)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of t.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Wb():`${Wb()}/${t.slice(2)}`);let s=zb(t)||e.startsWith("~"),r=zb(t)?t:MT(this.sessionbar.cwd,t);if(s)return r;try{if(qb(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.raw;if(!FT.test(s))return!1;let r=s.startsWith(Dt)?[s]:[Dt+s,s],i=null;for(let o of r)try{if(qb(O.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(t=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(t);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=PT(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,t){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,t)},fp);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:t}}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 t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let s=this.lines[t];if(s&&this.lineIds.get(s)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Bb(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,s=Number(t.x),r=Number(t.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"?Dw:el))}keyAtRow(e){let t=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(t,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 t=e-1;t>=1;t--){let s=this.keyAtRow(t);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 t=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(t,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,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-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=yr(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=Ga(p.bodyStyle)||p.ansi===!0?Ub(xp(p.body),b):Hb(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=Sp(p.body,y,k),P=kp(A,h.sourceColOffset,E);return{sourceLineId:h.sourceLineId,offset:P}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+k-y}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),s=Math.min(t,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 t=e.toLowerCase(),s=[];if(t.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(t,c);if(d===-1)break;a.push(d),c=d+t.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=t.length>0?t: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 t=this.lines[e.lineIdx];if(!t)return null;let s=this.lineIds.get(t);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==t.lineId)return null;let r=s.bodyDisplayShift??0,i=t.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}scrollToMatch(e){let t=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,t).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,t),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 t=this.term.height-this.promptRows()-Ve-st-nt-OT-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-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,t,s){this.started&&this.painter.paintRow(e,t,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),Le(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-nt-st-Ve;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Ve),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),t=this.term.height,s=this.sessionbar.title?.trim(),r=Ly(this.sessionbar.agent,this.sessionbar.model),i=ct(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Qe(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=Qe(l),f,p;if(s){let b=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-b)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=Rt(i,f),m=s?Rt(s,p):"",y=Qe(h)+(s?u+Qe(m):0),w=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(w)),this.term.noFormat(r)})}drawSeparator(e){let t=this.term.width,s=wl(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?fs(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;c.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;c.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let d=Zb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Qe(o)+Qe(u)+f.length+Qe(s);for(let A of c)y+=Qe(" \xB7 ")+Qe(A.text);y+=Qe(p);let w=Qe(h)+Qe(d)+Qe(m),b=Math.max(0,t-y-w),S="\u2500".repeat(b),k=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),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 A of c)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let t=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=Qe(i)+Qe(a)+Qe(o),d=Math.max(0,t-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${t}|${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 w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let b=m[w];if(b===void 0)continue;let S=null;b.includes("mode")?S="mode":b.includes("pick")?S="pick":b.includes("guide")?S="guide":b.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(b):this.term.dim(b)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Qe(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Qe(w),S=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=S:w.includes("pick")&&h.pick===null?h.pick=S:w.includes("guide")&&h.guide===null?h.guide=S:w.includes("detach")&&h.detach===null&&(h.detach=S),m+=b+Qe(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?wl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Zb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Qe(t)+i.length+Qe(r)+o.length+Qe(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:t,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()-nt-st-Ve,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=wl(this.btwOverlaySessionId),u=1+c.length+Qe(a)+" \xB7 ".length,f=u+Qe(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,t=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=t+h,y=h-d,w=y>=0?c[y]:void 0,b=this.activeMatchCol(w,l),S=w?this.selectionRangeForChunk(w):null,k=w!==void 0&&w.blockKey!==void 0&&(w.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w.blockKey)),A=w!==void 0&&w.blockKey===void 0&&f!==-1&&y>=f&&y<=p,E=k||A,P=this.terminalFocused&&E&&(this.hoveredSubKey===null||(w.hoverSubKey??null)===this.hoveredSubKey),H=Jb("sb",e,w,this.scrollbackHighlight,b,S)+(P?"|H":"");this.paintRow(m,H,()=>{w&&this.writeFormattedLine(w,e,b,u,S,P)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(gp,this.queuedTexts.length)}chipRows(){return Math.min(wp,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,s)=>t===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(yp,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Ve-st-nt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>yp,h=this.completions.length-yp+1,m=f?p?`comp|${t}|overflow|${h}`:`comp|${t}|${d}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),w=f.description??"",b=t-y.length-4,S=b>0?Rt(w,b):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Ve-st-nt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>wp,u=this.attachments.length-wp,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${In(f.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${u}`:f?`chip|${t}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${t}|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,t){process.stdout.write(GT(e,t,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Ve-st-nt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>gp,p=this.queuedTexts.length-gp,h=u===void 0?"":f?`+ ${p+1} more queued`:Rt(nE(u),t-4),m=!f&&d===c,y=u===void 0?`queued|${t}|empty`:`queued|${t}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let w=`\u23F3 ${h}`,b=w+" ".repeat(Math.max(0,t-1-w.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ms(s.buffer,t),i=Ds(r,s,mp),o=this.term.height-i.rendered-nt-st-Ve+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 t=this.term.width,s=this.term.height-bp-nt-st-Ve+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${Rt(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${Rt(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,s=this.compactionRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${Rt(e.message,t-2)}`)}),o(`cpct|q|${t}`,()=>{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}. ${Rt(c.label,t-8)}`;o(`cpct|o|${t}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${t}`,()=>{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 t=this.term.width,s=this.helpRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${Rt(e.title,t-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|${t}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${t}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${Rt(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${Rt(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(NT,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,s=this.permissionRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${Rt(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${t}|${a}`,()=>{this.term.dim(` ${Rt(a,t-2)}`)}),o(`perm|q|${t}`,()=>{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}. ${Rt(d.label,t-8)}`;o(`perm|o|${t}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${t}`,()=>{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,t){let s=this.bannerHits;if(!s||t!==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,t=this.promptRows(),s=e-t-nt-st-Ve;this.drawSeparator(s),this.drawBottomSeparator(e-Ve)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-nt-st-Ve+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-nt-st-Ve+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-bp-nt-st-Ve+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-nt-st-Ve+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-nt-st-Ve+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,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ms(s.buffer,t),i=Ds(r,s,mp),a=this.term.height-i.rendered-nt-st-Ve+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-nt-st-Ve;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 bp;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ms(s.buffer,t);return Math.min(mp,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(LT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(BT,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let t=this.term.width,s=this.optionsRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${Rt(e.title,t-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=t-p.length-3,y=`${p}${Rt(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${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|${t}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,s=this.wrapBtwTail(t,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,t){if(e<=4){let o=Math.min(t,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(t<=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>=t)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>t?i.slice(i.length-t):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let t=this.term.width,r=this.term.height-this.promptRows()-nt-st-Ve,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(t,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=Jb(`btw|c${f}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){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(t,d.length);return{rows:d.slice(d.length-l),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=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>=t)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,t){let s=this.lineIds.get(e);if(s!==void 0){let h=this.wrapCache.get(s);if(h)return h}let r=e.prefix??"",i=yr(r),o=Math.max(1,t-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),c=Math.max(1,o-a),d=Ga(e.bodyStyle),l=e.ansi?KT(e.body,a>0?c:o):XT(e.body,a>0?c:o,{stripMarkup:d}),u=[],f=0,p=0;for(let h=0;h<l.length;h++){let m=l[h]??"",y=h===0||a===0?m:" ".repeat(a)+m,w={prefix:h===0?e.prefix:" ".repeat(i),body:y};if(e.prefixStyle!==void 0&&(w.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(w.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(w.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(w.hoverSubKey=e.hoverSubKey),e.fillRow&&(w.fillRow=!0),e.ansi&&(w.ansi=!0),h===0&&e.iterm2Image&&(w.iterm2Image=e.iterm2Image),s!==void 0&&m.length>0)if(e.ansi){let b=f,S=0;for(let P=0;P<m.length;){let H=jn(m,P);if(H){P+=H.text.length,H.width>0&&(S+=1);continue}S+=1,P+=1}let k=S;for(;k>0&&f<e.body.length;){let P=jn(e.body,f);if(P){f+=P.text.length,P.width>0&&(k-=1);continue}f+=1,k-=1}let A=f;if(h===l.length-1){for(;A<e.body.length;){let P=jn(e.body,A);if(!P)break;A+=P.text.length}f=A}let E={sourceLineId:s,sourceColOffset:b,sourceColEnd:A};h>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(w,E)}else{let b=e.body.indexOf(m,p),S=b===-1?p:b,k={sourceLineId:s,sourceColOffset:S};h>0&&a>0&&(k.bodyDisplayShift=a),this.wrapOrigin.set(w,k),p=S+m.length}u.push(w)}return s!==void 0&&this.wrapCache.set(s,u),u}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1){e.prefix&&Ns(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,t-yr(e.prefix??"")),c=Ga(e.bodyStyle),d=e.ansi?e.body:Rt(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;Yb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Ns(this.term,u,e.bodyStyle,o)};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=Ga(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Vb(m)),Ns(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=QT(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Yb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Ns(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?Qe(d):yr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Ns(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)}};tv=/[^\x20-\x7e]/,Ip=new Intl.Segmenter(void 0,{granularity:"grapheme"}),nv=!1;JT=/[a-zA-Z+\-:_!#/]/;wl=pt});function sE(n,e,t=kl){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=t[n];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,n-1)};let r=t.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=t[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:n}}async function av(n,e){Hn();let t=pt(e.sessionId),s=e.importedFromMachine??"another machine",r=ct(e.cwd),i=kl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+kl.length*2+2,d=Un(n,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)n.moveTo(d.contentX,d.contentY+f),n.dim.noFormat(` ${p.label}`),n.noFormat(Xe(p.value,l-p.label.length-2)),f++;return f++,dv(n,d,f,{intro:"What do you want to do?",choices:kl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return ps({term:n,render:o,onKey:(a,c,d,l)=>{let u=rE(a,d);if(!u)return;let f=sE(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 dv(n,e,t,s){let r=e.contentW,i=t;n.moveTo(e.contentX,e.contentY+i),n.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}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Ha(d,r)):n.noFormat(d),i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${a.description}`),i++}i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${s.footer}`)}function rE(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function cv(n,e,t){let s=pt(e.sessionId),r=e.title??ct(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=Un(n,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;n.moveTo(c.contentX,c.contentY+l),n.dim.noFormat(" session: "),n.noFormat(Xe(s,d-10)),l++,n.moveTo(c.contentX,c.contentY+l),n.noFormat(" "+Xe(r,d-2)),l++,l++,dv(n,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(),n.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),t.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}}};t.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var kl,Cp=Y(()=>{"use strict";be();is();ri();kl=[{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 Za(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let s=n[t]??"",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 lv(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let s=t.indexOf(" "),r=s===-1?t:t.slice(0,s),i=s===-1?"":t.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Za(e);return o.length<=r.length?null:o+i}var Il=Y(()=>{"use strict"});var Eo,Rp=Y(()=>{"use strict";Eo=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,t={}){t.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,t=this.cur;for(;t<e&&/\s/.test(this.buffer[t]??"");)t+=1;for(;t<e&&!/\s/.test(this.buffer[t]??"");)t+=1;this.cur=t}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,t){if(t)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as uv from"os";async function di(n,e,t={}){let s=t.defaultCwd??(e?await Ib(e.cwd):void 0)??uv.homedir();Hn();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:pt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:ct(e.cwd)}]:[],a=new Eo(s),c=null,d=!1,l=null,u=null,f=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),b=h.indexOf(y),S=()=>{let _=o.length+6;l=Un(n,{contentHeight:_,title:r,overlay:t.overlay===!0});let F=l.contentW,B=0;for(let j of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${j.label}`),n.noFormat(Xe(j.value,F-j.label.length-2)),B++;B++,n.moveTo(l.contentX,l.contentY+B),n.noFormat(` ${i}`),B+=2,E(B),B+=2;let N=l.contentY+B;c!==null?(n.moveTo(l.contentX,N),n.red.noFormat(` ${Xe(c,F-2)}`),u=null,f=null,p=null):(n.moveTo(l.contentX,N),n.dim.noFormat(h),u=N,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},k=()=>o.length+3,A=0,E=_=>{if(!l)return;let F=_??k();n.moveTo(l.contentX,l.contentY+F).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+F),n.dim.noFormat("\u2502"),n.moveTo(l.contentX,l.contentY+F),n.noFormat(" ");let N=Math.max(1,l.contentW-1-2),j=a.text,G=a.cursor;G<A&&(A=G),G-A>=N&&(A=G-N+1),A<0&&(A=0);let X=j.slice(A,A+N);A>0&&X.length>0&&(X="\u2026"+X.slice(1));let V=G-A;if(d){n.noFormat(X);return}V>=X.length?(n.noFormat(X),n.bgWhite(" ")):(n.noFormat(X.slice(0,V)),n.bgWhite.noFormat(X[V]??" "),n.noFormat(X.slice(V+1)))},P=()=>{if(E(),!l)return;let _=k()+2;n.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+_),n.dim.noFormat("\u2502");let F=l.contentY+_;n.moveTo(l.contentX,F),c!==null?(n.red.noFormat(` ${Xe(c,l.contentW-2)}`),u=null,f=null,p=null):(n.dim.noFormat(h),u=F,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},H=_=>{if(d)return;let F=a.text;d=!0,c=null,P(),za(F).then(B=>{if(d=!1,B.ok){_({kind:"ok",path:B.path});return}c=B.reason,P()})};return ps({term:n,render:S,overlay:t.overlay===!0,onKey:(_,F,B,N)=>{if(!d){if(_==="ENTER"||_==="KP_ENTER"){H(N);return}if(_==="ESCAPE"){N({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){N({kind:"cancel"});return}if(_==="TAB"){d=!0,xb(a.text).then(j=>{if(d=!1,j.matches.length===0)return;let G;if(j.matches.length===1)G=j.prefix+j.matches[0];else{let X=Za(j.matches);if(X.length<=j.basePrefix.length)return;G=j.prefix+X}G!==a.text&&(a.setText(G,{recordUndo:!0}),c=null,P())});return}if(a.handleKey(_,B?.isCharacter===!0)){c=null,P();return}}},onMouse:(_,F,B)=>{if(d||_!=="MOUSE_LEFT_BUTTON_PRESSED")return;let N=F?.x,j=F?.y;if(!(typeof N!="number"||typeof j!="number")){if(l!==null&&(N<l.x||N>=l.x+l.w||j<l.y||j>=l.y+l.h)){B({kind:"back"});return}if(u!==null&&j===u){if(f!==null&&N>=f.start&&N<=f.end){H(B);return}if(p!==null&&N>=p.start&&N<=p.end){B({kind:"back"});return}}}}})}var Tp=Y(()=>{"use strict";be();is();ep();Il();ri();Rp()});import*as pv from"fs";import*as hv from"os";import*as xl from"path";function Al(n,e){let t=e;for(;t>0;){let s=n[t-1]??"";if(/\s/.test(s)){if(s===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function iE(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function oE(n){return n.replace(/\\ /g," ")}function fv(n){return n.replace(/ /g,"\\ ")}function aE(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function dE(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=hv.homedir()+t.slice(1)),xl.isAbsolute(t)?t:xl.resolve(e,t)}function cE(n){let e;try{e=pv.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function Cl(n,e,t=cE){let s=oE(n),{dirPrefix:r,base:i}=aE(s);if(r.length===0&&!iE(n)&&i.length===0)return null;let o=dE(r,e),a=t(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:fv(r+p),candidates:l}}let u=Za(d.map(f=>f.name));return{replacement:fv(r+u),candidates:l}}var Ep=Y(()=>{"use strict";Il()});function lE(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function uE(n,e,t){let s=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${s} via npm\u2026`:t.phase==="installed"?`${n} ${s} installed`:`${n} installing ${s} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let r=t.receivedBytes??0,i=t.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${c}%)`}return`${n} downloading ${s} ${o} MB`}return t.phase==="download_done"?`${n} downloaded ${s}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${s}\u2026`:t.phase==="installed"?`${n} ${s} installed`:e||n}function Rl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,lE(a))};return{write(a){t||(i=a,s=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=uE(i,s,a);s=d,e.write(d)},finalize(){t||(t=!0,o(0),e.finalize())}}}function mv(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),n.brightYellow(t))},finalize(){e||(e=!0,process.stdout.write(`
221
- `))}}}var Pp=Y(()=>{"use strict"});function _p(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function $p(n,e){let t=()=>{process.stdout.write(ti),process.stdout.write(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(vo),process.stdout.write(So),process.stdout.write(ko),process.stdout.write(ei),process.stdout.write("\x1B>")};t();let s=e.prefs??_p();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Tl(e.sessions,r),o=T=>{let M=T;return s.filters.cwdOnly&&(M=M.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=yE(M,s.filters.hostFilter),M},a=o(i),c={columns:e.config.tui.sessionColumns??fo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(T=>ho(T,Date.now())),l=mo(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let T=a.findIndex(M=>M.sessionId===e.currentSessionId);T>=0&&(f=T+1)}let h=!1,m="",y=120,w=!1,b=0,S="normal",k=null,A=!1,E="input",P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,N=null,j=!1,G=null,X=null,V=null,ye=null,Be=()=>{if(ye!==null){let T=ye;return{plain:T,render:()=>{n.brightYellow.noFormat(` ${T}`)}}}if(h){let T=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${T} \xB7 ^c clears`,render:()=>{n.brightYellow.noFormat(` /${m}`),n.bgBrightYellow(" "),n.dim.noFormat(` ${T} \xB7 ^c clears`)}}}return V!==null?{plain:V,render:()=>{n.dim.noFormat(` ${V}`)}}:null},mt=!1,_e=new Bs({history:[]});if(e.initialPrompt&&_e.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)_e.addAttachment(T);let gs=e.config.tui.promptHistoryMaxEntries;ma(O.globalTuiHistoryFile()).then(T=>{let M=T.length>gs?T.slice(T.length-gs):T;_e.setHistory(M)}).catch(()=>{});let Ee=new To(n),ee=Ls(n),ce=Jt(n),$e=0,fn="",pn=0,xn=[],Ht=1,Yt=0,vr=0,li=0,Wn="",Po=[],An=1,rd=0,Mo=[],Ut=1,Ce=0,_o=0,id=0,ui=()=>{ee=Ls(n),ce=Jt(n);let T=Math.max(10,ce-Mp-1);pn=Math.max(10,ce-gv);let M=Math.max(10,ce-8),U=_e.state().attachments.length,Q=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",te=Math.max(10,M-Q.length);fn=mE(r,te)+Q;let oe=_e.state();xn=ms(oe.buffer,pn);let me=Ds(xn,oe,ed);Ht=me.rendered,Yt=me.windowStart,vr=me.cursorVisualRow,li=me.cursorVisualCol;let He=6+Ht,Je=Math.max(3,ee-He);$e=Math.min(a.length,Je),Wn=ur(po,l,T,c).padEnd(T),Po=d.map(rt=>ur(rt,l,T,c).padEnd(T))},$o=()=>{d=a.map(T=>ho(T,Date.now())),l=mo(d,c),u=1+a.length,ui()},At=()=>{let T=o(i);h&&m.length>0?a=T.filter(M=>wE(M,m)):a=T,$o(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+$e>a.length&&(p=Math.max(0,a.length-$e)),hn()},ys=T=>{if(T!==void 0){let M=a.findIndex(U=>U.sessionId===T);if(M>=0){f=M+1,hn();return}}f=a.length>0?1:0,p=0,hn()},hn=()=>{if(f===0)return;let T=f-1;T<p?p=T:T>=p+$e?p=T-$e+1:p+$e>a.length&&(p=Math.max(0,a.length-$e))},ws=()=>Math.max(2,ce-3),le=!1,at=!0,Ne=!1,fi=[],Cn=e.composerAgentId,Us=e.composerModel,Sr=()=>{let T=Cn;if(!T)return"";let M=Us;return M?`${T}\u2022${M}`:T},js=null,bs=null,Vt=null,qs=()=>{let T=ws(),M=`\u2500 ${fn} `,U=Sr(),Q="";if(U.length>0){let et=`\u2500 ${U} `;et.length+M.length+1<=T&&(Q=et)}let te=Math.max(1,T-M.length-Q.length),oe="\u2500".repeat(te),me=(f===0||le)&&at;if(js=M.length>0?{start:2,end:1+M.length}:null,Q.length>0){let et=1+M.length+te+1;bs={start:et,end:et+Q.length-1}}else bs=null;let He=me?n.brightBlue:n.dim,Je=me?n.brightBlue.bold:n.dim.bold,rt=(et,As)=>{(As?Je:He).noFormat(et)};He.noFormat("\u256D"),rt(M,Vt==="cwd"),He.noFormat(oe),Q&&rt(Q,Vt==="agent"),He.noFormat("\u256E")},pi=()=>{let T=ws(),M="\u2500".repeat(T);(f===0||le)&&at?n.brightBlue.noFormat(`\u2570${M}\u256F`):n.dim.noFormat(`\u2570${M}\u256F`)},zn=()=>{let T=Be();if(T===null)return;let M=Math.max(0,Jt(n)-2);if(T.plain.length>M){let U=T.plain.slice(0,Math.max(0,M-1))+"\u2026";n.dim.noFormat(` ${U}`);return}T.render()},Fo=T=>{let M=xn[T];return M?(_e.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},vs=T=>{let M=ws(),U=Fo(T),Q=Math.max(0,M-1-U.length),te=" ".repeat(Q);(f===0||le)&&at?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${U}${te}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${U}${te}`),n.dim.noFormat("\u2502"))},kr=T=>{let M=Po[T]??"",U=a[T],Q=U&&U.priority&&U.priority>0?"* ":" ";f===T+1&&!le&&at?n.brightWhite.bgBlue.noFormat(`${Q}${M}`):n.noFormat(`${Q}${M}`)},jt=()=>{let T=p,M=Math.max(0,a.length-p-$e),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),T>0&&U.push({kind:"plain",text:`\u2191 ${T} above`}),M>0&&U.push({kind:"plain",text:`\u2193 ${M} below`}),U},Qt=()=>{let T=jt();return T.length===0?"":` ${T.map(M=>M.text).join(" \xB7 ")}`},mn=T=>pt(T),De=()=>{let T=k?`${k.sessionId}|${k.status}`:"";return["ind",S,T,G?`${G.text}${G.cursor}`:"",X??"",h?`1|${m}|${a.length}`:"0",Qt(),bi?"h1":"h0",Ks?"ho1":"ho0"].join("")},We=()=>{Le(()=>{Ee.paintRow(I(),De(),()=>{let T=()=>{Gn=null,qt=null};if(S==="confirm-kill"&&k)T(),n.brightYellow.noFormat(` kill ${mn(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)T(),k.status==="warm"?n.brightRed.noFormat(` kill + delete ${mn(k.sessionId)}? [y/N]`):n.brightRed.noFormat(` delete ${mn(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)T(),n.dim.noFormat(` working on ${mn(k.sessionId)}\u2026`);else if(S==="rename"&&k&&G){T();let M=G.text,U=G.cursor;n.brightYellow.noFormat(" title: "),n.brightYellow.noFormat(M.slice(0,U)),U<M.length?(n.bgBrightYellow.noFormat(M[U]??" "),n.brightYellow.noFormat(M.slice(U+1))):n.bgBrightYellow(" "),n.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(X!==null)T(),n.dim.noFormat(` ${X}`);else{let M=jt(),U=Qt(),Q="Esc \xB7 Go Back",te=Q.length,oe=5,me=U.length,He=Math.max(1,ce-me-te-oe);if(qt=null,M.length>0){n.dim.noFormat(" ");let Je=3;for(let rt=0;rt<M.length;rt++){let et=M[rt];rt>0&&(n.dim.noFormat(" \xB7 "),Je+=3),et.kind==="host"?(qt={start:Je,end:Je+et.text.length-1},Ks?n.noFormat(et.text):n.dim.noFormat(et.text)):n.dim.noFormat(et.text),Je+=et.text.length}}n.dim(" ".repeat(He)),bi?n.noFormat(Q):n.dim.noFormat(Q),Gn={start:ce-oe-te+1,end:ce-oe}}})})},Kn=T=>An+1+T,Ct=()=>An+Ht+1,Gt=()=>An+Ht+3,hi=T=>Gt()+1+(T-p),I=()=>Gt()+1+$e,Xt=()=>{let T=vr-Yt;if(T<0||T>=Ht)return;let M=3+li;n.moveTo(M,Kn(T))},Oo=()=>at?f===0?"f":le?"h":"u":"x",Ir=()=>`ct|${Oo()}|${ws()}|${fn}|${Sr()}|${Vt??""}`,mi=()=>`cb|${Oo()}|${ws()}`,Lo=()=>ye!==null?`cs|i|${ye}`:h?`cs|s|${m}|${a.length}`:V!==null?`cs|h|${V}`:"blank",Ws=T=>`cbb|${Oo()}|${ws()}|${Fo(T)}`,Ss=()=>`h|${Wn}`,xr=T=>{let M=a[T],U=M&&M.priority&&M.priority>0?"* ":" ",Q=Po[T]??"";return`sr|${f===T+1&&!le&&at?"1":"0"}|${U}${Q}`},Ze=()=>{Le(()=>{n.hideCursor(),ui(),hn(),An=1,Ee.ensureSize(ce,ee),Ee.paintRow(An,Ir(),()=>{qs()});for(let T=0;T<Ht;T++){let M=Yt+T;Ee.paintRow(Kn(T),Ws(M),()=>{vs(M)})}Ee.paintRow(Ct(),mi(),()=>{pi()}),Ee.paintRow(Ct()+1,Lo(),()=>zn()),Ee.paintRow(Gt(),Ss(),()=>{n.dim.noFormat(` ${Wn}`)});for(let T=0;T<$e;T++){let M=p+T,U=Gt()+1+T;M<a.length?Ee.paintRow(U,xr(M),()=>{kr(M)}):Ee.paintRow(U,"blank",()=>{})}We();for(let T=I()+1;T<=ee;T++)Ee.paintRow(T,"blank",()=>{});f===0&&(Xt(),n.hideCursor(!1))})},od=()=>{Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Ze()},Bo=()=>{Le(()=>{n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(" Picker hotkeys")(`
217
+ `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:t.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(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=t.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=tv(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 t=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=t.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=tv(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 t=bo,s=La;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
218
+ `);this.pasteBuffer="";let a=Fb(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(t);if(r===-1){let i=zT(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+t.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 t=this.term.width;return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let s of e)t+=this.wrappedRowsOf(s);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let s of t)this.forgetLine(s);this.invalidateSelectionIfTouches(t);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let o of t)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=t.length-s.count,d=this.lines.slice(s.start,o),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=d[f],h=t[f];p!==void 0&&YT(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=t.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=t.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=c);i=this.wrappedRowsOfMany(t)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),i=this.wrappedRowsOfMany(t);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,s,r){if(e.length===0)return;let i=e.split(`
219
+ `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let 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:t,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(t.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(),t=wl(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:t,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,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),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)),ie({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,t){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.sourceLineId),i=s<r||s===r&&e.offset<=t.offset,o=i?e:t,a=i?t: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 t=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.startLineId),i=this.lineIndexById(t.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,t.startOffset),c=o(s,e.offset,i,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(c>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-t.endOffset)>=d?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let c=(r.body??"").slice(o.start,o.end);(Ga(r.bodyStyle)||r.ansi)&&(c=Qb(c)),t.push(c)}return t.join(`
220
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(t===-1||s===-1)return null;let r=t,i=s,o=e.startOffset,a=e.endOffset;t>s&&(r=s,i=t,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 t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=t.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,c=Math.max(r.start,i),d=Math.min(r.end,a);if(d<=c)return null;let l,u;if(s.sourceColEnd!==void 0){let f=this.sourceBodyForId(s.sourceLineId);if(f===null)return null;let p=Sp(f,i,c),h=Sp(f,c,d);l=kp(e.body,o,p),u=kp(e.body,l,h)}else l=c-i+o,u=d-i+o;return{start:l,end:u,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,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 t of e){let s=this.lineIds.get(t);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 t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(t.start,s)),o=this.lines.splice(t.start,t.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>t.start&&(c.start-=t.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 t=e.start+e.count;if(t>=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>=t&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),i=this.lines.splice(t.start,t.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>t.start&&(o.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let s=[...t].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(!t.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,t,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=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(zf),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(t=>({...t}))}: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 t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!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},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let t=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){t=!1;break}if(t)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;t&&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 t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=t!==void 0&&t.start+t.count===this.lines.length,r=s?t.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(t.start,0,o),t.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,t){if(process.env.HYDRA_TUI_KEY_TRACE&&ie({tag:"key",name:e,isChar:!!t.isCharacter}),t.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=Sl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){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(t),a=JT(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)<=gl&&Math.abs(o.y-d.y)<=gl&&Date.now()-d.t<=fp||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,KT(t,"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,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=fp&&Math.abs(e.x-i.x)<=gl&&Math.abs(e.y-i.y)<=gl&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let u=e.y;for(;u>1&&this.keyAtRow(u-1)===l;)u-=1;let f=e.y-u;if(this.onBlockDoubleClick(l,f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&Jb.test(l)){let f=l.match(Jb)?.[1]??null;if(f&&this.onHydraLinkClick(f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let s=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&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 t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),c=Math.max(0,t-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>=t-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,t){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=t-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=t+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,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)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(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),!yl.test(r[a])&&!hp.test(r[a]))return null;let c=a;for(;c>0&&hp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&hp.test(r[d]);)d++;for(;d>c+1&&LT.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!yl.test(r[a]))return null;let u=a;for(;u>0&&yl.test(r[u-1]);)u--;let f=a+1;for(;f<r.length&&yl.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,u,f)}projectCleanRangeToRaw(e,t,s,r){let i=t,o=t;for(let a=0;a<e.length;a++)if(e[a]===s&&i===t&&(i=a),e[a]===r&&o===t){o=a;break}return{start:i,end:o}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(t.links){for(let p of t.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!pp.test(r[a]))return null;let c=a;for(;c>0&&pp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&pp.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))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 t=this.lineById(e.sourceLineId);if(t===null||t.ansi||!t.links)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=vp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of t.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?zb():`${zb()}/${t.slice(2)}`);let s=Kb(t)||e.startsWith("~"),r=Kb(t)?t:FT(this.sessionbar.cwd,t);if(s)return r;try{if(Wb(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.raw;if(!BT.test(s))return!1;let r=s.startsWith(Dt)?[s]:[Dt+s,s],i=null;for(let o of r)try{if(Wb(O.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(t=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(t);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=$T(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,t){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,t)},fp);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:t}}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 t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let s=this.lines[t];if(s&&this.lineIds.get(s)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Nb(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,s=Number(t.x),r=Number(t.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"?Hw:el))}keyAtRow(e){let t=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(t,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 t=e-1;t>=1;t--){let s=this.keyAtRow(t);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 t=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(t,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,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-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=yr(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=Ga(p.bodyStyle)||p.ansi===!0?jb(xp(p.body),b):Ub(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=Sp(p.body,y,k),P=kp(A,h.sourceColOffset,E);return{sourceLineId:h.sourceLineId,offset:P}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+k-y}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),s=Math.min(t,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 t=e.toLowerCase(),s=[];if(t.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(t,c);if(d===-1)break;a.push(d),c=d+t.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=t.length>0?t: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 t=this.lines[e.lineIdx];if(!t)return null;let s=this.lineIds.get(t);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==t.lineId)return null;let r=s.bodyDisplayShift??0,i=t.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}scrollToMatch(e){let t=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,t).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,t),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 t=this.term.height-this.promptRows()-Ve-st-nt-NT-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-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,t,s){this.started&&this.painter.paintRow(e,t,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),Le(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-nt-st-Ve;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Ve),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),t=this.term.height,s=this.sessionbar.title?.trim(),r=By(this.sessionbar.agent,this.sessionbar.model),i=ct(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Qe(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=Qe(l),f,p;if(s){let b=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-b)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=Rt(i,f),m=s?Rt(s,p):"",y=Qe(h)+(s?u+Qe(m):0),w=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(w)),this.term.noFormat(r)})}drawSeparator(e){let t=this.term.width,s=wl(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?ps(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;c.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;c.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let d=ev(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Qe(o)+Qe(u)+f.length+Qe(s);for(let A of c)y+=Qe(" \xB7 ")+Qe(A.text);y+=Qe(p);let w=Qe(h)+Qe(d)+Qe(m),b=Math.max(0,t-y-w),S="\u2500".repeat(b),k=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),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 A of c)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let t=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=Qe(i)+Qe(a)+Qe(o),d=Math.max(0,t-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${t}|${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 w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let b=m[w];if(b===void 0)continue;let S=null;b.includes("mode")?S="mode":b.includes("pick")?S="pick":b.includes("guide")?S="guide":b.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(b):this.term.dim(b)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Qe(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Qe(w),S=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=S:w.includes("pick")&&h.pick===null?h.pick=S:w.includes("guide")&&h.guide===null?h.guide=S:w.includes("detach")&&h.detach===null&&(h.detach=S),m+=b+Qe(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?wl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=ev(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Qe(t)+i.length+Qe(r)+o.length+Qe(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:t,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()-nt-st-Ve,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=wl(this.btwOverlaySessionId),u=1+c.length+Qe(a)+" \xB7 ".length,f=u+Qe(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,t=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=t+h,y=h-d,w=y>=0?c[y]:void 0,b=this.activeMatchCol(w,l),S=w?this.selectionRangeForChunk(w):null,k=w!==void 0&&w.blockKey!==void 0&&(w.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w.blockKey)),A=w!==void 0&&w.blockKey===void 0&&f!==-1&&y>=f&&y<=p,E=k||A,P=this.terminalFocused&&E&&(this.hoveredSubKey===null||(w.hoverSubKey??null)===this.hoveredSubKey),H=Yb("sb",e,w,this.scrollbackHighlight,b,S)+(P?"|H":"");this.paintRow(m,H,()=>{w&&this.writeFormattedLine(w,e,b,u,S,P)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(gp,this.queuedTexts.length)}chipRows(){return Math.min(wp,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,s)=>t===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(yp,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Ve-st-nt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>yp,h=this.completions.length-yp+1,m=f?p?`comp|${t}|overflow|${h}`:`comp|${t}|${d}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),w=f.description??"",b=t-y.length-4,S=b>0?Rt(w,b):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Ve-st-nt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>wp,u=this.attachments.length-wp,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${xn(f.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${u}`:f?`chip|${t}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${t}|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,t){process.stdout.write(eE(e,t,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Ve-st-nt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>gp,p=this.queuedTexts.length-gp,h=u===void 0?"":f?`+ ${p+1} more queued`:Rt(iE(u),t-4),m=!f&&d===c,y=u===void 0?`queued|${t}|empty`:`queued|${t}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let w=`\u23F3 ${h}`,b=w+" ".repeat(Math.max(0,t-1-w.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=gs(s.buffer,t),i=Ds(r,s,mp),o=this.term.height-i.rendered-nt-st-Ve+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 t=this.term.width,s=this.term.height-bp-nt-st-Ve+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${Rt(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${Rt(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,s=this.compactionRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${Rt(e.message,t-2)}`)}),o(`cpct|q|${t}`,()=>{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}. ${Rt(c.label,t-8)}`;o(`cpct|o|${t}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${t}`,()=>{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 t=this.term.width,s=this.helpRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${Rt(e.title,t-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|${t}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${t}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${Rt(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${Rt(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(UT,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,s=this.permissionRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${Rt(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${t}|${a}`,()=>{this.term.dim(` ${Rt(a,t-2)}`)}),o(`perm|q|${t}`,()=>{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}. ${Rt(d.label,t-8)}`;o(`perm|o|${t}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${t}`,()=>{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,t){let s=this.bannerHits;if(!s||t!==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,t=this.promptRows(),s=e-t-nt-st-Ve;this.drawSeparator(s),this.drawBottomSeparator(e-Ve)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-nt-st-Ve+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-nt-st-Ve+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-bp-nt-st-Ve+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-nt-st-Ve+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-nt-st-Ve;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-nt-st-Ve+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,t=Math.max(1,e-2),s=this.dispatcher.state(),r=gs(s.buffer,t),i=Ds(r,s,mp),a=this.term.height-i.rendered-nt-st-Ve+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-nt-st-Ve;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 bp;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=gs(s.buffer,t);return Math.min(mp,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(DT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(HT,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let t=this.term.width,s=this.optionsRows(),r=this.term.height-s-nt-st-Ve+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${Rt(e.title,t-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=t-p.length-3,y=`${p}${Rt(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${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|${t}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,s=this.wrapBtwTail(t,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,t){if(e<=4){let o=Math.min(t,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(t<=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>=t)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>t?i.slice(i.length-t):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let t=this.term.width,r=this.term.height-this.promptRows()-nt-st-Ve,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(t,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=Yb(`btw|c${f}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){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(t,d.length);return{rows:d.slice(d.length-l),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=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>=t)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,t){let s=this.lineIds.get(e);if(s!==void 0){let h=this.wrapCache.get(s);if(h)return h}let r=e.prefix??"",i=yr(r),o=Math.max(1,t-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),c=Math.max(1,o-a),d=Ga(e.bodyStyle),l=e.ansi?VT(e.body,a>0?c:o):tE(e.body,a>0?c:o,{stripMarkup:d}),u=[],f=0,p=0;for(let h=0;h<l.length;h++){let m=l[h]??"",y=h===0||a===0?m:" ".repeat(a)+m,w={prefix:h===0?e.prefix:" ".repeat(i),body:y};if(e.prefixStyle!==void 0&&(w.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(w.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(w.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(w.hoverSubKey=e.hoverSubKey),e.fillRow&&(w.fillRow=!0),e.ansi&&(w.ansi=!0),h===0&&e.iterm2Image&&(w.iterm2Image=e.iterm2Image),s!==void 0&&m.length>0)if(e.ansi){let b=f,S=0;for(let P=0;P<m.length;){let H=jn(m,P);if(H){P+=H.text.length,H.width>0&&(S+=1);continue}S+=1,P+=1}let k=S;for(;k>0&&f<e.body.length;){let P=jn(e.body,f);if(P){f+=P.text.length,P.width>0&&(k-=1);continue}f+=1,k-=1}let A=f;if(h===l.length-1){for(;A<e.body.length;){let P=jn(e.body,A);if(!P)break;A+=P.text.length}f=A}let E={sourceLineId:s,sourceColOffset:b,sourceColEnd:A};h>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(w,E)}else{let b=e.body.indexOf(m,p),S=b===-1?p:b,k={sourceLineId:s,sourceColOffset:S};h>0&&a>0&&(k.bodyDisplayShift=a),this.wrapOrigin.set(w,k),p=S+m.length}u.push(w)}return s!==void 0&&this.wrapCache.set(s,u),u}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1){e.prefix&&Ns(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,t-yr(e.prefix??"")),c=Ga(e.bodyStyle),d=e.ansi?e.body:Rt(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;Vb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Ns(this.term,u,e.bodyStyle,o)};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=Ga(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Qb(m)),Ns(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=ZT(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Vb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Ns(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?Qe(d):yr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Ns(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)}};nv=/[^\x20-\x7e]/,Ip=new Intl.Segmenter(void 0,{granularity:"grapheme"}),sv=!1;QT=/[a-zA-Z+\-:_!#/]/;wl=pt});function oE(n,e,t=kl){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=t[n];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,n-1)};let r=t.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=t[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:n}}async function dv(n,e){Hn();let t=pt(e.sessionId),s=e.importedFromMachine??"another machine",r=ct(e.cwd),i=kl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+kl.length*2+2,d=Un(n,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)n.moveTo(d.contentX,d.contentY+f),n.dim.noFormat(` ${p.label}`),n.noFormat(Xe(p.value,l-p.label.length-2)),f++;return f++,cv(n,d,f,{intro:"What do you want to do?",choices:kl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return hs({term:n,render:o,onKey:(a,c,d,l)=>{let u=aE(a,d);if(!u)return;let f=oE(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 cv(n,e,t,s){let r=e.contentW,i=t;n.moveTo(e.contentX,e.contentY+i),n.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}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Ha(d,r)):n.noFormat(d),i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${a.description}`),i++}i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${s.footer}`)}function aE(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function lv(n,e,t){let s=pt(e.sessionId),r=e.title??ct(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=Un(n,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;n.moveTo(c.contentX,c.contentY+l),n.dim.noFormat(" session: "),n.noFormat(Xe(s,d-10)),l++,n.moveTo(c.contentX,c.contentY+l),n.noFormat(" "+Xe(r,d-2)),l++,l++,cv(n,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(),n.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),t.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}}};t.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var kl,Cp=Y(()=>{"use strict";be();os();ri();kl=[{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 Za(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let s=n[t]??"",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 uv(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let s=t.indexOf(" "),r=s===-1?t:t.slice(0,s),i=s===-1?"":t.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Za(e);return o.length<=r.length?null:o+i}var Il=Y(()=>{"use strict"});var Eo,Rp=Y(()=>{"use strict";Eo=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,t={}){t.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,t=this.cur;for(;t<e&&/\s/.test(this.buffer[t]??"");)t+=1;for(;t<e&&!/\s/.test(this.buffer[t]??"");)t+=1;this.cur=t}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,t){if(t)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as fv from"os";async function di(n,e,t={}){let s=t.defaultCwd??(e?await xb(e.cwd):void 0)??fv.homedir();Hn();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:pt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:ct(e.cwd)}]:[],a=new Eo(s),c=null,d=!1,l=null,u=null,f=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),b=h.indexOf(y),S=()=>{let _=o.length+6;l=Un(n,{contentHeight:_,title:r,overlay:t.overlay===!0});let F=l.contentW,B=0;for(let j of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${j.label}`),n.noFormat(Xe(j.value,F-j.label.length-2)),B++;B++,n.moveTo(l.contentX,l.contentY+B),n.noFormat(` ${i}`),B+=2,E(B),B+=2;let N=l.contentY+B;c!==null?(n.moveTo(l.contentX,N),n.red.noFormat(` ${Xe(c,F-2)}`),u=null,f=null,p=null):(n.moveTo(l.contentX,N),n.dim.noFormat(h),u=N,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},k=()=>o.length+3,A=0,E=_=>{if(!l)return;let F=_??k();n.moveTo(l.contentX,l.contentY+F).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+F),n.dim.noFormat("\u2502"),n.moveTo(l.contentX,l.contentY+F),n.noFormat(" ");let N=Math.max(1,l.contentW-1-2),j=a.text,G=a.cursor;G<A&&(A=G),G-A>=N&&(A=G-N+1),A<0&&(A=0);let X=j.slice(A,A+N);A>0&&X.length>0&&(X="\u2026"+X.slice(1));let V=G-A;if(d){n.noFormat(X);return}V>=X.length?(n.noFormat(X),n.bgWhite(" ")):(n.noFormat(X.slice(0,V)),n.bgWhite.noFormat(X[V]??" "),n.noFormat(X.slice(V+1)))},P=()=>{if(E(),!l)return;let _=k()+2;n.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+_),n.dim.noFormat("\u2502");let F=l.contentY+_;n.moveTo(l.contentX,F),c!==null?(n.red.noFormat(` ${Xe(c,l.contentW-2)}`),u=null,f=null,p=null):(n.dim.noFormat(h),u=F,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},H=_=>{if(d)return;let F=a.text;d=!0,c=null,P(),za(F).then(B=>{if(d=!1,B.ok){_({kind:"ok",path:B.path});return}c=B.reason,P()})};return hs({term:n,render:S,overlay:t.overlay===!0,onKey:(_,F,B,N)=>{if(!d){if(_==="ENTER"||_==="KP_ENTER"){H(N);return}if(_==="ESCAPE"){N({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){N({kind:"cancel"});return}if(_==="TAB"){d=!0,Ab(a.text).then(j=>{if(d=!1,j.matches.length===0)return;let G;if(j.matches.length===1)G=j.prefix+j.matches[0];else{let X=Za(j.matches);if(X.length<=j.basePrefix.length)return;G=j.prefix+X}G!==a.text&&(a.setText(G,{recordUndo:!0}),c=null,P())});return}if(a.handleKey(_,B?.isCharacter===!0)){c=null,P();return}}},onMouse:(_,F,B)=>{if(d||_!=="MOUSE_LEFT_BUTTON_PRESSED")return;let N=F?.x,j=F?.y;if(!(typeof N!="number"||typeof j!="number")){if(l!==null&&(N<l.x||N>=l.x+l.w||j<l.y||j>=l.y+l.h)){B({kind:"back"});return}if(u!==null&&j===u){if(f!==null&&N>=f.start&&N<=f.end){H(B);return}if(p!==null&&N>=p.start&&N<=p.end){B({kind:"back"});return}}}}})}var Tp=Y(()=>{"use strict";be();os();ep();Il();ri();Rp()});import*as hv from"fs";import*as mv from"os";import*as xl from"path";function Al(n,e){let t=e;for(;t>0;){let s=n[t-1]??"";if(/\s/.test(s)){if(s===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function dE(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function cE(n){return n.replace(/\\ /g," ")}function pv(n){return n.replace(/ /g,"\\ ")}function lE(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function uE(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=mv.homedir()+t.slice(1)),xl.isAbsolute(t)?t:xl.resolve(e,t)}function fE(n){let e;try{e=hv.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function Cl(n,e,t=fE){let s=cE(n),{dirPrefix:r,base:i}=lE(s);if(r.length===0&&!dE(n)&&i.length===0)return null;let o=uE(r,e),a=t(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:pv(r+p),candidates:l}}let u=Za(d.map(f=>f.name));return{replacement:pv(r+u),candidates:l}}var Ep=Y(()=>{"use strict";Il()});function pE(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function hE(n,e,t){let s=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${s} via npm\u2026`:t.phase==="installed"?`${n} ${s} installed`:`${n} installing ${s} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let r=t.receivedBytes??0,i=t.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${c}%)`}return`${n} downloading ${s} ${o} MB`}return t.phase==="download_done"?`${n} downloaded ${s}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${s}\u2026`:t.phase==="installed"?`${n} ${s} installed`:e||n}function Rl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,pE(a))};return{write(a){t||(i=a,s=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=hE(i,s,a);s=d,e.write(d)},finalize(){t||(t=!0,o(0),e.finalize())}}}function gv(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),n.brightYellow(t))},finalize(){e||(e=!0,process.stdout.write(`
221
+ `))}}}var Pp=Y(()=>{"use strict"});function _p(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function $p(n,e){let t=()=>{process.stdout.write(ti),process.stdout.write(Os),process.stdout.write(ni),process.stdout.write(si),process.stdout.write(vo),process.stdout.write(So),process.stdout.write(ko),process.stdout.write(ei),process.stdout.write("\x1B>")};t();let s=e.prefs??_p();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Tl(e.sessions,r),o=T=>{let M=T;return s.filters.cwdOnly&&(M=M.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=vE(M,s.filters.hostFilter),M},a=o(i),c={columns:e.config.tui.sessionColumns??fo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(T=>ho(T,Date.now())),l=mo(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let T=a.findIndex(M=>M.sessionId===e.currentSessionId);T>=0&&(f=T+1)}let h=!1,m="",y=120,w=!1,b=0,S="normal",k=null,A=!1,E="input",P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,N=null,j=!1,G=null,X=null,V=null,ye=null,Be=()=>{if(ye!==null){let T=ye;return{plain:T,render:()=>{n.brightYellow.noFormat(` ${T}`)}}}if(h){let T=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${T} \xB7 ^c clears`,render:()=>{n.brightYellow.noFormat(` /${m}`),n.bgBrightYellow(" "),n.dim.noFormat(` ${T} \xB7 ^c clears`)}}}return V!==null?{plain:V,render:()=>{n.dim.noFormat(` ${V}`)}}:null},mt=!1,_e=new Bs({history:[]});if(e.initialPrompt&&_e.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)_e.addAttachment(T);let ys=e.config.tui.promptHistoryMaxEntries;ma(O.globalTuiHistoryFile()).then(T=>{let M=T.length>ys?T.slice(T.length-ys):T;_e.setHistory(M)}).catch(()=>{});let Ee=new To(n),ee=Ls(n),ce=Jt(n),$e=0,fn="",pn=0,An=[],Ht=1,Yt=0,vr=0,li=0,Wn="",Po=[],Cn=1,rd=0,Mo=[],Ut=1,Ce=0,_o=0,id=0,ui=()=>{ee=Ls(n),ce=Jt(n);let T=Math.max(10,ce-Mp-1);pn=Math.max(10,ce-yv);let M=Math.max(10,ce-8),U=_e.state().attachments.length,Q=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",te=Math.max(10,M-Q.length);fn=wE(r,te)+Q;let oe=_e.state();An=gs(oe.buffer,pn);let me=Ds(An,oe,ed);Ht=me.rendered,Yt=me.windowStart,vr=me.cursorVisualRow,li=me.cursorVisualCol;let He=6+Ht,Je=Math.max(3,ee-He);$e=Math.min(a.length,Je),Wn=ur(po,l,T,c).padEnd(T),Po=d.map(rt=>ur(rt,l,T,c).padEnd(T))},$o=()=>{d=a.map(T=>ho(T,Date.now())),l=mo(d,c),u=1+a.length,ui()},At=()=>{let T=o(i);h&&m.length>0?a=T.filter(M=>SE(M,m)):a=T,$o(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+$e>a.length&&(p=Math.max(0,a.length-$e)),hn()},ws=T=>{if(T!==void 0){let M=a.findIndex(U=>U.sessionId===T);if(M>=0){f=M+1,hn();return}}f=a.length>0?1:0,p=0,hn()},hn=()=>{if(f===0)return;let T=f-1;T<p?p=T:T>=p+$e?p=T-$e+1:p+$e>a.length&&(p=Math.max(0,a.length-$e))},bs=()=>Math.max(2,ce-3),le=!1,at=!0,Ne=!1,fi=[],Rn=e.composerAgentId,Us=e.composerModel,Sr=()=>{let T=Rn;if(!T)return"";let M=Us;return M?`${T}\u2022${M}`:T},js=null,vs=null,Vt=null,qs=()=>{let T=bs(),M=`\u2500 ${fn} `,U=Sr(),Q="";if(U.length>0){let et=`\u2500 ${U} `;et.length+M.length+1<=T&&(Q=et)}let te=Math.max(1,T-M.length-Q.length),oe="\u2500".repeat(te),me=(f===0||le)&&at;if(js=M.length>0?{start:2,end:1+M.length}:null,Q.length>0){let et=1+M.length+te+1;vs={start:et,end:et+Q.length-1}}else vs=null;let He=me?n.brightBlue:n.dim,Je=me?n.brightBlue.bold:n.dim.bold,rt=(et,Cs)=>{(Cs?Je:He).noFormat(et)};He.noFormat("\u256D"),rt(M,Vt==="cwd"),He.noFormat(oe),Q&&rt(Q,Vt==="agent"),He.noFormat("\u256E")},pi=()=>{let T=bs(),M="\u2500".repeat(T);(f===0||le)&&at?n.brightBlue.noFormat(`\u2570${M}\u256F`):n.dim.noFormat(`\u2570${M}\u256F`)},zn=()=>{let T=Be();if(T===null)return;let M=Math.max(0,Jt(n)-2);if(T.plain.length>M){let U=T.plain.slice(0,Math.max(0,M-1))+"\u2026";n.dim.noFormat(` ${U}`);return}T.render()},Fo=T=>{let M=An[T];return M?(_e.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},Ss=T=>{let M=bs(),U=Fo(T),Q=Math.max(0,M-1-U.length),te=" ".repeat(Q);(f===0||le)&&at?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${U}${te}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${U}${te}`),n.dim.noFormat("\u2502"))},kr=T=>{let M=Po[T]??"",U=a[T],Q=U&&U.priority&&U.priority>0?"* ":" ";f===T+1&&!le&&at?n.brightWhite.bgBlue.noFormat(`${Q}${M}`):n.noFormat(`${Q}${M}`)},jt=()=>{let T=p,M=Math.max(0,a.length-p-$e),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),T>0&&U.push({kind:"plain",text:`\u2191 ${T} above`}),M>0&&U.push({kind:"plain",text:`\u2193 ${M} below`}),U},Qt=()=>{let T=jt();return T.length===0?"":` ${T.map(M=>M.text).join(" \xB7 ")}`},mn=T=>pt(T),De=()=>{let T=k?`${k.sessionId}|${k.status}`:"";return["ind",S,T,G?`${G.text}${G.cursor}`:"",X??"",h?`1|${m}|${a.length}`:"0",Qt(),bi?"h1":"h0",Ks?"ho1":"ho0"].join("")},We=()=>{Le(()=>{Ee.paintRow(I(),De(),()=>{let T=()=>{Gn=null,qt=null};if(S==="confirm-kill"&&k)T(),n.brightYellow.noFormat(` kill ${mn(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)T(),k.status==="warm"?n.brightRed.noFormat(` kill + delete ${mn(k.sessionId)}? [y/N]`):n.brightRed.noFormat(` delete ${mn(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)T(),n.dim.noFormat(` working on ${mn(k.sessionId)}\u2026`);else if(S==="rename"&&k&&G){T();let M=G.text,U=G.cursor;n.brightYellow.noFormat(" title: "),n.brightYellow.noFormat(M.slice(0,U)),U<M.length?(n.bgBrightYellow.noFormat(M[U]??" "),n.brightYellow.noFormat(M.slice(U+1))):n.bgBrightYellow(" "),n.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(X!==null)T(),n.dim.noFormat(` ${X}`);else{let M=jt(),U=Qt(),Q="Esc \xB7 Go Back",te=Q.length,oe=5,me=U.length,He=Math.max(1,ce-me-te-oe);if(qt=null,M.length>0){n.dim.noFormat(" ");let Je=3;for(let rt=0;rt<M.length;rt++){let et=M[rt];rt>0&&(n.dim.noFormat(" \xB7 "),Je+=3),et.kind==="host"?(qt={start:Je,end:Je+et.text.length-1},Ks?n.noFormat(et.text):n.dim.noFormat(et.text)):n.dim.noFormat(et.text),Je+=et.text.length}}n.dim(" ".repeat(He)),bi?n.noFormat(Q):n.dim.noFormat(Q),Gn={start:ce-oe-te+1,end:ce-oe}}})})},Kn=T=>Cn+1+T,Ct=()=>Cn+Ht+1,Gt=()=>Cn+Ht+3,hi=T=>Gt()+1+(T-p),I=()=>Gt()+1+$e,Xt=()=>{let T=vr-Yt;if(T<0||T>=Ht)return;let M=3+li;n.moveTo(M,Kn(T))},Oo=()=>at?f===0?"f":le?"h":"u":"x",Ir=()=>`ct|${Oo()}|${bs()}|${fn}|${Sr()}|${Vt??""}`,mi=()=>`cb|${Oo()}|${bs()}`,Lo=()=>ye!==null?`cs|i|${ye}`:h?`cs|s|${m}|${a.length}`:V!==null?`cs|h|${V}`:"blank",Ws=T=>`cbb|${Oo()}|${bs()}|${Fo(T)}`,ks=()=>`h|${Wn}`,xr=T=>{let M=a[T],U=M&&M.priority&&M.priority>0?"* ":" ",Q=Po[T]??"";return`sr|${f===T+1&&!le&&at?"1":"0"}|${U}${Q}`},Ze=()=>{Le(()=>{n.hideCursor(),ui(),hn(),Cn=1,Ee.ensureSize(ce,ee),Ee.paintRow(Cn,Ir(),()=>{qs()});for(let T=0;T<Ht;T++){let M=Yt+T;Ee.paintRow(Kn(T),Ws(M),()=>{Ss(M)})}Ee.paintRow(Ct(),mi(),()=>{pi()}),Ee.paintRow(Ct()+1,Lo(),()=>zn()),Ee.paintRow(Gt(),ks(),()=>{n.dim.noFormat(` ${Wn}`)});for(let T=0;T<$e;T++){let M=p+T,U=Gt()+1+T;M<a.length?Ee.paintRow(U,xr(M),()=>{kr(M)}):Ee.paintRow(U,"blank",()=>{})}We();for(let T=I()+1;T<=ee;T++)Ee.paintRow(T,"blank",()=>{});f===0&&(Xt(),n.hideCursor(!1))})},od=()=>{Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Ze()},Bo=()=>{Le(()=>{n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(" Picker hotkeys")(`
222
222
 
223
- `);for(let T of hE){if(T===null){n(`
224
- `);continue}let[M,U]=T;n.brightCyan.noFormat(` ${M.padEnd(pE)}`),n.noFormat(U)(`
223
+ `);for(let T of yE){if(T===null){n(`
224
+ `);continue}let[M,U]=T;n.brightCyan.noFormat(` ${M.padEnd(gE)}`),n.noFormat(U)(`
225
225
  `)}n(`
226
226
  `),n.dim.noFormat(" press any key to dismiss")(`
227
- `)})},bt=()=>Ut+4,ad=2,vt=0,ks=()=>{ee=Ls(n);let T=Math.max(2,ee-(Ut+3)-ad);return Math.max(1,Math.floor(T/2))},dd=()=>{let T=ks();F<vt?vt=F:F>=vt+T&&(vt=F-T+1),vt+T>H.length&&(vt=Math.max(0,H.length-T)),vt<0&&(vt=0)},cd=T=>{ce=Jt(n);let M=Math.max(2,ce-3),U="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,M-U.length));T?n.brightBlue.noFormat(`\u256D${U}${Q}\u256E`):n.dim.noFormat(`\u256D${U}${Q}\u256E`),n.styleReset()},Ar=()=>{ce=Jt(n),rd=Math.max(10,ce-gv);let T=P.state();Mo=ms(T.buffer,rd);let M=Ds(Mo,T,fE);Ut=M.rendered,Ce=M.windowStart,_o=M.cursorVisualRow,id=M.cursorVisualCol},No=(T,M)=>{ce=Jt(n);let U=Math.max(2,ce-3),Q=Mo[T],te="";Q&&(te=(P.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let oe=Math.max(0,U-1-te.length),me=" ".repeat(oe);M?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${te}${me}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${te}${me}`),n.dim.noFormat("\u2502")),n.styleReset()},ld=T=>{ce=Jt(n);let M=Math.max(2,ce-3),U="\u2500".repeat(M);T?n.brightBlue.noFormat(`\u2570${U}\u256F`):n.dim.noFormat(`\u2570${U}\u256F`),n.styleReset()},Tt=()=>3+id,ft=()=>2+(_o-Ce),Do=()=>{let T=E==="input";Le(()=>{T&&n.hideCursor(),n.moveTo(1,1),cd(T);for(let M=0;M<Ut;M++)n.moveTo(1,2+M),No(Ce+M,T);n.moveTo(1,2+Ut),ld(T),T&&(n.moveTo(Tt(),ft()),n.hideCursor(!1))})},Ho=()=>{Le(()=>{n.hideCursor();for(let T=0;T<Ut;T++)n.moveTo(1,2+T),No(Ce+T,!0);n.moveTo(Tt(),ft()),n.hideCursor(!1)})},Uo={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},jo=(T,M)=>{let U=H[T];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=Jt(n),te=Math.max(20,Q-Mp),oe=pt(U.sessionId),me=U.title??ct(U.cwd),He=M&&U.snippets.length>1?` [${B+1}/${U.snippets.length}]`:M&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",Je=`${oe} ${U.status==="warm"?"warm":"cold"}`,rt=Math.max(5,te-Je.length-He.length-2),et=_a(me,rt),As=`${Je} ${et}${He}`.padEnd(te),Ot=U.snippets[M?B:0],Cs=Ot?Uo[Ot.kind]??Ot.kind:"",Js=Ot?.toolName?`${Cs} \xB7 ${Ot.toolName}`:Cs,Ys=Math.max(10,te-Js.length-6),Ye=Ot?_a(Ot.text,Ys):"",yn=Ot?` ${Js} ${Ye}`:" (no snippet)";return{rowBudget:te,line1:As,line2:yn.padEnd(te+Mp),focusedRow:M}},Cr=(T,M)=>{let{line1:U,focusedRow:Q}=jo(T,M);Q?n.brightWhite.bgBlue.noFormat(`\u276F ${U}`):n.noFormat(` ${U}`),n.styleReset()},qo=(T,M)=>{let{line2:U}=jo(T,M);n.dim.noFormat(U),n.styleReset()},gi=()=>{if(j)n.dim.noFormat(" searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(N!==null)n.brightRed.noFormat(` ${N}`),n.styleReset(),n.eraseLineAfter();else if(E==="input")H.length>0?n.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):n.dim.noFormat(" Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let T=H.length,M=_?" \xB7 truncated":"",U=T>0?` ${T} ${T===1?"session":"sessions"} match${M} \xB7 `:" ";n.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Jn=()=>{Ar();let T=E==="input",M=P.state().buffer.join(`
228
- `);Le(()=>{n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),cd(T);for(let Q=0;Q<Ut;Q++)n.moveTo(1,2+Q),No(Ce+Q,T);n.moveTo(1,2+Ut),ld(T);let U=H.length;if(U===0)n.moveTo(1,bt()),j||(N===null&&M.trim().length===0?(n.dim.noFormat(" type a query in the box above, then press Enter"),n.eraseLineAfter()):N===null&&(n.dim.noFormat(" no matches"),n.eraseLineAfter())),n.moveTo(1,bt()+1),gi();else{dd();let Q=ks(),te=E!=="input";for(let oe=0;oe<Q;oe++){let me=vt+oe;n.moveTo(1,bt()+oe*2),me<U?Cr(me,te&&me===F):n.eraseLineAfter(),n.moveTo(1,bt()+oe*2+1),me<U?qo(me,te&&me===F):n.eraseLineAfter()}n.moveTo(1,bt()+Q*2),gi()}T&&(n.moveTo(Tt(),ft()),n.hideCursor(!1))})},Yn=(T,M)=>{let U=T-vt;U<0||U>=ks()||Le(()=>{n.moveTo(1,bt()+U*2),Cr(T,M),n.moveTo(1,bt()+U*2+1),qo(T,M)})},Rr=()=>{Le(()=>{n.moveTo(1,bt()+ks()*2),gi()})},ud=()=>{Le(()=>{let T=ks(),M=H.length,U=E!=="input";for(let Q=0;Q<T;Q++){let te=vt+Q;n.moveTo(1,bt()+Q*2),te<M?Cr(te,U&&te===F):n.eraseLineAfter(),n.moveTo(1,bt()+Q*2+1),te<M?qo(te,U&&te===F):n.eraseLineAfter()}n.moveTo(1,bt()+T*2),gi()})},fd=()=>P.state().buffer.join(`
229
- `),Tr=T=>{let M=Ut;P.feed({type:"paste",text:T}),Ar(),Ut!==M?Jn():Ho()},Rn=async()=>{let T=fd().trim();if(T.length!==0){if(a.length===0){N="no sessions in view to search",Jn();return}j=!0,N=null,Jn();try{let M=await Fy(e.target,T,{sessionIds:a.map(U=>U.sessionId)});H=M.results,_=M.truncated,F=0,B=0,vt=0,E=M.results.length>0?"results":"input",Ar()}catch(M){N=`search failed: ${M.message}`}finally{j=!1,Jn()}}},Zt=()=>{},en=()=>{Le(()=>{let T=f===0;T&&n.hideCursor(),Ee.paintRow(An,Ir(),()=>{qs()}),Ee.paintRow(Ct(),mi(),()=>{pi()});for(let M=0;M<Ht;M++){let U=Yt+M;Ee.paintRow(Kn(M),Ws(U),()=>{vs(U)})}T&&(Xt(),n.hideCursor(!1))})},Vn=()=>{Le(()=>{Ee.paintRow(Ct()+1,Lo(),()=>zn())})},Tn=()=>{V!==null&&(V=null,Vn())},Qn=()=>{Le(()=>{let T=_e.state();xn=ms(T.buffer,pn);let M=Ds(xn,T,ed);Yt=M.windowStart,vr=M.cursorVisualRow,li=M.cursorVisualCol;let U=f===0;U&&n.hideCursor();for(let Q=0;Q<Ht;Q++){let te=Yt+Q;Ee.paintRow(Kn(Q),Ws(te),()=>{vs(te)})}U&&(Xt(),n.hideCursor(!1))})},Wo=async()=>{let T=await pl();if(!T.ok){X=T.reason,We();return}if(T.kind!=="image"){let M=_e.state(),U=[...M.buffer],Q=M.row,te=M.col;_e.feed({type:"paste",text:T.text});let oe=_e.state();if(U.length!==oe.buffer.length||Q!==oe.row||te!==oe.col||!U.every((He,Je)=>He===oe.buffer[Je])){let He=ms(oe.buffer,pn);Ds(He,oe,ed).rendered!==Ht?Ze():Qn()}return}_e.addAttachment(T.attachment),X=`attached ${T.attachment.name??"image"}`,Ze()},pd=T=>{T<p||T>=p+$e||Le(()=>{Ee.paintRow(hi(T),xr(T),()=>{kr(T)})})},gn=()=>{Le(()=>{for(let T=0;T<$e;T++){let M=Gt()+1+T,U=p+T;U<a.length?Ee.paintRow(M,xr(U),()=>{kr(U)}):Ee.paintRow(M,"blank",()=>{})}We()})},zo=()=>{Le(()=>{Ee.paintRow(Gt(),Ss(),()=>{n.dim.noFormat(` ${Wn}`)});for(let T=0;T<$e;T++){let M=Gt()+1+T,U=p+T;U<a.length?Ee.paintRow(M,xr(U),()=>{kr(U)}):Ee.paintRow(M,"blank",()=>{})}We(),f===0&&(Xt(),n.hideCursor(!1))})},Is=!1,En="",yi=0,$l=200,zs=null,wi=!1,Gn=null,bi=!1,qt=null,Ks=!1,Ft=null,Er=null,Ko=null,xs=T=>{let M=T.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let Q=M.indexOf("\x1B[I"),te=M.indexOf("\x1B[O"),oe=Q===-1?te:te===-1?Q:Math.min(Q,te);if(oe===-1)break;let me=at;at=oe===Q,at&&(yi=Date.now()),me!==at&&!Ne&&fi.length<=1&&Le(()=>{en(),gn()}),M=M.slice(0,oe)+M.slice(oe+"\x1B[I".length)}if(M.length===0)return}if(!Is&&M===""&&Er){Er();return}if(!Is&&(M===""||M==="\x1B_"||M==="\x1B")){Ko?.(M);return}if(Is){let Q=M.indexOf(La);if(Q===-1){En+=M;return}En+=M.slice(0,Q),Is=!1;let te=Buffer.from(En,"binary").toString("utf-8").replace(/\r\n?/g,`
230
- `);En="";let oe=M.slice(Q+La.length);if(A)E==="input"&&!j&&Tr(te);else if(f===0&&!h){let me=_e.feed({type:"paste",text:te});for(let et of me)et.type==="attachment-request"&&Wo();let He=_e.state(),Je=ms(He.buffer,pn);Ds(Je,He,ed).rendered!==Ht?Ze():Qn()}oe.length>0&&Ft&&Ft(Buffer.from(oe,"binary"));return}let U=M.indexOf(bo);if(U===-1){Ft?.(T);return}U>0&&Ft?.(Buffer.from(M.slice(0,U),"binary")),M=M.slice(U+bo.length),Is=!0,M.length>0&&xs(Buffer.from(M,"binary"))};return Ze(),await new Promise(T=>{let M=null,U=!1,Q=null,te=!1,oe=fi,me=L=>{oe.push(L)},He=()=>{oe.pop(),Ne||oe[oe.length-1]?.onResize()},Je={push:me,pop:He},rt=()=>{let L={kind:"new",cwd:r},K=_e.state().attachments;return K.length>0&&(L.attachments=[...K]),Cn&&(L.agentId=Cn),Us&&(L.model=Us),L},et=async()=>{Si(),Ee.clearCache(),me({onKey:()=>{},onResize:()=>{}});let K;try{K=await di(n,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{He(),Xs()}K.kind==="ok"&&K.path!==r&&(r=K.path,i=Tl(i,r),At()),Ne||Ze()},As=async()=>{let L=e.availableAgents;if(!L||L.length===0)return;Si(),Ee.clearCache(),me({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await Ka(n,L,Cn,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{He(),Xs()}if(ue.kind==="select"){Cn=ue.agentId;let J=e.config.defaultModels;if(Us=J?J[ue.agentId]:void 0,ue.persist)try{await Ri(ue.agentId)}catch{}}Ne||Ze()};Zt=()=>{P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,vt=0,N=null,j=!1,E="input",A=!1,He()};let Ot=(L,K,ue)=>{Rs(),oe[oe.length-1]?.onKey(L,K,ue)},Cs=()=>{Ne||oe[oe.length-1]?.onResize()};Ko=L=>{Ne||oe[oe.length-1]?.onKey(L,null,{})};let Js=!1,Ys=()=>{if(Js)return;Js=!0,oe.length=0,M&&(clearInterval(M),M=null),Q&&(Q.abort(),Q=null,U=!1),n.off("key",Ot),n.off("mouse",Jo),n.off("resize",Cs),process.stdout.write(Os),process.stdout.write(Na);let L=n;L.stdin&&Ft&&(L.stdin.removeListener("data",xs),L.stdin.on("data",Ft),Ft=null),Is=!1,En="",n.grabInput(!1),ie({src:"grab",site:"picker.detachInput",on:!1})},Ye=()=>{Ne||(Ne=!0,Ys(),n.hideCursor(!1),n.moveTo(1,I()+1),n(`
231
- `))},yn=()=>{if(Ne||oe.length>1||S!=="normal"||h||te)return;U&&Q&&(Q.abort(),Q=null,U=!1);let L=f>0?a[f-1]?.sessionId:void 0;U=!0;let K=new AbortController;Q=K,Lt(L,{silent:!0,signal:K.signal}).finally(()=>{Q===K&&(Q=null),U=!1})},Rs=()=>{Ne||(M&&clearInterval(M),M=setInterval(yn,3e3))},Wt=()=>(Ys(),Rl("",{write(K){ye=K,Vn()},finalize(){ye=null,Ye()}})),tn=()=>(Ye(),T({kind:mt?"exit":"abort"}),!0),Vs=()=>{let L=d.map(K=>`${K.session}|${K.upstream}|${K.host}|${K.state}|${K.agent}|${K.model}|${K.age}|${K.title}|${K.cwd}|${K.cost}`).join(`
227
+ `)})},bt=()=>Ut+4,ad=2,vt=0,Is=()=>{ee=Ls(n);let T=Math.max(2,ee-(Ut+3)-ad);return Math.max(1,Math.floor(T/2))},dd=()=>{let T=Is();F<vt?vt=F:F>=vt+T&&(vt=F-T+1),vt+T>H.length&&(vt=Math.max(0,H.length-T)),vt<0&&(vt=0)},cd=T=>{ce=Jt(n);let M=Math.max(2,ce-3),U="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,M-U.length));T?n.brightBlue.noFormat(`\u256D${U}${Q}\u256E`):n.dim.noFormat(`\u256D${U}${Q}\u256E`),n.styleReset()},Ar=()=>{ce=Jt(n),rd=Math.max(10,ce-yv);let T=P.state();Mo=gs(T.buffer,rd);let M=Ds(Mo,T,mE);Ut=M.rendered,Ce=M.windowStart,_o=M.cursorVisualRow,id=M.cursorVisualCol},No=(T,M)=>{ce=Jt(n);let U=Math.max(2,ce-3),Q=Mo[T],te="";Q&&(te=(P.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let oe=Math.max(0,U-1-te.length),me=" ".repeat(oe);M?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${te}${me}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${te}${me}`),n.dim.noFormat("\u2502")),n.styleReset()},ld=T=>{ce=Jt(n);let M=Math.max(2,ce-3),U="\u2500".repeat(M);T?n.brightBlue.noFormat(`\u2570${U}\u256F`):n.dim.noFormat(`\u2570${U}\u256F`),n.styleReset()},Tt=()=>3+id,ft=()=>2+(_o-Ce),Do=()=>{let T=E==="input";Le(()=>{T&&n.hideCursor(),n.moveTo(1,1),cd(T);for(let M=0;M<Ut;M++)n.moveTo(1,2+M),No(Ce+M,T);n.moveTo(1,2+Ut),ld(T),T&&(n.moveTo(Tt(),ft()),n.hideCursor(!1))})},Ho=()=>{Le(()=>{n.hideCursor();for(let T=0;T<Ut;T++)n.moveTo(1,2+T),No(Ce+T,!0);n.moveTo(Tt(),ft()),n.hideCursor(!1)})},Uo={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},jo=(T,M)=>{let U=H[T];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=Jt(n),te=Math.max(20,Q-Mp),oe=pt(U.sessionId),me=U.title??ct(U.cwd),He=M&&U.snippets.length>1?` [${B+1}/${U.snippets.length}]`:M&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",Je=`${oe} ${U.status==="warm"?"warm":"cold"}`,rt=Math.max(5,te-Je.length-He.length-2),et=_a(me,rt),Cs=`${Je} ${et}${He}`.padEnd(te),Ot=U.snippets[M?B:0],Rs=Ot?Uo[Ot.kind]??Ot.kind:"",Js=Ot?.toolName?`${Rs} \xB7 ${Ot.toolName}`:Rs,Ys=Math.max(10,te-Js.length-6),Ye=Ot?_a(Ot.text,Ys):"",yn=Ot?` ${Js} ${Ye}`:" (no snippet)";return{rowBudget:te,line1:Cs,line2:yn.padEnd(te+Mp),focusedRow:M}},Cr=(T,M)=>{let{line1:U,focusedRow:Q}=jo(T,M);Q?n.brightWhite.bgBlue.noFormat(`\u276F ${U}`):n.noFormat(` ${U}`),n.styleReset()},qo=(T,M)=>{let{line2:U}=jo(T,M);n.dim.noFormat(U),n.styleReset()},gi=()=>{if(j)n.dim.noFormat(" searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(N!==null)n.brightRed.noFormat(` ${N}`),n.styleReset(),n.eraseLineAfter();else if(E==="input")H.length>0?n.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):n.dim.noFormat(" Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let T=H.length,M=_?" \xB7 truncated":"",U=T>0?` ${T} ${T===1?"session":"sessions"} match${M} \xB7 `:" ";n.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Jn=()=>{Ar();let T=E==="input",M=P.state().buffer.join(`
228
+ `);Le(()=>{n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),cd(T);for(let Q=0;Q<Ut;Q++)n.moveTo(1,2+Q),No(Ce+Q,T);n.moveTo(1,2+Ut),ld(T);let U=H.length;if(U===0)n.moveTo(1,bt()),j||(N===null&&M.trim().length===0?(n.dim.noFormat(" type a query in the box above, then press Enter"),n.eraseLineAfter()):N===null&&(n.dim.noFormat(" no matches"),n.eraseLineAfter())),n.moveTo(1,bt()+1),gi();else{dd();let Q=Is(),te=E!=="input";for(let oe=0;oe<Q;oe++){let me=vt+oe;n.moveTo(1,bt()+oe*2),me<U?Cr(me,te&&me===F):n.eraseLineAfter(),n.moveTo(1,bt()+oe*2+1),me<U?qo(me,te&&me===F):n.eraseLineAfter()}n.moveTo(1,bt()+Q*2),gi()}T&&(n.moveTo(Tt(),ft()),n.hideCursor(!1))})},Yn=(T,M)=>{let U=T-vt;U<0||U>=Is()||Le(()=>{n.moveTo(1,bt()+U*2),Cr(T,M),n.moveTo(1,bt()+U*2+1),qo(T,M)})},Rr=()=>{Le(()=>{n.moveTo(1,bt()+Is()*2),gi()})},ud=()=>{Le(()=>{let T=Is(),M=H.length,U=E!=="input";for(let Q=0;Q<T;Q++){let te=vt+Q;n.moveTo(1,bt()+Q*2),te<M?Cr(te,U&&te===F):n.eraseLineAfter(),n.moveTo(1,bt()+Q*2+1),te<M?qo(te,U&&te===F):n.eraseLineAfter()}n.moveTo(1,bt()+T*2),gi()})},fd=()=>P.state().buffer.join(`
229
+ `),Tr=T=>{let M=Ut;P.feed({type:"paste",text:T}),Ar(),Ut!==M?Jn():Ho()},Tn=async()=>{let T=fd().trim();if(T.length!==0){if(a.length===0){N="no sessions in view to search",Jn();return}j=!0,N=null,Jn();try{let M=await Oy(e.target,T,{sessionIds:a.map(U=>U.sessionId)});H=M.results,_=M.truncated,F=0,B=0,vt=0,E=M.results.length>0?"results":"input",Ar()}catch(M){N=`search failed: ${M.message}`}finally{j=!1,Jn()}}},Zt=()=>{},en=()=>{Le(()=>{let T=f===0;T&&n.hideCursor(),Ee.paintRow(Cn,Ir(),()=>{qs()}),Ee.paintRow(Ct(),mi(),()=>{pi()});for(let M=0;M<Ht;M++){let U=Yt+M;Ee.paintRow(Kn(M),Ws(U),()=>{Ss(U)})}T&&(Xt(),n.hideCursor(!1))})},Vn=()=>{Le(()=>{Ee.paintRow(Ct()+1,Lo(),()=>zn())})},En=()=>{V!==null&&(V=null,Vn())},Qn=()=>{Le(()=>{let T=_e.state();An=gs(T.buffer,pn);let M=Ds(An,T,ed);Yt=M.windowStart,vr=M.cursorVisualRow,li=M.cursorVisualCol;let U=f===0;U&&n.hideCursor();for(let Q=0;Q<Ht;Q++){let te=Yt+Q;Ee.paintRow(Kn(Q),Ws(te),()=>{Ss(te)})}U&&(Xt(),n.hideCursor(!1))})},Wo=async()=>{let T=await pl();if(!T.ok){X=T.reason,We();return}if(T.kind!=="image"){let M=_e.state(),U=[...M.buffer],Q=M.row,te=M.col;_e.feed({type:"paste",text:T.text});let oe=_e.state();if(U.length!==oe.buffer.length||Q!==oe.row||te!==oe.col||!U.every((He,Je)=>He===oe.buffer[Je])){let He=gs(oe.buffer,pn);Ds(He,oe,ed).rendered!==Ht?Ze():Qn()}return}_e.addAttachment(T.attachment),X=`attached ${T.attachment.name??"image"}`,Ze()},pd=T=>{T<p||T>=p+$e||Le(()=>{Ee.paintRow(hi(T),xr(T),()=>{kr(T)})})},gn=()=>{Le(()=>{for(let T=0;T<$e;T++){let M=Gt()+1+T,U=p+T;U<a.length?Ee.paintRow(M,xr(U),()=>{kr(U)}):Ee.paintRow(M,"blank",()=>{})}We()})},zo=()=>{Le(()=>{Ee.paintRow(Gt(),ks(),()=>{n.dim.noFormat(` ${Wn}`)});for(let T=0;T<$e;T++){let M=Gt()+1+T,U=p+T;U<a.length?Ee.paintRow(M,xr(U),()=>{kr(U)}):Ee.paintRow(M,"blank",()=>{})}We(),f===0&&(Xt(),n.hideCursor(!1))})},xs=!1,Pn="",yi=0,$l=200,zs=null,wi=!1,Gn=null,bi=!1,qt=null,Ks=!1,Ft=null,Er=null,Ko=null,As=T=>{let M=T.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let Q=M.indexOf("\x1B[I"),te=M.indexOf("\x1B[O"),oe=Q===-1?te:te===-1?Q:Math.min(Q,te);if(oe===-1)break;let me=at;at=oe===Q,at&&(yi=Date.now()),me!==at&&!Ne&&fi.length<=1&&Le(()=>{en(),gn()}),M=M.slice(0,oe)+M.slice(oe+"\x1B[I".length)}if(M.length===0)return}if(!xs&&M===""&&Er){Er();return}if(!xs&&(M===""||M==="\x1B_"||M==="\x1B")){Ko?.(M);return}if(xs){let Q=M.indexOf(La);if(Q===-1){Pn+=M;return}Pn+=M.slice(0,Q),xs=!1;let te=Buffer.from(Pn,"binary").toString("utf-8").replace(/\r\n?/g,`
230
+ `);Pn="";let oe=M.slice(Q+La.length);if(A)E==="input"&&!j&&Tr(te);else if(f===0&&!h){let me=_e.feed({type:"paste",text:te});for(let et of me)et.type==="attachment-request"&&Wo();let He=_e.state(),Je=gs(He.buffer,pn);Ds(Je,He,ed).rendered!==Ht?Ze():Qn()}oe.length>0&&Ft&&Ft(Buffer.from(oe,"binary"));return}let U=M.indexOf(bo);if(U===-1){Ft?.(T);return}U>0&&Ft?.(Buffer.from(M.slice(0,U),"binary")),M=M.slice(U+bo.length),xs=!0,M.length>0&&As(Buffer.from(M,"binary"))};return Ze(),await new Promise(T=>{let M=null,U=!1,Q=null,te=!1,oe=fi,me=L=>{oe.push(L)},He=()=>{oe.pop(),Ne||oe[oe.length-1]?.onResize()},Je={push:me,pop:He},rt=()=>{let L={kind:"new",cwd:r},K=_e.state().attachments;return K.length>0&&(L.attachments=[...K]),Rn&&(L.agentId=Rn),Us&&(L.model=Us),L},et=async()=>{Si(),Ee.clearCache(),me({onKey:()=>{},onResize:()=>{}});let K;try{K=await di(n,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{He(),Xs()}K.kind==="ok"&&K.path!==r&&(r=K.path,i=Tl(i,r),At()),Ne||Ze()},Cs=async()=>{let L=e.availableAgents;if(!L||L.length===0)return;Si(),Ee.clearCache(),me({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await Ka(n,L,Rn,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{He(),Xs()}if(ue.kind==="select"){Rn=ue.agentId;let J=e.config.defaultModels;if(Us=J?J[ue.agentId]:void 0,ue.persist)try{await Ri(ue.agentId)}catch{}}Ne||Ze()};Zt=()=>{P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,vt=0,N=null,j=!1,E="input",A=!1,He()};let Ot=(L,K,ue)=>{Ts(),oe[oe.length-1]?.onKey(L,K,ue)},Rs=()=>{Ne||oe[oe.length-1]?.onResize()};Ko=L=>{Ne||oe[oe.length-1]?.onKey(L,null,{})};let Js=!1,Ys=()=>{if(Js)return;Js=!0,oe.length=0,M&&(clearInterval(M),M=null),Q&&(Q.abort(),Q=null,U=!1),n.off("key",Ot),n.off("mouse",Jo),n.off("resize",Rs),process.stdout.write(Os),process.stdout.write(Na);let L=n;L.stdin&&Ft&&(L.stdin.removeListener("data",As),L.stdin.on("data",Ft),Ft=null),xs=!1,Pn="",n.grabInput(!1),ie({src:"grab",site:"picker.detachInput",on:!1})},Ye=()=>{Ne||(Ne=!0,Ys(),n.hideCursor(!1),n.moveTo(1,I()+1),n(`
231
+ `))},yn=()=>{if(Ne||oe.length>1||S!=="normal"||h||te)return;U&&Q&&(Q.abort(),Q=null,U=!1);let L=f>0?a[f-1]?.sessionId:void 0;U=!0;let K=new AbortController;Q=K,Lt(L,{silent:!0,signal:K.signal}).finally(()=>{Q===K&&(Q=null),U=!1})},Ts=()=>{Ne||(M&&clearInterval(M),M=setInterval(yn,3e3))},Wt=()=>(Ys(),Rl("",{write(K){ye=K,Vn()},finalize(){ye=null,Ye()}})),tn=()=>(Ye(),T({kind:mt?"exit":"abort"}),!0),Vs=()=>{let L=d.map(K=>`${K.session}|${K.upstream}|${K.host}|${K.state}|${K.agent}|${K.model}|${K.age}|${K.title}|${K.cwd}|${K.cost}`).join(`
232
232
  `);return`${f}:${p}:${X??""}
233
- ${L}`},Lt=async(L,K={})=>{try{let ue=K.silent?Vs():"",J=u,he=await Dn(e.target,{includeNonInteractive:!0,signal:K.signal}),de=L??(f>0?a[f-1]?.sessionId:void 0);if(i=Tl(he,r),At(),de!==void 0){let Pe=a.findIndex(Ae=>Ae.sessionId===de);Pe>=0?f=Pe+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+$e>a.length&&(p=Math.max(0,a.length-$e)),hn(),K.silent&&Vs()===ue)return;u===J?zo():Ze()}catch(ue){if(K.silent)return;X=`refresh failed: ${ue.message}`,Ze()}},Ts=async L=>{if(!k)return;let K=k;S="busy",We();try{await My(e.target,K.sessionId,L),S="normal",k=null,G=null,await Lt(K.sessionId)}catch(ue){S="normal",k=null,G=null,X=`rename failed: ${ue.message}`,We()}},Pr=async L=>{try{await $y(e.target,L.sessionId),X="title regen queued (press r to refresh)",We()}catch(K){X=`regen failed: ${K.message}`,We()}},vi=async L=>{let ue=(L.priority&&L.priority>0?L.priority:0)>0?null:1,J=ue??0;for(let de of i)de.sessionId===L.sessionId&&(de.priority=J>0?J:void 0);let he=L.sessionId;i=Tl(i,r),At(),ys(he),Ze(),X=J>0?"priority: high":"priority: normal",We();try{await _y(e.target,L.sessionId,ue)}catch(de){X=`priority failed: ${de.message}`,We()}},Mr=async()=>{if(te)return;te=!0;let L=f>0?a[f-1]?.sessionId:void 0;X="syncing agents\u2026",We();try{let{synced:K,skipped:ue,agents:J}=await Py(e.target);await Lt(L),X=`synced ${K} new (${ue} known) from ${J} agent${J===1?"":"s"}`,We()}catch(K){X=`sync failed: ${K.message}`,We()}finally{te=!1}},Qs=async L=>{if(!k)return;let K=k;S="busy",We();try{L==="kill"?await us(e.target,K.sessionId):await Oy(e.target,K.sessionId),S="normal",k=null,K.sessionId===e.currentSessionId&&(mt=!0);let ue;if(L==="kill")ue=K.sessionId;else{let J=a.findIndex(he=>he.sessionId===K.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await Lt(ue)}catch(ue){S="normal",k=null,X=`${L} failed: ${ue.message}`,We()}},Xn=(L,K)=>{L===0!=(K===0)&&(en(),K===0?(n.hideCursor(!1),Xt()):n.hideCursor())},qe=L=>{let K=Math.min(u-1,Math.max(0,f+L));if(K===f)return;let ue=f;f=K,hn(),Le(()=>{gn(),Xn(ue,f)})},nn=()=>X===null?!1:(X=null,We(),!0),Pn=()=>{Bo(),me({onKey:L=>{if(L==="CTRL_C"){Ye(),T({kind:"abort"});return}He()},onResize:()=>Bo()})},Zn=L=>{let K=null,ue=null,J=!0,he=()=>{Le(()=>{if(n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(` Session info \u2014 ${pt(L.sessionId)}`)(`
233
+ ${L}`},Lt=async(L,K={})=>{try{let ue=K.silent?Vs():"",J=u,he=await Dn(e.target,{includeNonInteractive:!0,signal:K.signal}),de=L??(f>0?a[f-1]?.sessionId:void 0);if(i=Tl(he,r),At(),de!==void 0){let Pe=a.findIndex(Ae=>Ae.sessionId===de);Pe>=0?f=Pe+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+$e>a.length&&(p=Math.max(0,a.length-$e)),hn(),K.silent&&Vs()===ue)return;u===J?zo():Ze()}catch(ue){if(K.silent)return;X=`refresh failed: ${ue.message}`,Ze()}},Es=async L=>{if(!k)return;let K=k;S="busy",We();try{await _y(e.target,K.sessionId,L),S="normal",k=null,G=null,await Lt(K.sessionId)}catch(ue){S="normal",k=null,G=null,X=`rename failed: ${ue.message}`,We()}},Pr=async L=>{try{await Fy(e.target,L.sessionId),X="title regen queued (press r to refresh)",We()}catch(K){X=`regen failed: ${K.message}`,We()}},vi=async L=>{let ue=(L.priority&&L.priority>0?L.priority:0)>0?null:1,J=ue??0;for(let de of i)de.sessionId===L.sessionId&&(de.priority=J>0?J:void 0);let he=L.sessionId;i=Tl(i,r),At(),ws(he),Ze(),X=J>0?"priority: high":"priority: normal",We();try{await $y(e.target,L.sessionId,ue)}catch(de){X=`priority failed: ${de.message}`,We()}},Mr=async()=>{if(te)return;te=!0;let L=f>0?a[f-1]?.sessionId:void 0;X="syncing agents\u2026",We();try{let{synced:K,skipped:ue,agents:J}=await My(e.target);await Lt(L),X=`synced ${K} new (${ue} known) from ${J} agent${J===1?"":"s"}`,We()}catch(K){X=`sync failed: ${K.message}`,We()}finally{te=!1}},Qs=async L=>{if(!k)return;let K=k;S="busy",We();try{L==="kill"?await fs(e.target,K.sessionId):await Ly(e.target,K.sessionId),S="normal",k=null,K.sessionId===e.currentSessionId&&(mt=!0);let ue;if(L==="kill")ue=K.sessionId;else{let J=a.findIndex(he=>he.sessionId===K.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await Lt(ue)}catch(ue){S="normal",k=null,X=`${L} failed: ${ue.message}`,We()}},Xn=(L,K)=>{L===0!=(K===0)&&(en(),K===0?(n.hideCursor(!1),Xt()):n.hideCursor())},qe=L=>{let K=Math.min(u-1,Math.max(0,f+L));if(K===f)return;let ue=f;f=K,hn(),Le(()=>{gn(),Xn(ue,f)})},nn=()=>X===null?!1:(X=null,We(),!0),Mn=()=>{Bo(),me({onKey:L=>{if(L==="CTRL_C"){Ye(),T({kind:"abort"});return}He()},onResize:()=>Bo()})},Zn=L=>{let K=null,ue=null,J=!0,he=()=>{Le(()=>{if(n.hideCursor(),Ee.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(` Session info \u2014 ${pt(L.sessionId)}`)(`
234
234
 
235
235
  `),J)n.dim.noFormat(" loading\u2026")(`
236
236
  `);else if(ue!==null)n.brightRed.noFormat(` ${ue}`)(`
@@ -238,50 +238,50 @@ ${L}`},Lt=async(L,K={})=>{try{let ue=K.silent?Vs():"",J=u,he=await Dn(e.target,{
238
238
  `);n(`
239
239
  `),n.dim.noFormat(" Esc / ^C to return")(`
240
240
  `)})};he();let de=new AbortController,Pe={onKey:Ae=>{if(Ae==="ESCAPE"||Ae==="CTRL_C"){de.abort(),He();return}},onResize:()=>he()};me(Pe),(async()=>{try{let Ae=await un(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(L.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:de.signal});if(!Ae.ok)throw new Error(`daemon returned HTTP ${Ae.status}`);let ze=await Ae.json(),dt=Nn(ze),sn=$f(dt,L.status);K=qc(sn,!1).replace(/\n$/,"").split(`
241
- `)}catch(Ae){if(de.signal.aborted)return;ue=`failed to load info: ${Ae.message}`}finally{J=!1,!Ne&&oe[oe.length-1]===Pe&&he()}})()},Gs=()=>{if(a.length===0){X="no sessions to search",We();return}P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,vt=0,N=null,j=!1,E="input",A=!0,Ar(),Jn(),me({onKey:(K,ue,J)=>{if(E==="input"){if(j)return;if(K==="ESCAPE"||K==="CTRL_C"){Zt();return}if(K==="ENTER"||K==="KP_ENTER"){if(fd().trim().length===0)return;Rn();return}if((K==="DOWN"||K==="TAB"||K==="CTRL_N")&&H.length>0){E="results",F=0,B=0,Le(()=>{Do(),Yn(0,!0),Rr(),n.hideCursor()});return}let he=P.state(),de=[...he.buffer],Pe=he.row,Ae=he.col,ze=null;if(K==="")ze={type:"key",name:"ctrl-underscore"};else if(K==="\x1B_"||K==="\x1B")ze={type:"key",name:"alt-underscore"};else if(J?.isCharacter)ze={type:"char",ch:K};else{let gt=Sl(K);gt!==null&&(ze={type:"key",name:gt})}if(ze===null){n.moveTo(Tt(),ft());return}P.feed(ze);let dt=P.state();if(de.length===dt.buffer.length&&de.every((gt,xe)=>gt===dt.buffer[xe])&&Pe===dt.row&&Ae===dt.col){n.moveTo(Tt(),ft());return}let es=Ut;Ar(),Ut!==es?Jn():Ho();return}if(E==="results"){if(K==="ESCAPE"||K==="CTRL_C"){Zt();return}if(K==="CTRL_F"){E="input",ud(),Rr(),Do();return}if(K==="ENTER"||K==="KP_ENTER"){let de=H[F];if(!de)return;let Pe=a.find(ze=>ze.sessionId===de.sessionId);if(!!Pe?.importedFromMachine&&!Pe.upstreamSessionId){Ye();let ze={kind:"attach",sessionId:de.sessionId};Pe.agentId!==void 0&&(ze.agentId=Pe.agentId),T(ze);return}(async()=>{let ze=await cv(n,{sessionId:de.sessionId,title:de.title,cwd:de.cwd},Je);if(ze==="cancel"){Ye(),T({kind:"abort"});return}if(ze==="back")return;Ye();let dt={kind:"attach",sessionId:de.sessionId,readonly:ze==="view"};Pe?.agentId!==void 0&&(dt.agentId=Pe.agentId),T(dt)})();return}if(J?.isCharacter&&(K==="n"||K==="N")){let de=H[F];if(!de||de.snippets.length<=1)return;B=(B+1)%de.snippets.length,Yn(F,!0);return}if(J?.isCharacter&&(K==="p"||K==="P")){let de=H[F];if(!de||de.snippets.length<=1)return;B=(B-1+de.snippets.length)%de.snippets.length,Yn(F,!0);return}let he=de=>{if(de<0&&F===0){E="input",Le(()=>{Yn(0,!1),Rr(),Do()});return}let Pe=Math.min(H.length-1,Math.max(0,F+de));if(Pe===F)return;let Ae=F,ze=vt;F=Pe,B=0,dd(),vt!==ze?ud():(Le(()=>{Yn(Ae,!1),Yn(F,!0)}),Rr())};switch(K){case"UP":case"SHIFT_TAB":case"CTRL_P":he(-1);return;case"DOWN":case"TAB":case"CTRL_N":he(1);return;case"PAGE_UP":he(-ks());return;case"PAGE_DOWN":he(ks());return;case"HOME":he(-F);return;case"END":he(H.length);return}return}},onResize:()=>Jn()})},Fl=(L,K,ue)=>{if(S!=="busy"){if(L==="CTRL_O"){et();return}if(L==="CTRL_L"){od();return}if(S==="rename"&&G){if(L==="ENTER"||L==="KP_ENTER"){let J=G.text.trim();if(J.length===0){S="normal",k=null,G=null,We();return}Ts(J);return}if(L==="ESCAPE"||L==="CTRL_C"){S="normal",k=null,G=null,We();return}if(G.handleKey(L,ue?.isCharacter===!0)){We();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(L==="y"||L==="Y")){Qs(S==="confirm-kill"?"kill":"delete");return}if(L==="ESCAPE"||L==="CTRL_C"||L==="ENTER"||L==="KP_ENTER"||ue?.isCharacter&&(L==="n"||L==="N")){S="normal",k=null,We();return}return}if(nn(),le&&(le=!1,f=0,Le(()=>{en(),gn()})),L==="CTRL_F"&&f!==0){Gs();return}if(f===0&&!h){if(L==="ESCAPE"){tn();return}if(L==="ENTER"||L==="KP_ENTER"){let xe=_e.expandedText(),St=rt();xe.trim().length>0&&(St.prompt=xe),St.installStatus=Wt(),T(St);return}if(L==="UP"&&w){let xe=Date.now(),St=xe-b;if(b=xe,St<y){Xt();return}w=!1}if(L==="DOWN"){let xe=_e.state(),St=xe.historyIndex!==-1||xe.queueIndex!==-1,Mn=xn.length===0||vr===xn.length-1;if(!St&&Mn&&a.length>0){qe(1);return}}if(L==="PAGE_DOWN"&&(xn.length===0||vr===xn.length-1)&&a.length>0){qe(1);return}if(L==="CTRL_P"){a.length>0&&qe(1);return}if(w=!1,L==="TAB"){let xe=_e.state(),St=xe.buffer[xe.row]??"",Mn=Al(St,xe.col);if(Mn!==null){let it=Cl(Mn.token,r);if(it!==null){if(it.replacement!==Mn.token&&(_e.replaceRangeOnCurrentLine(Mn.start,xe.col,it.replacement),Qn()),it.candidates.length>1){let _n=it.candidates.join(" ");V=`${it.candidates.length} matches: ${_n}`,Vn()}else Tn();Xt();return}}}Tn();let J=_e.state(),he=[...J.buffer],de=J.row,Pe=J.col,Ae=null;if(L==="")Ae={type:"key",name:"ctrl-underscore"};else if(L==="\x1B_"||L==="\x1B")Ae={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)Ae={type:"char",ch:L};else{let xe=Sl(L);xe!==null&&(Ae={type:"key",name:xe})}if(Ae===null){Xt();return}let ze=_e.feed(Ae),dt=_e.state(),sn=he.length===dt.buffer.length&&he.every((xe,St)=>xe===dt.buffer[St])&&de===dt.row&&Pe===dt.col;if(ze.some(xe=>xe.type==="exit")){tn();return}for(let xe of ze)xe.type==="attachment-request"&&Wo();if(sn){Xt();return}let es=ms(dt.buffer,pn);if(Ds(es,dt,ed).rendered!==Ht){Ze();return}Qn();return}if(!h&&ue?.isCharacter&&L==="?"){Pn();return}if(h){if(ue?.isCharacter){m+=L,At(),Ze();return}if(L==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),At(),Ze()):(h=!1,At(),Ze());return}if(L==="ESCAPE"||L==="CTRL_C"){h=!1,m="",At(),Ze();return}}if(ue?.isCharacter){if(L==="/"){h=!0,m="",At(),Ze();return}if(L==="n"||L==="N"){qe(1);return}if(L==="p"||L==="P"){qe(-1);return}if(L==="c"||L==="C"){let J=f>0?a[f-1]:void 0,he=rt();J?.cwd&&(he.cwd=J.cwd),he.installStatus=Wt(),T(he);return}if(L==="q"||L==="Q"){tn();return}if(L==="o"||L==="O"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,At(),ys(J),Ze();return}if(L==="h"||L==="H"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=yv(s.filters.hostFilter,i),At(),ys(J),Ze();return}if(L==="i"&&f>0){let J=a[f-1];if(!J)return;Zn(J);return}if(L==="I"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,At(),ys(J),Ze();return}if(L==="r"||L==="R"){let J=f>0?a[f-1]?.sessionId:void 0;Lt(J);return}if(L==="s"||L==="S"){Mr();return}if((L==="v"||L==="V")&&f>0){let J=a[f-1];if(!J)return;let he={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(he.agentId=J.agentId),he.installStatus=Wt(),T(he);return}if((L==="f"||L==="F")&&f>0){let J=a[f-1];if(!J)return;Ye();let he={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(he.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(he.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(he.sourceUpstreamSessionId=J.upstreamSessionId),T(he);return}if((L==="k"||L==="K")&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",We();return}if(L==="t"&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},G=new Eo(J.title??""),S="rename",We();return}if(L==="T"&&f>0){let J=a[f-1];if(!J)return;Pr({sessionId:J.sessionId});return}if(L==="*"&&f>0){let J=a[f-1];if(!J)return;vi(J);return}if((L==="d"||L==="D")&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",We();return}le=!1,f=0,_e.feed({type:"char",ch:L}),Ze();return}switch(L){case"UP":case"SHIFT_TAB":case"CTRL_P":L==="UP"&&(f===1&&(w=!0),b=Date.now()),qe(-1);return;case"DOWN":case"TAB":case"CTRL_N":qe(1);return;case"PAGE_UP":qe(-$e);return;case"PAGE_DOWN":qe($e);return;case"HOME":qe(1-f);return;case"END":qe(u);return;case"RIGHT":if(le||f===0)break;case"ENTER":case"KP_ENTER":{if(le){let de=_e.expandedText(),Pe=rt();de.trim().length>0&&(Pe.prompt=de),Pe.installStatus=Wt(),T(Pe);return}if(f===0){let de=rt();de.installStatus=Wt(),T(de);return}let J=a[f-1];if(!J){Ye(),T({kind:"abort"});return}let he={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(he.agentId=J.agentId),he.installStatus=Wt(),T(he);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":tn();return}}};me({onKey:(L,K,ue)=>Fl(L,K,ue),onResize:()=>{Ne||Ze()}});let Jo=(L,K)=>{if(Ne||oe.length!==1||S!=="normal")return;let ue=L==="MOUSE_MOTION",J=L==="MOUSE_LEFT_BUTTON_PRESSED",he=L==="MOUSE_LEFT_BUTTON_RELEASED",de=L==="MOUSE_WHEEL_UP",Pe=L==="MOUSE_WHEEL_DOWN",Ae=at&&Date.now()-yi<$l,ze=!at||Ae;if(J){zs={x:K?.x??-1,y:K?.y??-1},wi=ze;return}if(ue&&ze)return;let dt=he&&zs!==null&&K?.x===zs.x&&K?.y===zs.y,sn=dt&&!wi,es=dt&&wi;if(he&&(zs=null,wi=!1,!dt))return;if(de||Pe){if(a.length===0)return;let Ke=de?-3:3,yt=Math.max(0,a.length-$e),$r=Math.min(yt,Math.max(0,p+Ke));if($r===p)return;if(p=$r,f>0){let Qo=f-1;Qo<p?f=p+1:Qo>=p+$e&&(f=p+$e)}gn();return}if(!ue&&!sn)return;let gt=K?.y;if(typeof gt!="number")return;{let Ke=K?.x,yt=Gn!==null&&gt===I()&&typeof Ke=="number"&&Ke>=Gn.start&&Ke<=Gn.end,$r=qt!==null&&gt===I()&&typeof Ke=="number"&&Ke>=qt.start&&Ke<=qt.end;(yt!==bi||$r!==Ks)&&(bi=yt,Ks=$r,We(),f===0?(Xt(),n.hideCursor(!1)):n.hideCursor(!0))}if(sn&&Gn!==null&&gt===I()){let Ke=K?.x;if(typeof Ke=="number"&&Ke>=Gn.start&&Ke<=Gn.end){tn();return}}if(sn&&qt!==null&&gt===I()){let Ke=K?.x;if(typeof Ke=="number"&&Ke>=qt.start&&Ke<=qt.end){let yt=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=yv(s.filters.hostFilter,i),At(),ys(yt),Ze();return}}if(gt>=An&&gt<=Ct()){let Ke=null;if(gt===An){let yt=K?.x;typeof yt=="number"&&(bs!==null&&yt>=bs.start&&yt<=bs.end?Ke="agent":js!==null&&yt>=js.start&&yt<=js.end&&(Ke="cwd"))}if(Ke!==Vt&&(Vt=Ke,en()),sn&&gt===An){if(Vt==="agent"){As();return}if(Vt==="cwd"){et();return}}if((sn||es)&&f!==0){le=!1;let yt=f;f=0,Le(()=>{gn(),Xn(yt,f)});return}ue&&!le&&f!==0&&(le=!0,Le(()=>{en(),gn()}));return}Vt!==null&&(Vt=null,en()),le&&(le=!1,Le(()=>{en(),gn()}));let St=Gt()+1,Mn=St+$e-1;if(gt<St||gt>Mn)return;let it=p+(gt-St);if(it<0||it>=a.length)return;let _n=a[it];if(!_n)return;let _r=it+1;if(ue&&f===0)return;let Yo=f===0,hd=f===_r;if(es&&f!==_r){let Ke=f;f=_r,hn(),Le(()=>{gn(),Xn(Ke,f)});return}if(es)return;if(f!==_r){let Ke=f;f=_r,hn(),Le(()=>{gn(),Xn(Ke,f)})}if(!sn||Yo||!hd)return;let Vo={kind:"attach",sessionId:_n.sessionId};_n.agentId!==void 0&&(Vo.agentId=_n.agentId),Vo.installStatus=Wt(),T(Vo)},Xs=()=>{n.grabInput({mouse:"motion"}),ie({src:"grab",site:"picker.installGrab",on:!0});let L=n;L.stdin&&typeof L.onStdin=="function"&&(Ft=L.onStdin,L.stdin.removeListener("data",L.onStdin),L.stdin.on("data",xs),process.stdout.write(Xc),process.stdout.write(tl)),n.on("key",Ot),n.on("mouse",Jo),n.on("resize",Cs)},Si=()=>{process.stdout.write(Os),process.stdout.write(Na);let L=n;L.stdin&&Ft&&(L.stdin.removeListener("data",xs),L.stdin.on("data",Ft),Ft=null),Is=!1,En="",n.off("key",Ot),n.off("mouse",Jo),n.off("resize",Cs),n.grabInput(!1),ie({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Xs(),process.platform!=="win32"){let L=!1,K=()=>{L&&(L=!1,n.fullscreen(!0),t(),n.hideCursor(),Xs(),Ne||od())};Er=()=>{L||Ne||(L=!0,Si(),n.fullscreen(!1),process.stdout.write(`${Ba}${Zc}
242
- `),process.once("SIGCONT",K),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(yn,3e3)})}function mE(n,e){let t="Create new session in ",s=Math.max(1,e-t.length);return t+_a(ct(n),s)}function Tl(n,e){let t=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=t(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...n].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=t(i)-t(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function gE(n,e){return n?e.has(n):!0}function yE(n,e,t=gu()){return e==="__all"?n:e==="__local"?n.filter(s=>gE(s.importedFromMachine,t)||!!s.upstreamSessionId):n.filter(s=>s.importedFromMachine===e&&!t.has(e)&&!s.upstreamSessionId)}function yv(n,e,t=gu()){let s=new Set;for(let o of e)o.importedFromMachine&&!o.upstreamSessionId&&!t.has(o.importedFromMachine)&&s.add(o.importedFromMachine);let r=["__local",...[...s].sort(),"__all"],i=r.indexOf(n);return i===-1?"__local":r[(i+1)%r.length]??"__local"}function wE(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),s=[pt(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,ct(n.cwd)];for(let r of s)if(r.toLowerCase().includes(t))return!0;return!1}var Mp,ed,fE,gv,pE,hE,wv=Y(()=>{"use strict";Nc();Od();be();is();Ge();Ma();sp();Vd();hl();cp();Ap();Cp();Tp();Rp();Ep();ri();lp();up();Da();zr();Ff();Hr();Pp();Mp=2,ed=4,fE=4,gv=4,pE=20,hE=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import bE from"wrap-ansi";async function bv(n,e,t,s){Hn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=t.split(`
243
- `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(n),l=Ls(n),u=Math.min(vE,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(A=>bE(A,f,{hard:!0,trim:!1}).split(`
244
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,w=y.length+(m?1:0)+4,b=Un(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),S=b.contentW,k=0;n.moveTo(b.contentX,b.contentY+k),n.brightWhite.bold.noFormat(Xe(` ${i}`,S)),k+=2;for(let A of y)n.moveTo(b.contentX,b.contentY+k),n.brightRed.noFormat(Xe(` ${A}`,S)),k++;return m&&(n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(Xe(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(Xe(` ${a}`,S)),b};return ps({term:n,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 vE,vv=Y(()=>{"use strict";ri();vE=100});import{spawn as SE}from"child_process";function kE(n,e){let t="";for(let s=0;s<n.length;s++){let r=n[s];if(r!=="%"||s===n.length-1){t+=r;continue}switch(n[s+1]){case"%":t+="%",s++;break;case"s":t+=e.sessionId,s++;break;case"c":t+=e.cwd,s++;break;case"a":t+=e.agentId,s++;break;case"u":t+=e.baseUrl,s++;break;case"t":t+=e.tokenFile,s++;break;default:t+=r;break}}return t}function IE(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function xE(n,e){let t=IE(n.command);if(t.length===0)return null;let s=t.map(a=>tt(kE(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function AE(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(s,r)=>{if(e.truncated)return;let i=n-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>t(s,"stdout"),onStderr:s=>t(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function Sv(n,e,t){let s=xE(n,e);if(s===null){t.notify("hotkey: empty command");return}let r=AE(t.maxOutputBytes??CE),i=t.spawnFn??SE,o;try{o=i(s.program,s.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{t.emitLines(r.onExit(a,c))})}var CE,kv=Y(()=>{"use strict";Ge();CE=16*1024});import{spawn as RE,spawnSync as TE}from"child_process";import*as Hs from"fs";import*as El from"path";function Iv(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${EE}1337;SetUserVar=${n}=${t}${PE}`)}function xv(n){if(process.env.TMUX_PANE)try{let e=RE("tmux",n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function ME(){if(!process.stdin.isTTY)return null;let n=t=>{try{let s=Hs.readlinkSync(t);return s.startsWith("/dev/")&&s!=="/dev/tty"?El.basename(s):null}catch{return null}},e=n("/proc/self/fd/0")??n("/dev/fd/0");if(e)return e;try{let t=TE("tty",[],{encoding:"utf8",timeout:500});if(t.status!==0)return null;let s=t.stdout.trim();return!s.startsWith("/dev/")||s==="/dev/tty"?null:El.basename(s)}catch{return null}}function Av(){return Fp===void 0&&(Fp=ME()),Fp}function _E(n){let e=Av();if(e)try{Hs.mkdirSync(O.ttySessionDir(),{recursive:!0});let t=`${process.pid}:${process.ppid}:${n}
245
- `;Hs.writeFileSync(O.ttySessionFile(e),t,{mode:384})}catch{}}function $E(n){let e=n.trim();if(e.length===0)return null;if(!e.includes(":"))return{hydraPid:0,parentPid:0,sessionId:e};let t=e.split(":");if(t.length<3)return null;let s=Number.parseInt(t[0],10),r=Number.parseInt(t[1],10),i=t.slice(2).join(":");return!Number.isFinite(s)||!Number.isFinite(r)||i.length===0?null:{hydraPid:s,parentPid:r,sessionId:i}}function FE(){let n=Av();if(!n)return null;try{let e=Hs.readFileSync(O.ttySessionFile(n),"utf8");return $E(e)}catch{return null}}function OE(){let n=FE();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function Op(n){Iv("hydra_session",n),xv(["set-option","-pt",process.env.TMUX_PANE??"","@hydra_session",n]),_E(n)}function Cv(){Iv("hydra_session",""),xv(["set-option","-put",process.env.TMUX_PANE??"","@hydra_session"])}function Rv(){return OE()}var EE,PE,Fp,Tv=Y(()=>{"use strict";be();EE="\x1B]",PE="\x07"});function Ev(n){let e={};if(!n||typeof n!="object")return e;let t=n;typeof t.historyPolicy=="string"&&(e.appliedPolicy=t.historyPolicy),typeof t.clientId=="string"&&t.clientId.length>0&&(e.clientId=t.clientId);let s=t._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 Pv(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function Mv(n){return n.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:n.pendingTurns===0?1:0,banner:"busy",busySince:n.daemonTurnStartedAt}:{pendingTurnsDelta:n.pendingTurns>0?-n.pendingTurns:0,banner:"ready"}}var _v=Y(()=>{"use strict"});import{readFileSync as LE}from"fs";import{performance as BE}from"perf_hooks";import{writeHeapSnapshot as NE}from"v8";import{nanoid as $v}from"nanoid";import DE from"terminal-kit";import Lp from"fs/promises";import ci from"path";function HE(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function UE(n){let e=Pl(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function jE(n){let e=new Map,t=[];for(let s of n){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),t.push(r))}return t.map(s=>e.get(s))}function Pl(n){if(n.options&&n.options.length>0){let e=n.options.filter(t=>t!==n.defaultAnswer);return n.options.includes(n.defaultAnswer)?[n.defaultAnswer,...e]:[n.defaultAnswer,...n.options]}return[n.defaultAnswer]}function qE(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function WE(n,e,t,s,r=60){let i=n.map((o,a)=>{let c=Pl(o.representative),d=e[a]??0,l=t[a]?Np:c[d]??c[0]??"";return{label:qE(o.representative.question,r),value:l}});return{title:`Open questions (${n.length})`,options:i,selectedIndex:Math.max(0,Math.min(n.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 zE(n,e,t){return n===Np?{type:"dismiss",method:Rb,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:Cb,params:{sessionId:t,questionId:e.id,answer:n}}}function KE(n,e,t,s,r){let i=[];for(let o=0;o<n.length;o++){let a=n[o];if(!a||!t[o])continue;let c=s[o]?Np:Pl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=zE(c,l,r);u!==null&&i.push(u)}}return i}function JE(n,e,t,s,r,i,o,a){if(!e||t===null||t.length===0)return{type:"noop"};if(n.type==="char"){if(n.ch==="d"||n.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(n.ch)){let d=parseInt(n.ch,10)-1;if(d<t.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(n.type!=="key")return{type:"noop"};let c=d=>{let l=t[o];if(!l)return{type:"noop"};let u=Pl(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(n.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(t.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:KE(t,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Fv(n){if(!Array.isArray(n))return;let e=ds({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function Bp(n){switch(n.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function QE(n,e){e.has(n)?e.delete(n):e.add(n)}function GE(){if(Ov)return;Ov=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{ie({src:"uncaughtException",stack:n(e)}),wr(),process.stderr.write(`
241
+ `)}catch(Ae){if(de.signal.aborted)return;ue=`failed to load info: ${Ae.message}`}finally{J=!1,!Ne&&oe[oe.length-1]===Pe&&he()}})()},Gs=()=>{if(a.length===0){X="no sessions to search",We();return}P=new Bs({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,vt=0,N=null,j=!1,E="input",A=!0,Ar(),Jn(),me({onKey:(K,ue,J)=>{if(E==="input"){if(j)return;if(K==="ESCAPE"||K==="CTRL_C"){Zt();return}if(K==="ENTER"||K==="KP_ENTER"){if(fd().trim().length===0)return;Tn();return}if((K==="DOWN"||K==="TAB"||K==="CTRL_N")&&H.length>0){E="results",F=0,B=0,Le(()=>{Do(),Yn(0,!0),Rr(),n.hideCursor()});return}let he=P.state(),de=[...he.buffer],Pe=he.row,Ae=he.col,ze=null;if(K==="")ze={type:"key",name:"ctrl-underscore"};else if(K==="\x1B_"||K==="\x1B")ze={type:"key",name:"alt-underscore"};else if(J?.isCharacter)ze={type:"char",ch:K};else{let gt=Sl(K);gt!==null&&(ze={type:"key",name:gt})}if(ze===null){n.moveTo(Tt(),ft());return}P.feed(ze);let dt=P.state();if(de.length===dt.buffer.length&&de.every((gt,xe)=>gt===dt.buffer[xe])&&Pe===dt.row&&Ae===dt.col){n.moveTo(Tt(),ft());return}let es=Ut;Ar(),Ut!==es?Jn():Ho();return}if(E==="results"){if(K==="ESCAPE"||K==="CTRL_C"){Zt();return}if(K==="CTRL_F"){E="input",ud(),Rr(),Do();return}if(K==="ENTER"||K==="KP_ENTER"){let de=H[F];if(!de)return;let Pe=a.find(ze=>ze.sessionId===de.sessionId);if(!!Pe?.importedFromMachine&&!Pe.upstreamSessionId){Ye();let ze={kind:"attach",sessionId:de.sessionId};Pe.agentId!==void 0&&(ze.agentId=Pe.agentId),T(ze);return}(async()=>{let ze=await lv(n,{sessionId:de.sessionId,title:de.title,cwd:de.cwd},Je);if(ze==="cancel"){Ye(),T({kind:"abort"});return}if(ze==="back")return;Ye();let dt={kind:"attach",sessionId:de.sessionId,readonly:ze==="view"};Pe?.agentId!==void 0&&(dt.agentId=Pe.agentId),T(dt)})();return}if(J?.isCharacter&&(K==="n"||K==="N")){let de=H[F];if(!de||de.snippets.length<=1)return;B=(B+1)%de.snippets.length,Yn(F,!0);return}if(J?.isCharacter&&(K==="p"||K==="P")){let de=H[F];if(!de||de.snippets.length<=1)return;B=(B-1+de.snippets.length)%de.snippets.length,Yn(F,!0);return}let he=de=>{if(de<0&&F===0){E="input",Le(()=>{Yn(0,!1),Rr(),Do()});return}let Pe=Math.min(H.length-1,Math.max(0,F+de));if(Pe===F)return;let Ae=F,ze=vt;F=Pe,B=0,dd(),vt!==ze?ud():(Le(()=>{Yn(Ae,!1),Yn(F,!0)}),Rr())};switch(K){case"UP":case"SHIFT_TAB":case"CTRL_P":he(-1);return;case"DOWN":case"TAB":case"CTRL_N":he(1);return;case"PAGE_UP":he(-Is());return;case"PAGE_DOWN":he(Is());return;case"HOME":he(-F);return;case"END":he(H.length);return}return}},onResize:()=>Jn()})},Fl=(L,K,ue)=>{if(S!=="busy"){if(L==="CTRL_O"){et();return}if(L==="CTRL_L"){od();return}if(S==="rename"&&G){if(L==="ENTER"||L==="KP_ENTER"){let J=G.text.trim();if(J.length===0){S="normal",k=null,G=null,We();return}Es(J);return}if(L==="ESCAPE"||L==="CTRL_C"){S="normal",k=null,G=null,We();return}if(G.handleKey(L,ue?.isCharacter===!0)){We();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(L==="y"||L==="Y")){Qs(S==="confirm-kill"?"kill":"delete");return}if(L==="ESCAPE"||L==="CTRL_C"||L==="ENTER"||L==="KP_ENTER"||ue?.isCharacter&&(L==="n"||L==="N")){S="normal",k=null,We();return}return}if(nn(),le&&(le=!1,f=0,Le(()=>{en(),gn()})),L==="CTRL_F"&&f!==0){Gs();return}if(f===0&&!h){if(L==="ESCAPE"){tn();return}if(L==="ENTER"||L==="KP_ENTER"){let xe=_e.expandedText(),St=rt();xe.trim().length>0&&(St.prompt=xe),St.installStatus=Wt(),T(St);return}if(L==="UP"&&w){let xe=Date.now(),St=xe-b;if(b=xe,St<y){Xt();return}w=!1}if(L==="DOWN"){let xe=_e.state(),St=xe.historyIndex!==-1||xe.queueIndex!==-1,_n=An.length===0||vr===An.length-1;if(!St&&_n&&a.length>0){qe(1);return}}if(L==="PAGE_DOWN"&&(An.length===0||vr===An.length-1)&&a.length>0){qe(1);return}if(L==="CTRL_P"){a.length>0&&qe(1);return}if(w=!1,L==="TAB"){let xe=_e.state(),St=xe.buffer[xe.row]??"",_n=Al(St,xe.col);if(_n!==null){let it=Cl(_n.token,r);if(it!==null){if(it.replacement!==_n.token&&(_e.replaceRangeOnCurrentLine(_n.start,xe.col,it.replacement),Qn()),it.candidates.length>1){let $n=it.candidates.join(" ");V=`${it.candidates.length} matches: ${$n}`,Vn()}else En();Xt();return}}}En();let J=_e.state(),he=[...J.buffer],de=J.row,Pe=J.col,Ae=null;if(L==="")Ae={type:"key",name:"ctrl-underscore"};else if(L==="\x1B_"||L==="\x1B")Ae={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)Ae={type:"char",ch:L};else{let xe=Sl(L);xe!==null&&(Ae={type:"key",name:xe})}if(Ae===null){Xt();return}let ze=_e.feed(Ae),dt=_e.state(),sn=he.length===dt.buffer.length&&he.every((xe,St)=>xe===dt.buffer[St])&&de===dt.row&&Pe===dt.col;if(ze.some(xe=>xe.type==="exit")){tn();return}for(let xe of ze)xe.type==="attachment-request"&&Wo();if(sn){Xt();return}let es=gs(dt.buffer,pn);if(Ds(es,dt,ed).rendered!==Ht){Ze();return}Qn();return}if(!h&&ue?.isCharacter&&L==="?"){Mn();return}if(h){if(ue?.isCharacter){m+=L,At(),Ze();return}if(L==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),At(),Ze()):(h=!1,At(),Ze());return}if(L==="ESCAPE"||L==="CTRL_C"){h=!1,m="",At(),Ze();return}}if(ue?.isCharacter){if(L==="/"){h=!0,m="",At(),Ze();return}if(L==="n"||L==="N"){qe(1);return}if(L==="p"||L==="P"){qe(-1);return}if(L==="c"||L==="C"){let J=f>0?a[f-1]:void 0,he=rt();J?.cwd&&(he.cwd=J.cwd),he.installStatus=Wt(),T(he);return}if(L==="q"||L==="Q"){tn();return}if(L==="o"||L==="O"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,At(),ws(J),Ze();return}if(L==="h"||L==="H"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=wv(s.filters.hostFilter,i),At(),ws(J),Ze();return}if(L==="i"&&f>0){let J=a[f-1];if(!J)return;Zn(J);return}if(L==="I"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,At(),ws(J),Ze();return}if(L==="r"||L==="R"){let J=f>0?a[f-1]?.sessionId:void 0;Lt(J);return}if(L==="s"||L==="S"){Mr();return}if((L==="v"||L==="V")&&f>0){let J=a[f-1];if(!J)return;let he={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(he.agentId=J.agentId),he.installStatus=Wt(),T(he);return}if((L==="f"||L==="F")&&f>0){let J=a[f-1];if(!J)return;Ye();let he={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(he.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(he.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(he.sourceUpstreamSessionId=J.upstreamSessionId),T(he);return}if((L==="k"||L==="K")&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",We();return}if(L==="t"&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},G=new Eo(J.title??""),S="rename",We();return}if(L==="T"&&f>0){let J=a[f-1];if(!J)return;Pr({sessionId:J.sessionId});return}if(L==="*"&&f>0){let J=a[f-1];if(!J)return;vi(J);return}if((L==="d"||L==="D")&&f>0){let J=a[f-1];if(!J)return;k={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",We();return}le=!1,f=0,_e.feed({type:"char",ch:L}),Ze();return}switch(L){case"UP":case"SHIFT_TAB":case"CTRL_P":L==="UP"&&(f===1&&(w=!0),b=Date.now()),qe(-1);return;case"DOWN":case"TAB":case"CTRL_N":qe(1);return;case"PAGE_UP":qe(-$e);return;case"PAGE_DOWN":qe($e);return;case"HOME":qe(1-f);return;case"END":qe(u);return;case"RIGHT":if(le||f===0)break;case"ENTER":case"KP_ENTER":{if(le){let de=_e.expandedText(),Pe=rt();de.trim().length>0&&(Pe.prompt=de),Pe.installStatus=Wt(),T(Pe);return}if(f===0){let de=rt();de.installStatus=Wt(),T(de);return}let J=a[f-1];if(!J){Ye(),T({kind:"abort"});return}let he={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(he.agentId=J.agentId),he.installStatus=Wt(),T(he);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":tn();return}}};me({onKey:(L,K,ue)=>Fl(L,K,ue),onResize:()=>{Ne||Ze()}});let Jo=(L,K)=>{if(Ne||oe.length!==1||S!=="normal")return;let ue=L==="MOUSE_MOTION",J=L==="MOUSE_LEFT_BUTTON_PRESSED",he=L==="MOUSE_LEFT_BUTTON_RELEASED",de=L==="MOUSE_WHEEL_UP",Pe=L==="MOUSE_WHEEL_DOWN",Ae=at&&Date.now()-yi<$l,ze=!at||Ae;if(J){zs={x:K?.x??-1,y:K?.y??-1},wi=ze;return}if(ue&&ze)return;let dt=he&&zs!==null&&K?.x===zs.x&&K?.y===zs.y,sn=dt&&!wi,es=dt&&wi;if(he&&(zs=null,wi=!1,!dt))return;if(de||Pe){if(a.length===0)return;let Ke=de?-3:3,yt=Math.max(0,a.length-$e),$r=Math.min(yt,Math.max(0,p+Ke));if($r===p)return;if(p=$r,f>0){let Qo=f-1;Qo<p?f=p+1:Qo>=p+$e&&(f=p+$e)}gn();return}if(!ue&&!sn)return;let gt=K?.y;if(typeof gt!="number")return;{let Ke=K?.x,yt=Gn!==null&&gt===I()&&typeof Ke=="number"&&Ke>=Gn.start&&Ke<=Gn.end,$r=qt!==null&&gt===I()&&typeof Ke=="number"&&Ke>=qt.start&&Ke<=qt.end;(yt!==bi||$r!==Ks)&&(bi=yt,Ks=$r,We(),f===0?(Xt(),n.hideCursor(!1)):n.hideCursor(!0))}if(sn&&Gn!==null&&gt===I()){let Ke=K?.x;if(typeof Ke=="number"&&Ke>=Gn.start&&Ke<=Gn.end){tn();return}}if(sn&&qt!==null&&gt===I()){let Ke=K?.x;if(typeof Ke=="number"&&Ke>=qt.start&&Ke<=qt.end){let yt=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=wv(s.filters.hostFilter,i),At(),ws(yt),Ze();return}}if(gt>=Cn&&gt<=Ct()){let Ke=null;if(gt===Cn){let yt=K?.x;typeof yt=="number"&&(vs!==null&&yt>=vs.start&&yt<=vs.end?Ke="agent":js!==null&&yt>=js.start&&yt<=js.end&&(Ke="cwd"))}if(Ke!==Vt&&(Vt=Ke,en()),sn&&gt===Cn){if(Vt==="agent"){Cs();return}if(Vt==="cwd"){et();return}}if((sn||es)&&f!==0){le=!1;let yt=f;f=0,Le(()=>{gn(),Xn(yt,f)});return}ue&&!le&&f!==0&&(le=!0,Le(()=>{en(),gn()}));return}Vt!==null&&(Vt=null,en()),le&&(le=!1,Le(()=>{en(),gn()}));let St=Gt()+1,_n=St+$e-1;if(gt<St||gt>_n)return;let it=p+(gt-St);if(it<0||it>=a.length)return;let $n=a[it];if(!$n)return;let _r=it+1;if(ue&&f===0)return;let Yo=f===0,hd=f===_r;if(es&&f!==_r){let Ke=f;f=_r,hn(),Le(()=>{gn(),Xn(Ke,f)});return}if(es)return;if(f!==_r){let Ke=f;f=_r,hn(),Le(()=>{gn(),Xn(Ke,f)})}if(!sn||Yo||!hd)return;let Vo={kind:"attach",sessionId:$n.sessionId};$n.agentId!==void 0&&(Vo.agentId=$n.agentId),Vo.installStatus=Wt(),T(Vo)},Xs=()=>{n.grabInput({mouse:"motion"}),ie({src:"grab",site:"picker.installGrab",on:!0});let L=n;L.stdin&&typeof L.onStdin=="function"&&(Ft=L.onStdin,L.stdin.removeListener("data",L.onStdin),L.stdin.on("data",As),process.stdout.write(Xc),process.stdout.write(tl)),n.on("key",Ot),n.on("mouse",Jo),n.on("resize",Rs)},Si=()=>{process.stdout.write(Os),process.stdout.write(Na);let L=n;L.stdin&&Ft&&(L.stdin.removeListener("data",As),L.stdin.on("data",Ft),Ft=null),xs=!1,Pn="",n.off("key",Ot),n.off("mouse",Jo),n.off("resize",Rs),n.grabInput(!1),ie({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Xs(),process.platform!=="win32"){let L=!1,K=()=>{L&&(L=!1,n.fullscreen(!0),t(),n.hideCursor(),Xs(),Ne||od())};Er=()=>{L||Ne||(L=!0,Si(),n.fullscreen(!1),process.stdout.write(`${Ba}${Zc}
242
+ `),process.once("SIGCONT",K),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(yn,3e3)})}function wE(n,e){let t="Create new session in ",s=Math.max(1,e-t.length);return t+_a(ct(n),s)}function Tl(n,e){let t=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=t(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...n].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=t(i)-t(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function bE(n,e){return n?e.has(n):!0}function vE(n,e,t=gu()){return e==="__all"?n:e==="__local"?n.filter(s=>bE(s.importedFromMachine,t)||!!s.upstreamSessionId):n.filter(s=>s.importedFromMachine===e&&!t.has(e)&&!s.upstreamSessionId)}function wv(n,e,t=gu()){let s=new Set;for(let o of e)o.importedFromMachine&&!o.upstreamSessionId&&!t.has(o.importedFromMachine)&&s.add(o.importedFromMachine);let r=["__local",...[...s].sort(),"__all"],i=r.indexOf(n);return i===-1?"__local":r[(i+1)%r.length]??"__local"}function SE(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),s=[pt(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,ct(n.cwd)];for(let r of s)if(r.toLowerCase().includes(t))return!0;return!1}var Mp,ed,mE,yv,gE,yE,bv=Y(()=>{"use strict";Nc();Od();be();os();Ge();Ma();sp();Vd();hl();cp();Ap();Cp();Tp();Rp();Ep();ri();lp();up();Da();zr();Ff();Hr();Pp();Mp=2,ed=4,mE=4,yv=4,gE=20,yE=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import kE from"wrap-ansi";async function vv(n,e,t,s){Hn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=t.split(`
243
+ `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(n),l=Ls(n),u=Math.min(IE,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(A=>kE(A,f,{hard:!0,trim:!1}).split(`
244
+ `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,w=y.length+(m?1:0)+4,b=Un(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),S=b.contentW,k=0;n.moveTo(b.contentX,b.contentY+k),n.brightWhite.bold.noFormat(Xe(` ${i}`,S)),k+=2;for(let A of y)n.moveTo(b.contentX,b.contentY+k),n.brightRed.noFormat(Xe(` ${A}`,S)),k++;return m&&(n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(Xe(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(Xe(` ${a}`,S)),b};return hs({term:n,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 IE,Sv=Y(()=>{"use strict";ri();IE=100});import{spawn as xE}from"child_process";function AE(n,e){let t="";for(let s=0;s<n.length;s++){let r=n[s];if(r!=="%"||s===n.length-1){t+=r;continue}switch(n[s+1]){case"%":t+="%",s++;break;case"s":t+=e.sessionId,s++;break;case"c":t+=e.cwd,s++;break;case"a":t+=e.agentId,s++;break;case"u":t+=e.baseUrl,s++;break;case"t":t+=e.tokenFile,s++;break;default:t+=r;break}}return t}function CE(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function RE(n,e){let t=CE(n.command);if(t.length===0)return null;let s=t.map(a=>tt(AE(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function TE(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(s,r)=>{if(e.truncated)return;let i=n-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>t(s,"stdout"),onStderr:s=>t(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function kv(n,e,t){let s=RE(n,e);if(s===null){t.notify("hotkey: empty command");return}let r=TE(t.maxOutputBytes??EE),i=t.spawnFn??xE,o;try{o=i(s.program,s.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{t.emitLines(r.onExit(a,c))})}var EE,Iv=Y(()=>{"use strict";Ge();EE=16*1024});import{spawn as PE,spawnSync as ME}from"child_process";import*as Hs from"fs";import*as El from"path";function xv(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${_E}1337;SetUserVar=${n}=${t}${$E}`)}function Av(n){if(process.env.TMUX_PANE)try{let e=PE("tmux",n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function FE(){if(!process.stdin.isTTY)return null;let n=t=>{try{let s=Hs.readlinkSync(t);return s.startsWith("/dev/")&&s!=="/dev/tty"?El.basename(s):null}catch{return null}},e=n("/proc/self/fd/0")??n("/dev/fd/0");if(e)return e;try{let t=ME("tty",[],{encoding:"utf8",timeout:500});if(t.status!==0)return null;let s=t.stdout.trim();return!s.startsWith("/dev/")||s==="/dev/tty"?null:El.basename(s)}catch{return null}}function Cv(){return Fp===void 0&&(Fp=FE()),Fp}function OE(n){let e=Cv();if(e)try{Hs.mkdirSync(O.ttySessionDir(),{recursive:!0});let t=`${process.pid}:${process.ppid}:${n}
245
+ `;Hs.writeFileSync(O.ttySessionFile(e),t,{mode:384})}catch{}}function LE(n){let e=n.trim();if(e.length===0)return null;if(!e.includes(":"))return{hydraPid:0,parentPid:0,sessionId:e};let t=e.split(":");if(t.length<3)return null;let s=Number.parseInt(t[0],10),r=Number.parseInt(t[1],10),i=t.slice(2).join(":");return!Number.isFinite(s)||!Number.isFinite(r)||i.length===0?null:{hydraPid:s,parentPid:r,sessionId:i}}function BE(){let n=Cv();if(!n)return null;try{let e=Hs.readFileSync(O.ttySessionFile(n),"utf8");return LE(e)}catch{return null}}function NE(){let n=BE();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function Op(n){xv("hydra_session",n),Av(["set-option","-pt",process.env.TMUX_PANE??"","@hydra_session",n]),OE(n)}function Rv(){xv("hydra_session",""),Av(["set-option","-put",process.env.TMUX_PANE??"","@hydra_session"])}function Tv(){return NE()}var _E,$E,Fp,Ev=Y(()=>{"use strict";be();_E="\x1B]",$E="\x07"});function Pv(n){let e={};if(!n||typeof n!="object")return e;let t=n;typeof t.historyPolicy=="string"&&(e.appliedPolicy=t.historyPolicy),typeof t.clientId=="string"&&t.clientId.length>0&&(e.clientId=t.clientId);let s=t._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 Mv(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function _v(n){return n.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:n.pendingTurns===0?1:0,banner:"busy",busySince:n.daemonTurnStartedAt}:{pendingTurnsDelta:n.pendingTurns>0?-n.pendingTurns:0,banner:"ready"}}var $v=Y(()=>{"use strict"});import{readFileSync as DE}from"fs";import{performance as HE}from"perf_hooks";import{writeHeapSnapshot as UE}from"v8";import{nanoid as Fv}from"nanoid";import jE from"terminal-kit";import Lp from"fs/promises";import ci from"path";function qE(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function WE(n){let e=Pl(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function zE(n){let e=new Map,t=[];for(let s of n){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),t.push(r))}return t.map(s=>e.get(s))}function Pl(n){if(n.options&&n.options.length>0){let e=n.options.filter(t=>t!==n.defaultAnswer);return n.options.includes(n.defaultAnswer)?[n.defaultAnswer,...e]:[n.defaultAnswer,...n.options]}return[n.defaultAnswer]}function KE(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function JE(n,e,t,s,r=60){let i=n.map((o,a)=>{let c=Pl(o.representative),d=e[a]??0,l=t[a]?Np:c[d]??c[0]??"";return{label:KE(o.representative.question,r),value:l}});return{title:`Open questions (${n.length})`,options:i,selectedIndex:Math.max(0,Math.min(n.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 YE(n,e,t){return n===Np?{type:"dismiss",method:Tb,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:Rb,params:{sessionId:t,questionId:e.id,answer:n}}}function VE(n,e,t,s,r){let i=[];for(let o=0;o<n.length;o++){let a=n[o];if(!a||!t[o])continue;let c=s[o]?Np:Pl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=YE(c,l,r);u!==null&&i.push(u)}}return i}function QE(n,e,t,s,r,i,o,a){if(!e||t===null||t.length===0)return{type:"noop"};if(n.type==="char"){if(n.ch==="d"||n.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(n.ch)){let d=parseInt(n.ch,10)-1;if(d<t.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(n.type!=="key")return{type:"noop"};let c=d=>{let l=t[o];if(!l)return{type:"noop"};let u=Pl(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(n.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(t.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:VE(t,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Ov(n){if(!Array.isArray(n))return;let e=cs({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function Bp(n){switch(n.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function ZE(n,e){e.has(n)?e.delete(n):e.add(n)}function eP(){if(Lv)return;Lv=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{ie({src:"uncaughtException",stack:n(e)}),wr(),process.stderr.write(`
246
246
  uncaught: ${n(e)}
247
247
  `),process.exit(1)}),process.on("unhandledRejection",e=>{ie({src:"unhandledRejection",stack:n(e)}),wr(),process.stderr.write(`
248
248
  unhandled rejection: ${n(e)}
249
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&ie({src:"process-exit",code:e})}),process.platform!=="win32"&&process.env.HYDRA_HEAP_SNAPSHOT==="1"&&process.on("SIGUSR2",()=>{try{let e=`/tmp/hydra-heap-${process.pid}-${Date.now()}.heapsnapshot`,t=NE(e),s=process.memoryUsage();ie({src:"heap-snapshot",path:t,rss:s.rss,heapUsed:s.heapUsed,heapTotal:s.heapTotal,external:s.external}),process.stderr.write(`
249
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&ie({src:"process-exit",code:e})}),process.platform!=="win32"&&process.env.HYDRA_HEAP_SNAPSHOT==="1"&&process.on("SIGUSR2",()=>{try{let e=`/tmp/hydra-heap-${process.pid}-${Date.now()}.heapsnapshot`,t=UE(e),s=process.memoryUsage();ie({src:"heap-snapshot",path:t,rss:s.rss,heapUsed:s.heapUsed,heapTotal:s.heapTotal,external:s.external}),process.stderr.write(`
250
250
  [heap] ${t} rss=${s.rss} heapUsed=${s.heapUsed}
251
- `)}catch(e){ie({src:"heap-snapshot-failed",err:e instanceof Error?e.message:String(e)})}})}async function Nv(n){GE(),BE.setResourceTimingBufferSize(0);let e=await Ie(),t=n.target??await Bt(e);if(Ih(e.tui.logMaxBytes),t.isLocal&&!n.target&&await cr(e),n.agentId)try{let p=await Qr(t),h=Oa(n.agentId,p.map(m=>m.id));h!==void 0&&h!==n.agentId&&(n.agentId=h)}catch{}let s=DE.terminal;ov(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Xp(e),defaultEnterAction:e.tui.defaultEnterAction,...n.agentId?{lastChosenAgent:n.agentId}:{}},o=_p(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(wr(),s.fullscreen(!1),a=!1,process.stdout.write(`
252
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=n;try{for(;u!==null;)u=await ZE(s,e,t,u,r,i,o)}finally{Cv(),d(),process.off("exit",l)}let f=await ja();if(f&&process.stderr.write(`\u2728 ${qa(f)}
251
+ `)}catch(e){ie({src:"heap-snapshot-failed",err:e instanceof Error?e.message:String(e)})}})}async function Dv(n){eP(),HE.setResourceTimingBufferSize(0);let e=await Ie(),t=n.target??await Bt(e);if(Ih(e.tui.logMaxBytes),t.isLocal&&!n.target&&await cr(e,t),n.agentId)try{let p=await Qr(t),h=Oa(n.agentId,p.map(m=>m.id));h!==void 0&&h!==n.agentId&&(n.agentId=h)}catch{}let s=jE.terminal;av(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Xp(e),defaultEnterAction:e.tui.defaultEnterAction,...n.agentId?{lastChosenAgent:n.agentId}:{}},o=_p(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(wr(),s.fullscreen(!1),a=!1,process.stdout.write(`
252
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=n;try{for(;u!==null;)u=await nP(s,e,t,u,r,i,o)}finally{Rv(),d(),process.off("exit",l)}let f=await ja();if(f&&process.stderr.write(`\u2728 ${qa(f)}
253
253
  `),process.stdout.isTTY){let p=await Jr(e);if(p?.version!==void 0){let h=p.version!==ve,m=ir(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let w=h?`daemon ${p.version} \u2260 cli ${ve}`:"config changed since daemon started",b=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(b(`! ${w} \u2014 run \`${ns()} daemon restart\` to apply.`)+`
254
254
  `)}}}if(r.sessionId&&process.stdout.isTTY){let p=pt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${ns()} --session ${p}${h}
255
- `)}}function XE(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,c=e.length,d=a>0,l;if(!d||n.expanded)l=e;else{let _=Math.max(0,c-a),F=e.slice(_),B=[];for(let N=0;N<_;N++){let j=e[N];if(j===void 0)continue;let G=t.get(j);G&&!Tf(G.status)&&B.push(j)}l=[...B,...F]}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",w=y?`amended \xB7 ${fs(h)}`:`stopped (${m}) \xB7 ${fs(h)}`,b;if(c===0)m!==null?b=w:b=f?`thinking \xB7 ${fs(h)}`:`thought \xB7 ${fs(h)}`;else{let _=c===1?"tool":"tools",F=m!==null?w:f?fs(h):`took ${fs(h)}`,B=[`${c} ${_}`,F];f&&d&&u>0&&B.push(`${u} hidden`),b=B.join(" \xB7 ")}let S=c===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],H=[null];for(let _ of l){let F=t.get(_);if(F){let B=Fa(F,p);for(let N of B)N.hoverSubKey=_;if(P.push(...B),H.push(...B.map(()=>_)),o?.has(_)){let N=nw(F);for(let j of N)j.hoverSubKey=_;P.push(...N),H.push(...N.map(()=>_))}}}return{lines:P,rowOwners:H}}async function ZE(n,e,t,s,r,i,o){let a=await eP(n,e,t,s,o,i);if(!a)return n.grabInput(!1),ie({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.resolved?.status==="warm"&&t.isLocal,d=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":a.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",l=s.installStatus;s.installStatus&&delete s.installStatus;let u=a.installStatus??l??Rl(c?"":d,mv(n));c||u.write(d);let f=t.isLocal?async()=>(await Bt(await Ie())).wsUrl:t.wsUrl,p=["acp.v1",`hydra-acp-token.${t.token}`],h=null,m=null,y=new xo({url:f,subprotocols:p,onConnect:async g=>{g||h&&await h()},onDisconnect:g=>{m&&m(g)},log:g=>ie({src:"resilient-ws",line:g})}),w=new zt(y);await y.start(),w.onNotification(_d,g=>{let v=im.safeParse(g);v.success&&u.applyProgress(v.data)});let b=[],S=null,k=!1,A=!1,E=(g,v)=>{g&&(S?S(g,v):b.push({event:g,rawUpdate:v}))},P,H=g=>{g!==P&&(P=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},_=null,F=null,B=!1,N=0,j=0,G=!1,X=!1,V,ye=null,Be=null,mt=null,_e=null,gs=()=>setInterval(()=>{if(ye===null||ce===null)return;let g=_e===null?0:Date.now()-_e;ce.setBanner({elapsedMs:Date.now()-ye,stalled:g>=YE}),it()},1e3),Ee=!1,ee=g=>{let v=j;j=Math.max(0,j+g);let x=typeof ce<"u"&&ce!==null;v===0&&j>0?(X=!1,ye=Date.now(),_e=Date.now(),$e?.setTurnRunning(!0),x&&ce.setBanner({status:"busy",elapsedMs:0,stalled:!1}),Be===null&&x&&(Be=gs())):v>0&&j===0?(X=!1,ye=null,_e=null,$e?.setTurnRunning(!1),Be!==null&&(clearInterval(Be),Be=null),x&&ce.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):j>0&&X&&(X=!1,x&&ce.setBanner({status:"busy",stalled:!1}))},ce=null,$e=null,fn,pn=null,xn=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"]),Ht=g=>{let{update:v}=g??{},x=ds(v,{cwd:Ne});tP(v,x),_e=Date.now();let R=v?.sessionUpdate;if(typeof R=="string"&&!xn.has(R)){let C=v??{};typeof C.messageId=="string"&&(fn=C.messageId)}if(R==="prompt_received"?ee(1):x?.kind==="turn-complete"&&(ee(-1),B=!0),R==="permission_resolved"){Ut(v);return}if(R==="hydra_compaction"){An(v);return}if(R==="clarifier_question_asked"){let C=v,$=typeof C.question?.question=="string"?C.question.question:"",z=$.length>50?$.slice(0,49)+"\u2026":$;I.notify(z?`new question: ${z} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(E(x,v),id(v))};w.onNotification("session/update",g=>{if(!k){if(pn!==null){pn.push(g);return}Ht(g)}}),w.onNotification("hydra-acp/session/closed",()=>{if(k)return;j>0&&ee(-j),typeof ce<"u"&&ce!==null&&ce.setBanner({status:"cold",elapsedMs:void 0})});let Yt=new Map,vr=200,li=0,Wn=!1,Po=4e3;w.onNotification("hydra-acp/prompt_queue/added",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let R=v.messageId,C=v.prompt,$=setTimeout(()=>{k||(Yt.delete(R),te.set(R,Q(R,C)),ce&&$e&&rt())},vr);Yt.set(R,$)}else te.set(v.messageId,Q(v.messageId,v.prompt)),ce&&$e&&rt();if(Cn!==void 0&&v.originator?.clientId===Cn){let R=oe.shift();R&&(R.messageId=v.messageId,me.set(v.messageId,R))}}),w.onNotification("hydra-acp/prompt_queue/updated",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string"||!te.has(v.messageId))return;te.set(v.messageId,Q(v.messageId,v.prompt));let x=me.get(v.messageId);if(x){let R=Array.isArray(v.prompt)?v.prompt:[],C="",$=[];for(let z of R){if(!z||typeof z!="object")continue;let D=z;D.type==="text"&&typeof D.text=="string"?C+=D.text:D.type==="image"&&typeof D.data=="string"&&typeof D.mimeType=="string"&&$.push({data:D.data,mimeType:D.mimeType,sizeBytes:Math.floor(D.data.length*3/4)})}x.text=C,x.attachments=$}ce&&$e&&rt()}),w.onNotification("hydra-acp/prompt_queue/removed",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(V=v.messageId);let x=Yt.get(v.messageId);x!==void 0&&(clearTimeout(x),Yt.delete(v.messageId)),te.delete(v.messageId)&&ce&&$e&&rt();let C=me.get(v.messageId);C&&(me.delete(v.messageId),v.reason==="started"&&(C.flushed=!0,E({kind:"user-text",text:C.displayText,attachments:C.attachments}),Je=C))}),w.onNotification("hydra-acp/cancel_failed",g=>{if(k)return;let v=g??{};if(!(typeof ce<"u"&&ce!==null))return;li=Date.now(),Wn=!0;let R=typeof v.code=="number"?` (${v.code})`:"",C=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";ce.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${R}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),w.onNotification("hydra-acp/prompt/amended",g=>{if(k)return;let v=g??{};if(typeof v.cancelledMessageId!="string")return;let x=v.cancelledMessageId;He.add(x),Je!==null&&Je.messageId!==void 0&&Je.messageId===x&&(E({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Je=null,He.delete(x))});let An=g=>{let v=g??{},x=typeof v.phase=="string"?v.phase:void 0;if(x==="started")I.setCompactionIndicator("compacting...");else if(x==="iteration")I.setCompactionIndicator("compacting...");else if(x==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(x==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(x==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(x==="failed"){I.setCompactionIndicator(null);let R=typeof v.error=="string"?v.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;I.notify(`compaction failed: ${C}`,5e3)}},rd=()=>{mt===null&&(mt=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),mt!==null&&(clearInterval(mt),mt=null)):v.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),mt!==null&&(clearInterval(mt),mt=null))}catch{}},5e3))},Mo=()=>{mt!==null&&(clearInterval(mt),mt=null)},Ut=g=>{let v=g??{},x=typeof v.toolCallId=="string"?v.toolCallId:void 0,R;v.outcome&&typeof v.outcome=="object"?R=v.outcome:typeof v.chosenOptionId=="string"&&(R={kind:"selected",optionId:v.chosenOptionId}),_o(x,R?{outcome:R}:void 0)},Ce=null,_o=(g,v)=>{if(!Ce||Ce.toolCallId&&g&&Ce.toolCallId!==g)return;let x=Ce.resolve;Ce=null,I.setPermissionPrompt(null),x(v??{outcome:{outcome:"cancelled"}})},id=g=>{if(!Ce?.toolCallId)return;let v=g??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Ce.toolCallId&&(!v.status||v.status==="pending"||_o(v.toolCallId,void 0))},ui=()=>{if(!Ce){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:Ce.title,detail:Ce.detail,options:Ce.options.map(g=>({label:g.name})),selectedIndex:Ce.selectedIndex})},$o=g=>{if(!Ce)return;let{options:v,resolve:x}=Ce;if(Ce=null,I.setPermissionPrompt(null),g===null){x({outcome:{outcome:"cancelled"}});return}x({outcome:{outcome:"selected",optionId:g}})};w.onRequest("session/request_permission",async g=>{if(k)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ii(g);let v=g??{},R=(Array.isArray(v.options)?v.options:[]).map(Z=>({optionId:Z.optionId,name:Te(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=v.toolCall?.title??v.toolCall?.name??"tool",$=Te(C),z=Te(nb(tb(g))),D=v.toolCall?.toolCallId;return R.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${$} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{Ce={title:$,detail:z,options:R,selectedIndex:0,resolve:Z,toolCallId:D},ui()})}),w.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let At,ys,hn=!0,ws=!1;try{let g=await w.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ve}});ys=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(hn=!1),ws=an(g?._meta??void 0).prompt?.amending===!0}catch{}let le=a.sessionId,at=a.agentId,Ne=a.cwd,fi,Cn,Us,Sr,js,bs,Vt,qs,pi,zn,Fo=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let v={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Mt]:g}}:{}},x;try{x=await Kw({request:()=>w.request("session/new",v),showBanner:($,z,D)=>Jw(n,$,z,D,{authenticate:Z=>w.request("authenticate",{methodId:Z})}),resolveOnboarding:async $=>{if($)try{return(await Qr(t)).find(Z=>Z.id===$)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch($){n.grabInput(!1),ie({src:"grab",site:"runSession.session-new-failed",on:!1}),y.close().catch(()=>{});let z=$ instanceof Error?$.message:String($);ie({src:"session-new-failed",agentId:s.agentId??null,message:z});let D=await bv(n,s.agentId,z,{canGoBack:!s.forceNew});if(D==="cancel")return null;let Z={...s};return delete Z.sessionId,delete Z.resume,D==="retry"?Z.forceNew=!0:(delete Z.forceNew,delete Z.agentId),Z}if(x.kind==="cancel")return n.grabInput(!1),ie({src:"grab",site:"runSession.auth-cancel",on:!1}),y.close().catch(()=>{}),null;if(x.kind==="back"){n.grabInput(!1),ie({src:"grab",site:"runSession.auth-back",on:!1}),y.close().catch(()=>{});let $={...s};return delete $.sessionId,delete $.forceNew,delete $.resume,delete $.agentId,$}let R=x.result;u.write(d),le=R.sessionId,Op(le),r.sessionId=le,r.readonly=!1;let C=an(R._meta??void 0);C.clientId&&(Cn=C.clientId),At=C.upstreamSessionId,C.agentId&&(at=C.agentId),C.cwd&&(Ne=C.cwd),C.title&&(fi=C.title),Us=C.currentModel,Sr=C.currentMode,pi=C.currentUsage,zn=C.turnStartedAt,C.availableCommands&&(js=fc(C.availableCommands)),C.availableModes&&(bs=C.availableModes),Vt=Fv(R.configOptions),qs=C.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let v=await w.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:ve},...Object.keys(g).length>0?{_meta:{[Mt]:g}}:{}});le=v.sessionId,Op(le),v.clientId&&(Cn=v.clientId),r.sessionId=le,r.readonly=s.readonly===!0;let x=an(v._meta??void 0);Fo=x.resurrected===!0,At=x.upstreamSessionId,x.agentId&&(at=x.agentId),x.cwd&&(Ne=x.cwd),x.title&&(fi=x.title),Us=x.currentModel,Sr=x.currentMode,pi=x.currentUsage,zn=x.turnStartedAt,x.availableCommands&&(js=fc(x.availableCommands)),x.availableModes&&(bs=x.availableModes),Vt=Fv(v.configOptions),qs=x.queue}let vs=O.tuiHistoryFile(le),kr=O.globalTuiHistoryFile(),jt=await ma(vs).catch(()=>[]),Qt=await ma(kr).catch(()=>[]);Qt.length>e.tui.promptHistoryMaxEntries&&(Qt=Qt.slice(Qt.length-e.tui.promptHistoryMaxEntries));let mn=[...jt],De=new Bs({history:Yd(Qt,mn)});$e=De;let We=!1,Kn=(g,v)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let R=(v??g).replace(/\n+$/,""),C=ga(jt,x),$=C!==jt;jt=C,mn=ga(mn,R);let z=ga(Qt,x,e.tui.promptHistoryMaxEntries),D=z!==Qt;Qt=z,De.setHistory(Yd(Qt,mn)),$&&Wr(vs,jt).catch(()=>{}),D&&rg(kr,x).catch(()=>{})};j>0&&De.setTurnRunning(!0);let Ct=null,Gt=null;sv(rv(e.tui.ambiguousWidth,process.env)),rw(e.tui.diffContextLines);let hi=!1,I,Xt=()=>{hi&&(hi=!1,I.start())},Oo=()=>{hi||(hi=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Xt);let Ir=null,mi=null;I=new vl({term:n,dispatcher:De,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"?Oo:void 0,onBlockClick:(g,v)=>{sS(g,v)},onBlockDoubleClick:(g,v)=>nS(g,v),onHydraLinkClick:g=>(Ko(g),!0),onBlockVisible:g=>{Zv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let v=Xn.get(g);if(v!==void 0&&v.length>0)return new Set(v);let x=I.contiguousRun(g,new Set(Qs.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Ir=I.bannerHitAt(g.x,g.y),mi=Ir?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=mi,R=Ir;if(mi=null,Ir=null,R!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Cs(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Bp(C))return;xs(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let v={type:"attachment-request",source:"primary"};s.readonly===!0&&Bp(v)||xs(v)},onKey:g=>{for(let v of g){if(G&&ud(v)){v.type==="key"&&ie({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Ce&&Ar(v)){v.type==="key"&&ie({src:"key-swallowed",site:"permission",name:v.name});continue}if(fd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"help",name:v.name});continue}if(bi(v)){v.type==="key"&&ie({src:"key-swallowed",site:"questions",name:v.name});continue}if(Gn(v)){v.type==="key"&&ie({src:"key-swallowed",site:"options",name:v.name});continue}if(cd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(vt(v)){v.type==="key"&&ie({src:"key-swallowed",site:"completion",name:v.name});continue}if(dd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(v.type==="attachment-paths"){T(v.paths);continue}if(v.type==="key"&&No(v.name)){ie({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let x=De.feed(v);for(let R of x)s.readonly===!0&&Bp(R)||xs(R)}ad(),I.setBannerSearchIndicator(De.state().historySearchQuery),I.setAttachments(De.state().attachments),I.refreshPrompt()}}),ce=I,I.setStickyBottomKey("plan");let Lo=[{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]"}],Ws=js??[],Ss=bs??[],xr=Vt??[],Ze=()=>xr.find(g=>g.id==="agent"),od=()=>{let g=new Set,v=[];for(let x of[...Lo,...Ws])g.has(x.name)||(g.add(x.name),v.push(x));return v},Bo=()=>{let g=De.state().buffer,v=g[0]??"";if(!v.startsWith("/"))return[];if(g.length>1)return[];let x=v.indexOf(" "),R=x===-1?v:v.slice(0,x);if(R.lastIndexOf("/")>0)return[];let C=od().filter($=>$.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},bt=[],ad=()=>{let g=Bo();if(g.length>0){bt=[],I.setCompletions(g);return}I.setCompletions(bt)},vt=g=>{if(g.type!=="key"||g.name!=="tab")return bt.length>0&&(bt=[]),!1;let v=Bo();if(I.isOverlayOpen()&&v.length===0)return I.toggleFocusedPane(),!0;if(v.length>0){bt=[];let x=De.state().buffer[0]??"",R=lv({matches:v.map(C=>C.name),firstLine:x});return R===null||De.replaceFirstLine(R),!0}return ks()},ks=()=>{let g=De.state(),v=g.buffer[g.row]??"",x=Al(v,g.col);if(x===null)return!1;let R=Cl(x.token,Ne);return R===null?!1:(R.replacement!==x.token&&De.replaceRangeOnCurrentLine(x.start,g.col,R.replacement),bt=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},dd=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay(),!0),cd=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 v=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(v),!0}if(g.type==="paste"){let v=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(v),!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 v=I.scrollbackSearchTerm();return v.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Ar=g=>{if(!Ce)return!1;let v=Ce.options;if(g.type==="key")switch(g.name){case"up":return Ce.selectedIndex=Math.max(0,Ce.selectedIndex-1),ui(),!0;case"down":return Ce.selectedIndex=Math.min(v.length-1,Ce.selectedIndex+1),ui(),!0;case"enter":{let x=v[Ce.selectedIndex];return x&&$o(x.optionId),!0}case"escape":case"ctrl-c":return $o(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,R=v[x];return R&&$o(R.optionId),!0}return!0},No=g=>{let v=e.tui.hotkeys[g];return v?(Sv(v,{sessionId:le,cwd:Ne,agentId:at||ys||"",baseUrl:t.baseUrl,tokenFile:O.authToken()},{notify:x=>I.notify(x),cwd:Ne,emitLines:x=>{I.appendLines(x.map(R=>{let C;switch(R.style){case"meta":C="dim";break;case"stderr":case"error":C="tool-status-fail";break;default:C="info"}return{prefix:" ",body:R.text,bodyStyle:C}}))}}),!0):!1},ld=at||ys||"?",Tt={...pi??{}};u.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:ld,cwd:Ne,sessionId:le,title:fi,model:Us,usage:{...Tt}}),Sr&&I.setBanner({currentMode:Sr}),ja().then(g=>{g&&I.notify(`\u2728 ${qa(g)}`,3e4)}).catch(()=>{});let ft=null,Do=new Promise(g=>{ft=g}),Ho=()=>{w.notify("session/cancel",{sessionId:le}).catch(()=>{})},Uo=()=>{ce!==null&&j===1&&(X=!0,ce.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},jo=()=>{if(Ct){Ct.cancel(),Uo();return}if(j>0){Ho(),Uo();return}Cr()},Cr=()=>{Ks(0)},qo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",v]],...VE]},gi=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:qo(),hint:"any key dismisses \xB7 /help lists commands"})},Jn=()=>{G=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=le;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Yn=()=>{G=!1,I.setCompactionPrompt(null)},Rr=g=>{let v=I.compactionPromptSpec();if(!v)return;let x=v.options.length;if(x===0)return;let R=((v.selectedIndex+g)%x+x)%x;R!==v.selectedIndex&&I.setCompactionPrompt({...v,selectedIndex:R})},ud=g=>{if(!G)return!1;if(g.type==="key"){if(g.name==="escape")return Yn(),!0;if(g.name==="up")return Rr(-1),!0;if(g.name==="down")return Rr(1),!0;if(g.name==="enter"){let v=I.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Jn():Yn(),!0}}if(g.type==="char"){let v=g.ch.toLowerCase();if(v==="y"||v==="1")return Jn(),!0;if(v==="n"||v==="2")return Yn(),!0}return!0},fd=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Tr=["tools","plan","thoughts","diffs","mouse","enter"],Rn=0,Zt=null,en=[],Vn=[],Tn=[],Qn=0,Wo=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}},pd=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"}},gn=()=>({title:"Session options",options:Tr.map(g=>({label:pd(g),value:Wo(g)})),selectedIndex:Rn}),zo=()=>{I.isOptionsPromptActive()&&Zt===null&&I.setOptionsPrompt(gn())},Is=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Rn=0,I.setOptionsPrompt(gn())},En=()=>{if(Zt===null)return;let g=WE(Zt,en,Tn,Qn);I.setOptionsPrompt(g)},yi=()=>{Zt=null,en=[],Vn=[],Tn=[],Qn=0,I.setOptionsPrompt(null)},$l=async()=>{if(Zt!==null){yi();return}try{let v=await w.request(Ab,{sessionId:le}),x=HE(v.questions??[]);if(x.length===0){I.notify("no open questions");return}let R=jE(x);Zt=R,Qn=0,en=R.map(C=>UE(C.representative)),Vn=R.map(()=>!1),Tn=R.map(()=>!1),En()}catch(g){I.notify("clarifier unavailable"),ie({src:"questions",step:"list_failed",error:g.message})}},zs=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Pr.clear(),vi.clear(),_r();break;case"plan":i.planExpanded=!i.planExpanded,Gs=null,Si();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Rs.clear(),eS();break;case"mouse":{let v=!I.isMouseEnabled();I.setMouseEnabled(v),i.mouseEnabled=v;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}zo()},wi=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${pd(g)} is session-only \u2014 not saved`);return;case"thoughts":await ea("showThoughts",i.showThoughts);break;case"diffs":await ea("showFileUpdates",i.showFileUpdates);break;case"mouse":await ea("mouse",i.mouseEnabled);break;case"enter":await ea("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${pd(g)} ${Wo(g)}`)}catch(v){I.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},Gn=g=>{if(Zt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Rn=Math.max(0,Rn-1),zo(),!0;case"down":return Rn=Math.min(Tr.length-1,Rn+1),zo(),!0;case"enter":{let v=Tr[Rn];return v&&zs(v),!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 v=parseInt(g.ch,10)-1,x=Tr[v];return x&&(Rn=v,zs(x)),!0}if(g.ch==="s"||g.ch==="S"){let v=Tr[Rn];return v&&wi(v),!0}}return!0},bi=g=>{if(Zt===null)return!1;let v=JE(g,!0,Zt,en,Vn,Tn,Qn,le);switch(v.type){case"noop":return!0;case"row":return Qn=v.selectedRow,En(),!0;case"cycle":return en[v.selectedRow]=v.newValueIndex,Vn[v.selectedRow]=!0,Tn[v.selectedRow]=!1,En(),!0;case"dismiss-toggle":{let x=v.selectedRow;return Tn[x]?(Tn[x]=!1,Vn[x]=!1):(Tn[x]=!0,Vn[x]=!0),En(),!0}case"discard":return yi(),!0;case"save":{let x=v.dispatches;return yi(),x.length===0||(async()=>{let R=0,C=0,$=0;for(let D of x)try{await w.request(D.method,D.params),D.type==="dismiss"?C++:R++}catch(Z){$++,ie({src:"questions",step:"dispatch_failed",method:D.method,error:Z.message})}let z=[];R>0&&z.push(`${R} answered`),C>0&&z.push(`${C} dismissed`),$>0&&z.push(`${$} failed`),z.length>0&&I.notify(`clarifier: ${z.join(", ")}`)})(),!0}}return!1},qt=()=>{if(!k){k=!0,_?(_.cancel(),_=null,F=null):F!==null&&(us(t,F).catch(()=>{}),F=null),process.off("SIGINT",jo),process.platform!=="win32"&&process.off("SIGCONT",Xt),Be!==null&&(clearInterval(Be),Be=null),mt!==null&&(clearInterval(mt),mt=null);for(let g of Yt.values())clearTimeout(g);Yt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Wr(vs,jt).catch(()=>{}),y.close().catch(()=>{})}},Ks=(g=0)=>{qt(),ft&&(ft(null),ft=null),g!==0&&process.exit(g)},Ft=async()=>{if(ie({src:"switch-session",step:"entered",finishSessionNull:ft===null}),!ft)return;_?(_.cancel(),_=null,F=null):F!==null&&(us(t,F).catch(()=>{}),F=null),Mo(),I.setSynthesisIndicator(null);let g=De.state().buffer.join(`
256
- `);g.replace(/\s+$/,"").length>0&&Kn(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Wr(vs,jt).catch(()=>{});let v=!1;try{let x=null,R=null;for(;x===null;){let D=await Dn(t,{includeNonInteractive:!0}),Z=s.agentId??i.lastChosenAgent??e.defaultAgent,Re=Z?e.defaultModels?.[Z]:void 0,Se=[];try{Se=await Qr(t)}catch{}let ae=await $p(n,{cwd:Ne,sessions:D,config:e,target:t,currentSessionId:le,prefs:o,...Z?{composerAgentId:Z}:{},...Re?{composerModel:Re}:{},...Se.length>0?{availableAgents:Se}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){v=!0,Ks(0);return}if(ae.kind==="new"){x={choice:ae,sessions:D};break}if(ae.kind==="fork"){let $n=await Uv(n,t,ae,D);if($n.kind==="cancel")return;if($n.kind==="back")continue;x={choice:{kind:"attach",sessionId:$n.ctx.sessionId,...$n.ctx.agentId?{agentId:$n.ctx.agentId}:{}},sessions:D},R={readonly:!1,cwd:$n.ctx.cwd},$n.ctx.resumeHint!==void 0&&(R.resumeHint=$n.ctx.resumeHint);break}let we=D.find($n=>$n.sessionId===ae.sessionId);if(!(we!==void 0&&!!we.importedFromMachine&&!we.upstreamSessionId&&ae.readonly!==!0)){if(t.isLocal&&we&&!we.importedFromMachine&&ae.readonly!==!0&&!(await za(we.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let Xo=await di(n,we,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Xo.kind==="cancel")return;if(Xo.kind==="back")continue;x={choice:ae,sessions:D},R={readonly:!1,cwd:Xo.path,resumeHint:{agentId:ae.agentId??we.agentId??"",cwd:Xo.path,upstreamSessionId:""}};break}x={choice:ae,sessions:D};break}let ts={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let Go=await Dv(n,t,we,ae,ts);if(Go.kind==="cancel")return;Go.kind!=="back"&&(x={choice:ae,sessions:D},R={readonly:ts.readonly===!0,cwd:Go.ctx.cwd},Go.ctx.resumeHint!==void 0&&(R.resumeHint=Go.ctx.resumeHint))}let{choice:C}=x,$=ft;if(ft=null,qt(),v=!0,C.kind==="new"){let{sessionId:D,agentId:Z,...Re}=s,Se={...Re,cwd:C.cwd??Ne,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Se.initialPrompt=C.prompt),C.attachments&&C.attachments.length>0&&(Se.initialAttachments=C.attachments),C.agentId!==void 0&&(Se.agentId=C.agentId,i.lastChosenAgent=C.agentId),C.model!==void 0&&(Se.model=C.model),C.installStatus!==void 0&&(Se.installStatus=C.installStatus),$(Se);return}if(C.kind!=="attach")return;let z={...s,sessionId:C.sessionId,cwd:R?.cwd??Ne,readonly:R?.readonly??C.readonly===!0};C.agentId!==void 0&&(z.agentId=C.agentId),R?.resumeHint!==void 0?z.resumeHint=R.resumeHint:delete z.resumeHint,C.installStatus!==void 0?z.installStatus=C.installStatus:delete z.installStatus,$(z)}finally{!v&&ft&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},Er=async(g="next")=>{if(!ft)return;let x=(await Dn(t)).filter(Se=>Se.status==="warm");if(x.length<=1)return;let R=x.findIndex(Se=>Se.sessionId===le),z=((R===-1?0:R)+(g==="prev"?-1:1)+x.length)%x.length,D=x[z],Z=ft;ft=null,qt();let Re={...s,sessionId:D.sessionId,cwd:Ne,readonly:!1,resolved:D};D.agentId!==void 0&&(Re.agentId=D.agentId),Z(Re)},Ko=async g=>{if(!ft)return;let v=await Dn(t,{includeNonInteractive:!0}),x=g.trim();if(!x){I.notify("usage: /session <id|next|prev>");return}let R=x.startsWith(Dt)?[x]:[x,Dt+x],C=v.find(D=>R.includes(D.sessionId));if(!C){let D=v.filter(Z=>R.some(Re=>Z.sessionId.startsWith(Re)));if(D.length===1)C=D[0];else if(D.length>1){I.notify(`ambiguous session id: ${x} (${D.length} matches)`);return}}if(!C){I.notify(`no session matches: ${x}`);return}if(C.sessionId===le){I.notify("already on that session");return}let $=ft;ft=null,qt();let z={...s,sessionId:C.sessionId,cwd:C.cwd??Ne,readonly:!1,resolved:C};C.agentId!==void 0&&(z.agentId=C.agentId),delete z.resumeHint,$(z)},xs=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ot(g.text,g.attachments,g.displayText):As(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?As(g.text,g.attachments,g.displayText):Ot(g.text,g.attachments,g.displayText);return;case"queue-edit":{let v=et(g.index);if(!v)return;let x=[];g.text.length>0&&x.push({type:"text",text:g.text});for(let R of g.attachments)x.push({type:"image",data:R.data,mimeType:R.mimeType});w.request("hydra-acp/prompt/update",{sessionId:le,messageId:v,prompt:x}).then(R=>{let C=R;!C.updated&&C.reason!=="ok"&&I.notify(`queue edit skipped (${C.reason})`)}).catch(R=>{I.notify(`queue edit failed: ${R.message}`)});return}case"queue-remove":{let v=et(g.index);if(!v)return;w.request("hydra-acp/prompt/cancel",{sessionId:le,messageId:v}).then(x=>{let R=x;!R.cancelled&&R.reason!=="ok"&&I.notify(`queue cancel skipped (${R.reason})`)}).catch(x=>{I.notify(`queue cancel failed: ${x.message}`)});return}case"cancel":{if(I.isOverlayOpen()){_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay();return}if(g.prefill&&Ct){let v=te.size===0,x=De.state().buffer.every(R=>R==="");v&&x&&(Gt={text:Ct.text,attachments:Ct.attachments})}Ct?Ct.cancel():j>0&&Ho(),Uo();return}case"exit":Cr();return;case"plan-toggle":Cs(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":Ft().catch(v=>{ie({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":Er("next").catch(()=>{});return;case"prev-live-session":Er("prev").catch(()=>{});return;case"toggle-options":Is();return;case"toggle-questions":$l();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 v=!I.isMouseEnabled();I.setMouseEnabled(v),i.mouseEnabled=v,I.notify(v?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":gi();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":M(g.source);return}},T=async g=>{if(!hn){I.notify("agent does not accept image attachments");return}let v=0;for(let x of g){if(x.startsWith("data:")){let C=rp(x);if(!C){I.notify("unsupported data: URI");continue}if(C.sizeBytes>hs){I.notify(`image too large (${In(C.sizeBytes)}, max ${In(hs)})`);continue}De.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),v++;continue}let R=Ja(x);if(!R){I.notify(`unsupported image type: ${ci.basename(x)}`);continue}try{let C=await Lp.readFile(x);if(C.length>hs){I.notify(`image too large (${In(C.length)}, max ${In(hs)})`);continue}De.addAttachment({mimeType:R,data:C.toString("base64"),name:ci.basename(x),sizeBytes:C.length}),v++}catch(C){I.notify(`cannot read ${ci.basename(x)}: ${C.message}`)}}v>0&&(I.setAttachments(De.state().attachments),I.refreshPrompt())},M=async(g="clipboard")=>{let v=g==="primary"?await Lb():await pl();if(!v.ok){I.notify(v.reason);return}if(v.kind==="image"){if(!hn){I.notify("agent does not accept image attachments");return}De.addAttachment(v.attachment),I.setAttachments(De.state().attachments),I.refreshPrompt();return}let x=De.feed({type:"paste",text:v.text});for(let R of x)xs(R);I.refreshPrompt()},U=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Q=(g,v)=>{let x=Array.isArray(v)?v:[],R="",C=0;for(let $ of x){if(!$||typeof $!="object")continue;let z=$;z.type==="text"&&typeof z.text=="string"?R+=z.text:z.type==="image"&&(C+=1)}return{messageId:g,text:Te(R),attachmentCount:C}},te=new Map,oe=[],me=new Map,He=new Set,Je=null,rt=()=>{let g=[...te.values()],v=g.map(U);I.setQueuedPrompts(v),I.setBanner({queued:g.length}),De.setQueue(g.map(x=>x.text))},et=g=>[...te.values()][g]?.messageId;if(qs&&qs.length>0){for(let g of qs){if(g.position===0){V=g.messageId;continue}te.set(g.messageId,Q(g.messageId,g.prompt))}te.size>0&&rt()}let As=(g,v,x)=>{I.scrollToBottom(),!Js(g)&&(Kn(g,x),Ys(g,v,x))},Ot=(g,v,x)=>{if(I.scrollToBottom(),Js(g))return;if(Kn(g,x),!ws||V===void 0){Ys(g,v,x);return}let R=V,C=[];g.length>0&&C.push({type:"text",text:g});for(let D of v)C.push({type:"image",data:D.data,mimeType:D.mimeType});let $={text:g,displayText:x??g,attachments:v,flushed:!1};oe.push($);let z=()=>{let D=oe.indexOf($);D>=0&&oe.splice(D,1),$.messageId!==void 0&&me.delete($.messageId)};w.request("hydra-acp/prompt/amend",{sessionId:le,targetMessageId:R,prompt:C}).then(D=>{let Z=D;if(Z.amended&&Z.reason==="ok"){ee(1);return}if(z(),Z.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),De.setBuffer(g,v),I.refreshPrompt();return}if(Z.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),De.setBuffer(g,v),I.refreshPrompt();return}if(Z.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),De.setBuffer(g,v),I.refreshPrompt();return}}).catch(D=>{z(),I.notify(`amend failed: ${D.message}`),De.setBuffer(g,v),I.refreshPrompt()})},Cs=async g=>{if(Ss.length===0){I.notify("no modes advertised by agent");return}let v=I.currentModeId(),x=Ss.findIndex($=>$.id===v),R=x===-1?0:(x+1)%Ss.length,C=Ss[R]?.id;if(C){I.setBanner({currentMode:C});try{await w.request("session/set_mode",{sessionId:le,modeId:C})}catch($){I.notify(`set_mode failed: ${$.message}`)}}},Js=g=>{let v=g.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
257
- `))return!1;let x=v.indexOf(" ");switch(x===-1?v:v.slice(0,x)){case"/quit":case"/exit":return Cr(),!0;case"/clear":return Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Pn=null,yn.clear(),Rs.clear(),Ts.clear(),Pr.clear(),Qs.clear(),Xn.clear(),I.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let $ of Lo)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"});if(Ws.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let $ of Ws)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"})}return I.appendLines(C),!0}case"/agent":{let C=x===-1?"":v.slice(x+1).trim(),$=Ze();if(!$)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let D=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let Z of $.options){let Re=Z.value===$.currentValue?"* ":" ";D.push({prefix:" ",body:`${Re}${Z.value.padEnd(16)} ${Z.name}`,bodyStyle:"info"})}return I.appendLines(D),!0}let z=$.options.find(D=>D.value===C)?.value;if(!z){let D=C.toLowerCase(),Z=$.options.filter(Re=>Re.value.toLowerCase().startsWith(D));Z.length===1&&(z=Z[0].value)}return z?z===$.currentValue?(I.notify(`already on agent ${z}`),!0):(I.notify(`switching to ${z}\u2026`),w.request("session/set_config_option",{sessionId:le,configId:"agent",value:z}).catch(D=>{I.notify(`set_config_option failed: ${D.message}`)}),!0):(I.notify(`unknown agent: ${C}`),!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 Ft().catch(C=>{ie({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=x===-1?"":v.slice(x+1).trim();return C?C==="next"||C==="prev"?(Er(C).catch($=>{I.notify(`session ${C} failed: ${$.message}`)}),!0):(Ko(C).catch($=>{I.notify(`session switch failed: ${$.message}`)}),!0):(Ft().catch($=>{ie({src:"switch-session-failed",stack:$ instanceof Error?$.stack??$.message:String($)})}),!0)}case"/rename":{let C=x===-1?"":v.slice(x+1).trim(),$=C.length>0?`/hydra title ${C}`:"/hydra title";return Kn(v,v),Ys($,[],v),!0}case"/btw":{let C=x===-1?"":v.slice(x+1).trim();if(!C)return I.isOverlayOpen()?(_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(le==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let $=N;_&&(_.cancel(),_=null);let z=null;F!==null&&!B?z=F:F!==null&&(us(t,F).catch(()=>{}),F=null),B=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let D=new ll({getMaxWidth:()=>{let ae=I.width();return ae>0?ae:void 0}});D.on("changed",()=>{I.setBtwOverlayContent(D.getLines())});let Z={};D.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let Re=ae=>{D.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},Se={};return z!==null&&(Se.reuseSessionId=z),Eb(t,le,C,Se).then(ae=>{if($!==N){ae.cancel();return}_=ae,F=ae.sessionId,I.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",we=>{if($===N)if(we.kind==="update"){D.append(we.update);let ot=ds(we.update);if(ot&&ot.kind==="usage-update"){let ts=!1;ot.used!==void 0&&Z.used!==ot.used&&(Z.used=ot.used,ts=!0),ot.size!==void 0&&Z.size!==ot.size&&(Z.size=ot.size,ts=!0),ot.costAmount!==void 0&&Z.costAmount!==ot.costAmount&&(Z.costAmount=ot.costAmount,ts=!0),ot.costCurrency!==void 0&&Z.costCurrency!==ot.costCurrency&&(Z.costCurrency=ot.costCurrency,ts=!0),ts&&I.setBtwOverlayMeta({usage:{...Z}})}}else we.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),_=null):we.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),_=null,F=null):we.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Re(`btw errored: ${we.error.message}`),F!==null&&us(t,F).catch(()=>{}),_=null,F=null)})}).catch(ae=>{if($!==N)return;let we=ae instanceof Error?ae.message:String(ae);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Re(`btw startup failed: ${we}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${we}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(le==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=x===-1?"":v.slice(x+1).trim(),$=le;return(async()=>{try{let z=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent($)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!z.ok){let we=await z.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${z.status} ${we}`.trim(),bodyStyle:"info"}]);return}let D=await z.text(),Z=new Date().toISOString().replace(/[:.]/g,"-"),Re=`hydra-${pt($)}-${Z}.md`,Se=C.length>0?tt(C):Re,ae=ci.resolve(Se);await Lp.mkdir(ci.dirname(ae),{recursive:!0}),await Lp.writeFile(ae,D,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(z){I.appendLines([{prefix:" ",body:`/export failed: ${z.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Ys=async(g,v,x)=>{let R=[];g.length>0&&R.push({type:"text",text:g});for(let Se of v)R.push({type:"image",data:Se.data,mimeType:Se.mimeType});ee(1);let C={text:g,displayText:x??g,attachments:v,flushed:!1};oe.push(C),Wn=!1;let $=!1,z=null,D=Se=>{typeof ce<"u"&&ce!==null&&ce.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Se,bodyStyle:"tool-status-fail"}])},Z=!1;Ct={text:g,attachments:v,cancel:()=>{if(Wn){Wn=!1,Z=!0,D("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),w.request("hydra-acp/session/force_cancel",{sessionId:le}).catch(ae=>{D(`force-stop failed: ${ae.message}`)});return}if($)return;$=!0,w.notify("session/cancel",{sessionId:le}).catch(()=>{});let Se=Date.now();z=setTimeout(()=>{Ct!==null&&(li>=Se||(Wn=!0,D("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Po)}};let Re;try{let Se=await w.request("session/prompt",{sessionId:le,prompt:R});Se&&typeof Se.stopReason=="string"&&(Re=Se.stopReason)}catch(Se){let ae=oe.indexOf(C);ae>=0&&oe.splice(ae,1),C.messageId!==void 0&&me.delete(C.messageId),Z?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:Se.message,bodyStyle:"tool-status-fail"}])}finally{if(Ct=null,z!==null&&(clearTimeout(z),z=null),ee(-1),C.flushed&&Je===C){let Se=C.messageId!==void 0&&He.has(C.messageId);Se&&C.messageId!==void 0&&He.delete(C.messageId);let ae={kind:"turn-complete"};Re!==void 0&&(ae.stopReason=Re),Se&&(ae.amended=!0),E(ae),Je=null}if(Gt!==null){let{text:Se,attachments:ae}=Gt;Gt=null,De.state().buffer.every(ot=>ot==="")&&(De.setBuffer(Se,ae),I.refreshPrompt())}}},Ye=new Map,yn=new Map,Rs=new Map,Wt=new Map,tn=[],Vs=0,Lt=`tools:${Vs}`,Ts=new Map,Pr=new Map,vi=new Set,Mr=new Map,Qs=new Map,Xn=new Map,qe=null,nn=null,Pn=null,Zn=null,Gs=null,Fl=e.tui.maxToolItems,Jo=e.tui.maxPlanItems,Xs=()=>({maxPlanItems:Gs??i.planExpanded?1/0:Jo}),Si=()=>{if(Zn===null)return;let g=pr(Zn,Xs());g.length>0&&I.upsertLines("plan",[{body:""},...g])},L="",K=null,ue=0,J=()=>{if(K===null)return;let g=I.width(),v=hr(L,g>0?{maxWidth:g}:void 0);v.length!==0&&I.upsertLines(K,v)},he=g=>{g.length!==0&&(K===null&&(I.ensureSeparator(),K=`agent:${ue}`,ue+=1,L=""),L+=g,J())},de=()=>{K=null,L=""},Pe="",Ae=null,ze=0,dt=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),sn=()=>{if(Ae===null||Pe.length===0)return;let g=go(Pe);g.length!==0&&I.upsertLines(Ae,g)},es=g=>{let v=Qs.get(g);if(v===void 0)return[];let x=go(v.text);return v.workerTaskId&&x.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"dim"}),x},gt=(g,v)=>{g.length!==0&&(Ae===null&&(I.ensureSeparator("thought"),Ae=`thought:${ze}`,ze+=1,Pe=""),Pe+=g,Qs.set(Ae,{text:Pe,workerTaskId:v}),sn())},xe=()=>{Ae=null,Pe=""},St=g=>XE({...g,collapsedLimit:Fl}),Mn=g=>Pr.get(g)??i.toolsExpanded,it=()=>{if(qe===null)return;let{lines:g,rowOwners:v}=St({order:tn,states:Ye,startedAt:qe,endedAt:nn,stopReason:Pn,expanded:Mn(Lt),perToolExpanded:vi});I.upsertLines(Lt,g),Mr.set(Lt,v)},_n=g=>{let v=Ts.get(g);if(!v)return;let{lines:x,rowOwners:R}=St({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:Mn(g),perToolExpanded:vi});I.upsertLines(g,x),Mr.set(g,R)},_r=()=>{qe!==null&&!Ts.has(Lt)&&it();for(let g of Ts.keys())_n(g)},Yo=()=>{qe!==null&&Ts.set(Lt,{order:[...tn],states:new Map(Ye),startedAt:qe,endedAt:nn??Date.now(),stopReason:Pn,rowOwners:Mr.get(Lt)??[]})},hd=()=>{Vs+=1,Lt=`tools:${Vs}`,qe=Date.now(),nn=null,Pn=null,it()};function Vo(g){if(!g||typeof g!="object")return null;let v=g,x=Array.isArray(v.content)?v.content:void 0;if(!x)return null;let R=[],C=$=>{if(typeof $=="string"){R.push({text:wt($)});return}if($&&typeof $=="object"){let z=$;typeof z.__hydraBlob=="string"&&R.push({hash:z.__hydraBlob})}};for(let $ of x){if(!$||typeof $!="object")continue;let z=$;if(z.type==="content"&&z.content&&typeof z.content=="object"){let D=z.content;if(D.text!==void 0){C(D.text);continue}}if(z.type==="text"&&z.text!==void 0){C(z.text);continue}z.text!==void 0&&C(z.text)}return R.length>0?R:null}let Ke=(g,v)=>{let x=v.map($=>"text"in $?$.text:"").join(`
258
- `);if(x.length===0)return;let{text:R,truncated:C}=tw(x);g.resultText=R,g.resultTruncated=C},yt=new Set,$r=(g,v)=>{!v.some(R=>"hash"in R)||yt.has(g)||(yt.add(g),(async()=>{let R=await Promise.all(v.map(async $=>"text"in $?$:{text:await Ol($.hash)??""}));yt.delete(g);let C=Ye.get(g);if(!C)for(let $ of Ts.values()){let z=$.states.get(g);if(z){C=z;break}}if(C){Ke(C,R),Ye.has(g)&&it();for(let[$,z]of Ts)z.states.has(g)&&_n($);I.repaintNow()}})().catch(()=>{yt.delete(g)}))},Qo=(g,v,x,R,C,$,z,D,Z,Re)=>{let Se=!Ye.has(g),ae=Ye.get(g),we=ae??{initialTitle:v??"tool",latestTitle:v??"tool",status:x??"pending",startedAt:Date.now()};if(!ae&&Z!==void 0&&(we.workerTaskId=Z),ae&&v!==void 0&&(we.latestTitle=v),$!==void 0&&we.detail===void 0&&(we.detail=$),z!==void 0&&we.detailFull===void 0&&(we.detailFull=z),D!==void 0&&D.length>0&&(we.locations=D),ae&&x!==void 0&&(we.status=x),ae||(we.status=x??"pending"),we.endedAt===void 0&&Tf(we.status)&&(we.endedAt=Date.now()),R!==void 0&&(we.errorText=R),C!==void 0&&(we.editDiff=C),Re!==void 0){let ot=Vo(Re);ot!==null&&(Ke(we,ot),ot.some(ts=>"hash"in ts)&&$r(g,ot))}Ye.set(g,we),Se&&(qe===null&&(Vs+=1,Lt=`tools:${Vs}`,qe=Date.now(),nn=null,Pn=null),tn.push(g))},Ol=async g=>{try{let v=await w.request("hydra-acp/session/tool_content",{sessionId:le,hash:g});return typeof v?.content=="string"?v.content:null}catch{return null}},md=new Set,Xv=(g,v)=>{md.has(g)||v.oldRef===void 0&&v.newRef===void 0||(md.add(g),(async()=>{let[x,R]=await Promise.all([v.oldRef?Ol(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?Ol(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&x===null||v.newRef!==void 0&&R===null){md.delete(g);let Re=Cf(v,"diff",{deferredStatus:"error"});Re.length>0&&(I.upsertLines(`editdiff:${g}`,Re),I.repaintNow());return}let $={...v.path!==void 0?{path:v.path}:{},oldText:x??"",newText:R??""};yn.set(g,$);let z=Ye.get(g);z?.editDiff&&(z.editDiff=$),md.delete(g);let D=Rs.get(g),Z=D===void 0?i.showFileUpdates:D?"diff":"edit";Z!=="none"&&(gd(g,$,Z==="diff"?"diff":"edit"),I.repaintNow())})())},gd=(g,v,x)=>{let R=`editdiff:${g}`,C=Cf(v,x);if(C.length===0){I.removeKey(R);return}I.upsertLines(R,C),x==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&I.notifyWhenVisible(R)},Zv=g=>{if(!g.startsWith("editdiff:"))return;let v=g.slice(9),x=yn.get(v);x&&(x.oldRef!==void 0||x.newRef!==void 0)&&Xv(v,x)},Wp=g=>{let v=`editdiff:${g}`,x=i.showFileUpdates,R=Ye.get(g),C;if(x==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let z=Rs.get(g);C=z!==void 0?z?"diff":"edit":x==="diff"?"diff":"edit"}if(C===null){I.removeKey(v);return}let $=R.editDiff;yn.set(g,$),gd(g,$,C)},eS=()=>{let g=i.showFileUpdates;for(let[v,x]of yn){let R=`editdiff:${v}`,C=Rs.get(v),$=C===void 0?g:C?"diff":"edit";if($==="none"){I.removeKey(R);continue}gd(v,x,$==="diff"?"diff":"edit")}},tS=g=>{if(!g.path)return null;let v=wt(g.oldText).split(`
255
+ `)}}function tP(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,c=e.length,d=a>0,l;if(!d||n.expanded)l=e;else{let _=Math.max(0,c-a),F=e.slice(_),B=[];for(let N=0;N<_;N++){let j=e[N];if(j===void 0)continue;let G=t.get(j);G&&!Tf(G.status)&&B.push(j)}l=[...B,...F]}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",w=y?`amended \xB7 ${ps(h)}`:`stopped (${m}) \xB7 ${ps(h)}`,b;if(c===0)m!==null?b=w:b=f?`thinking \xB7 ${ps(h)}`:`thought \xB7 ${ps(h)}`;else{let _=c===1?"tool":"tools",F=m!==null?w:f?ps(h):`took ${ps(h)}`,B=[`${c} ${_}`,F];f&&d&&u>0&&B.push(`${u} hidden`),b=B.join(" \xB7 ")}let S=c===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],H=[null];for(let _ of l){let F=t.get(_);if(F){let B=Fa(F,p);for(let N of B)N.hoverSubKey=_;if(P.push(...B),H.push(...B.map(()=>_)),o?.has(_)){let N=sw(F);for(let j of N)j.hoverSubKey=_;P.push(...N),H.push(...N.map(()=>_))}}}return{lines:P,rowOwners:H}}async function nP(n,e,t,s,r,i,o){let a=await sP(n,e,t,s,o,i);if(!a)return n.grabInput(!1),ie({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.resolved?.status==="warm"&&t.isLocal,d=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":a.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",l=s.installStatus;s.installStatus&&delete s.installStatus;let u=a.installStatus??l??Rl(c?"":d,gv(n));c||u.write(d);let f=t.isLocal?async()=>(await Bt(await Ie())).wsUrl:t.wsUrl,p=["acp.v1",`hydra-acp-token.${t.token}`],h=null,m=null,y=new xo({url:f,subprotocols:p,onConnect:async g=>{g||h&&await h()},onDisconnect:g=>{m&&m(g)},log:g=>ie({src:"resilient-ws",line:g})}),w=new zt(y);await y.start(),w.onNotification(_d,g=>{let v=im.safeParse(g);v.success&&u.applyProgress(v.data)});let b=[],S=null,k=!1,A=!1,E=(g,v)=>{g&&(S?S(g,v):b.push({event:g,rawUpdate:v}))},P,H=g=>{g!==P&&(P=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},_=null,F=null,B=!1,N=0,j=0,G=!1,X=!1,V,ye=null,Be=null,mt=null,_e=null,ys=()=>setInterval(()=>{if(ye===null||ce===null)return;let g=_e===null?0:Date.now()-_e;ce.setBanner({elapsedMs:Date.now()-ye,stalled:g>=GE}),it()},1e3),Ee=!1,ee=g=>{let v=j;j=Math.max(0,j+g);let x=typeof ce<"u"&&ce!==null;v===0&&j>0?(X=!1,ye=Date.now(),_e=Date.now(),$e?.setTurnRunning(!0),x&&ce.setBanner({status:"busy",elapsedMs:0,stalled:!1}),Be===null&&x&&(Be=ys())):v>0&&j===0?(X=!1,ye=null,_e=null,$e?.setTurnRunning(!1),Be!==null&&(clearInterval(Be),Be=null),x&&ce.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):j>0&&X&&(X=!1,x&&ce.setBanner({status:"busy",stalled:!1}))},ce=null,$e=null,fn,pn=null,An=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"]),Ht=g=>{let{update:v}=g??{},x=cs(v,{cwd:Ne});rP(v,x),_e=Date.now();let R=v?.sessionUpdate;if(typeof R=="string"&&!An.has(R)){let C=v??{};typeof C.messageId=="string"&&(fn=C.messageId)}if(R==="prompt_received"?ee(1):x?.kind==="turn-complete"&&(ee(-1),B=!0),R==="permission_resolved"){Ut(v);return}if(R==="hydra_compaction"){Cn(v);return}if(R==="clarifier_question_asked"){let C=v,$=typeof C.question?.question=="string"?C.question.question:"",z=$.length>50?$.slice(0,49)+"\u2026":$;I.notify(z?`new question: ${z} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(E(x,v),id(v))};w.onNotification("session/update",g=>{if(!k){if(pn!==null){pn.push(g);return}Ht(g)}}),w.onNotification("hydra-acp/session/closed",()=>{if(k)return;j>0&&ee(-j),typeof ce<"u"&&ce!==null&&ce.setBanner({status:"cold",elapsedMs:void 0})});let Yt=new Map,vr=200,li=0,Wn=!1,Po=4e3;w.onNotification("hydra-acp/prompt_queue/added",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let R=v.messageId,C=v.prompt,$=setTimeout(()=>{k||(Yt.delete(R),te.set(R,Q(R,C)),ce&&$e&&rt())},vr);Yt.set(R,$)}else te.set(v.messageId,Q(v.messageId,v.prompt)),ce&&$e&&rt();if(Rn!==void 0&&v.originator?.clientId===Rn){let R=oe.shift();R&&(R.messageId=v.messageId,me.set(v.messageId,R))}}),w.onNotification("hydra-acp/prompt_queue/updated",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string"||!te.has(v.messageId))return;te.set(v.messageId,Q(v.messageId,v.prompt));let x=me.get(v.messageId);if(x){let R=Array.isArray(v.prompt)?v.prompt:[],C="",$=[];for(let z of R){if(!z||typeof z!="object")continue;let D=z;D.type==="text"&&typeof D.text=="string"?C+=D.text:D.type==="image"&&typeof D.data=="string"&&typeof D.mimeType=="string"&&$.push({data:D.data,mimeType:D.mimeType,sizeBytes:Math.floor(D.data.length*3/4)})}x.text=C,x.attachments=$}ce&&$e&&rt()}),w.onNotification("hydra-acp/prompt_queue/removed",g=>{if(k)return;let v=g??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(V=v.messageId);let x=Yt.get(v.messageId);x!==void 0&&(clearTimeout(x),Yt.delete(v.messageId)),te.delete(v.messageId)&&ce&&$e&&rt();let C=me.get(v.messageId);C&&(me.delete(v.messageId),v.reason==="started"&&(C.flushed=!0,E({kind:"user-text",text:C.displayText,attachments:C.attachments}),Je=C))}),w.onNotification("hydra-acp/cancel_failed",g=>{if(k)return;let v=g??{};if(!(typeof ce<"u"&&ce!==null))return;li=Date.now(),Wn=!0;let R=typeof v.code=="number"?` (${v.code})`:"",C=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";ce.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${R}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),w.onNotification("hydra-acp/prompt/amended",g=>{if(k)return;let v=g??{};if(typeof v.cancelledMessageId!="string")return;let x=v.cancelledMessageId;He.add(x),Je!==null&&Je.messageId!==void 0&&Je.messageId===x&&(E({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Je=null,He.delete(x))});let Cn=g=>{let v=g??{},x=typeof v.phase=="string"?v.phase:void 0;if(x==="started")I.setCompactionIndicator("compacting...");else if(x==="iteration")I.setCompactionIndicator("compacting...");else if(x==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(x==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(x==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(x==="failed"){I.setCompactionIndicator(null);let R=typeof v.error=="string"?v.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;I.notify(`compaction failed: ${C}`,5e3)}},rd=()=>{mt===null&&(mt=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),mt!==null&&(clearInterval(mt),mt=null)):v.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),mt!==null&&(clearInterval(mt),mt=null))}catch{}},5e3))},Mo=()=>{mt!==null&&(clearInterval(mt),mt=null)},Ut=g=>{let v=g??{},x=typeof v.toolCallId=="string"?v.toolCallId:void 0,R;v.outcome&&typeof v.outcome=="object"?R=v.outcome:typeof v.chosenOptionId=="string"&&(R={kind:"selected",optionId:v.chosenOptionId}),_o(x,R?{outcome:R}:void 0)},Ce=null,_o=(g,v)=>{if(!Ce||Ce.toolCallId&&g&&Ce.toolCallId!==g)return;let x=Ce.resolve;Ce=null,I.setPermissionPrompt(null),x(v??{outcome:{outcome:"cancelled"}})},id=g=>{if(!Ce?.toolCallId)return;let v=g??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Ce.toolCallId&&(!v.status||v.status==="pending"||_o(v.toolCallId,void 0))},ui=()=>{if(!Ce){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:Ce.title,detail:Ce.detail,options:Ce.options.map(g=>({label:g.name})),selectedIndex:Ce.selectedIndex})},$o=g=>{if(!Ce)return;let{options:v,resolve:x}=Ce;if(Ce=null,I.setPermissionPrompt(null),g===null){x({outcome:{outcome:"cancelled"}});return}x({outcome:{outcome:"selected",optionId:g}})};w.onRequest("session/request_permission",async g=>{if(k)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ii(g);let v=g??{},R=(Array.isArray(v.options)?v.options:[]).map(Z=>({optionId:Z.optionId,name:Te(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=v.toolCall?.title??v.toolCall?.name??"tool",$=Te(C),z=Te(sb(nb(g))),D=v.toolCall?.toolCallId;return R.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${$} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{Ce={title:$,detail:z,options:R,selectedIndex:0,resolve:Z,toolCallId:D},ui()})}),w.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let At,ws,hn=!0,bs=!1;try{let g=await w.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ve}});ws=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(hn=!1),bs=an(g?._meta??void 0).prompt?.amending===!0}catch{}let le=a.sessionId,at=a.agentId,Ne=a.cwd,fi,Rn,Us,Sr,js,vs,Vt,qs,pi,zn,Fo=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let v={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Mt]:g}}:{}},x;try{x=await Jw({request:()=>w.request("session/new",v),showBanner:($,z,D)=>Yw(n,$,z,D,{authenticate:Z=>w.request("authenticate",{methodId:Z})}),resolveOnboarding:async $=>{if($)try{return(await Qr(t)).find(Z=>Z.id===$)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch($){n.grabInput(!1),ie({src:"grab",site:"runSession.session-new-failed",on:!1}),y.close().catch(()=>{});let z=$ instanceof Error?$.message:String($);ie({src:"session-new-failed",agentId:s.agentId??null,message:z});let D=await vv(n,s.agentId,z,{canGoBack:!s.forceNew});if(D==="cancel")return null;let Z={...s};return delete Z.sessionId,delete Z.resume,D==="retry"?Z.forceNew=!0:(delete Z.forceNew,delete Z.agentId),Z}if(x.kind==="cancel")return n.grabInput(!1),ie({src:"grab",site:"runSession.auth-cancel",on:!1}),y.close().catch(()=>{}),null;if(x.kind==="back"){n.grabInput(!1),ie({src:"grab",site:"runSession.auth-back",on:!1}),y.close().catch(()=>{});let $={...s};return delete $.sessionId,delete $.forceNew,delete $.resume,delete $.agentId,$}let R=x.result;u.write(d),le=R.sessionId,Op(le),r.sessionId=le,r.readonly=!1;let C=an(R._meta??void 0);C.clientId&&(Rn=C.clientId),At=C.upstreamSessionId,C.agentId&&(at=C.agentId),C.cwd&&(Ne=C.cwd),C.title&&(fi=C.title),Us=C.currentModel,Sr=C.currentMode,pi=C.currentUsage,zn=C.turnStartedAt,C.availableCommands&&(js=fc(C.availableCommands)),C.availableModes&&(vs=C.availableModes),Vt=Ov(R.configOptions),qs=C.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let v=await w.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:ve},...Object.keys(g).length>0?{_meta:{[Mt]:g}}:{}});le=v.sessionId,Op(le),v.clientId&&(Rn=v.clientId),r.sessionId=le,r.readonly=s.readonly===!0;let x=an(v._meta??void 0);Fo=x.resurrected===!0,At=x.upstreamSessionId,x.agentId&&(at=x.agentId),x.cwd&&(Ne=x.cwd),x.title&&(fi=x.title),Us=x.currentModel,Sr=x.currentMode,pi=x.currentUsage,zn=x.turnStartedAt,x.availableCommands&&(js=fc(x.availableCommands)),x.availableModes&&(vs=x.availableModes),Vt=Ov(v.configOptions),qs=x.queue}let Ss=O.tuiHistoryFile(le),kr=O.globalTuiHistoryFile(),jt=await ma(Ss).catch(()=>[]),Qt=await ma(kr).catch(()=>[]);Qt.length>e.tui.promptHistoryMaxEntries&&(Qt=Qt.slice(Qt.length-e.tui.promptHistoryMaxEntries));let mn=[...jt],De=new Bs({history:Yd(Qt,mn)});$e=De;let We=!1,Kn=(g,v)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let R=(v??g).replace(/\n+$/,""),C=ga(jt,x),$=C!==jt;jt=C,mn=ga(mn,R);let z=ga(Qt,x,e.tui.promptHistoryMaxEntries),D=z!==Qt;Qt=z,De.setHistory(Yd(Qt,mn)),$&&Wr(Ss,jt).catch(()=>{}),D&&rg(kr,x).catch(()=>{})};j>0&&De.setTurnRunning(!0);let Ct=null,Gt=null;rv(iv(e.tui.ambiguousWidth,process.env)),iw(e.tui.diffContextLines);let hi=!1,I,Xt=()=>{hi&&(hi=!1,I.start())},Oo=()=>{hi||(hi=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Xt);let Ir=null,mi=null;I=new vl({term:n,dispatcher:De,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"?Oo:void 0,onBlockClick:(g,v)=>{iS(g,v)},onBlockDoubleClick:(g,v)=>rS(g,v),onHydraLinkClick:g=>(Ko(g),!0),onBlockVisible:g=>{tS(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let v=Xn.get(g);if(v!==void 0&&v.length>0)return new Set(v);let x=I.contiguousRun(g,new Set(Qs.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Ir=I.bannerHitAt(g.x,g.y),mi=Ir?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=mi,R=Ir;if(mi=null,Ir=null,R!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Rs(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Bp(C))return;As(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let v={type:"attachment-request",source:"primary"};s.readonly===!0&&Bp(v)||As(v)},onKey:g=>{for(let v of g){if(G&&ud(v)){v.type==="key"&&ie({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Ce&&Ar(v)){v.type==="key"&&ie({src:"key-swallowed",site:"permission",name:v.name});continue}if(fd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"help",name:v.name});continue}if(bi(v)){v.type==="key"&&ie({src:"key-swallowed",site:"questions",name:v.name});continue}if(Gn(v)){v.type==="key"&&ie({src:"key-swallowed",site:"options",name:v.name});continue}if(cd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(vt(v)){v.type==="key"&&ie({src:"key-swallowed",site:"completion",name:v.name});continue}if(dd(v)){v.type==="key"&&ie({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(v.type==="attachment-paths"){T(v.paths);continue}if(v.type==="key"&&No(v.name)){ie({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let x=De.feed(v);for(let R of x)s.readonly===!0&&Bp(R)||As(R)}ad(),I.setBannerSearchIndicator(De.state().historySearchQuery),I.setAttachments(De.state().attachments),I.refreshPrompt()}}),ce=I,I.setStickyBottomKey("plan");let Lo=[{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]"}],Ws=js??[],ks=vs??[],xr=Vt??[],Ze=()=>xr.find(g=>g.id==="agent"),od=()=>{let g=new Set,v=[];for(let x of[...Lo,...Ws])g.has(x.name)||(g.add(x.name),v.push(x));return v},Bo=()=>{let g=De.state().buffer,v=g[0]??"";if(!v.startsWith("/"))return[];if(g.length>1)return[];let x=v.indexOf(" "),R=x===-1?v:v.slice(0,x);if(R.lastIndexOf("/")>0)return[];let C=od().filter($=>$.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},bt=[],ad=()=>{let g=Bo();if(g.length>0){bt=[],I.setCompletions(g);return}I.setCompletions(bt)},vt=g=>{if(g.type!=="key"||g.name!=="tab")return bt.length>0&&(bt=[]),!1;let v=Bo();if(I.isOverlayOpen()&&v.length===0)return I.toggleFocusedPane(),!0;if(v.length>0){bt=[];let x=De.state().buffer[0]??"",R=uv({matches:v.map(C=>C.name),firstLine:x});return R===null||De.replaceFirstLine(R),!0}return Is()},Is=()=>{let g=De.state(),v=g.buffer[g.row]??"",x=Al(v,g.col);if(x===null)return!1;let R=Cl(x.token,Ne);return R===null?!1:(R.replacement!==x.token&&De.replaceRangeOnCurrentLine(x.start,g.col,R.replacement),bt=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},dd=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay(),!0),cd=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 v=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(v),!0}if(g.type==="paste"){let v=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(v),!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 v=I.scrollbackSearchTerm();return v.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Ar=g=>{if(!Ce)return!1;let v=Ce.options;if(g.type==="key")switch(g.name){case"up":return Ce.selectedIndex=Math.max(0,Ce.selectedIndex-1),ui(),!0;case"down":return Ce.selectedIndex=Math.min(v.length-1,Ce.selectedIndex+1),ui(),!0;case"enter":{let x=v[Ce.selectedIndex];return x&&$o(x.optionId),!0}case"escape":case"ctrl-c":return $o(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,R=v[x];return R&&$o(R.optionId),!0}return!0},No=g=>{let v=e.tui.hotkeys[g];return v?(kv(v,{sessionId:le,cwd:Ne,agentId:at||ws||"",baseUrl:t.baseUrl,tokenFile:O.authToken()},{notify:x=>I.notify(x),cwd:Ne,emitLines:x=>{I.appendLines(x.map(R=>{let C;switch(R.style){case"meta":C="dim";break;case"stderr":case"error":C="tool-status-fail";break;default:C="info"}return{prefix:" ",body:R.text,bodyStyle:C}}))}}),!0):!1},ld=at||ws||"?",Tt={...pi??{}};u.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:ld,cwd:Ne,sessionId:le,title:fi,model:Us,usage:{...Tt}}),Sr&&I.setBanner({currentMode:Sr}),ja().then(g=>{g&&I.notify(`\u2728 ${qa(g)}`,3e4)}).catch(()=>{});let ft=null,Do=new Promise(g=>{ft=g}),Ho=()=>{w.notify("session/cancel",{sessionId:le}).catch(()=>{})},Uo=()=>{ce!==null&&j===1&&(X=!0,ce.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},jo=()=>{if(Ct){Ct.cancel(),Uo();return}if(j>0){Ho(),Uo();return}Cr()},Cr=()=>{Ks(0)},qo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",v]],...XE]},gi=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:qo(),hint:"any key dismisses \xB7 /help lists commands"})},Jn=()=>{G=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=le;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Yn=()=>{G=!1,I.setCompactionPrompt(null)},Rr=g=>{let v=I.compactionPromptSpec();if(!v)return;let x=v.options.length;if(x===0)return;let R=((v.selectedIndex+g)%x+x)%x;R!==v.selectedIndex&&I.setCompactionPrompt({...v,selectedIndex:R})},ud=g=>{if(!G)return!1;if(g.type==="key"){if(g.name==="escape")return Yn(),!0;if(g.name==="up")return Rr(-1),!0;if(g.name==="down")return Rr(1),!0;if(g.name==="enter"){let v=I.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Jn():Yn(),!0}}if(g.type==="char"){let v=g.ch.toLowerCase();if(v==="y"||v==="1")return Jn(),!0;if(v==="n"||v==="2")return Yn(),!0}return!0},fd=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Tr=["tools","plan","thoughts","diffs","mouse","enter"],Tn=0,Zt=null,en=[],Vn=[],En=[],Qn=0,Wo=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}},pd=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"}},gn=()=>({title:"Session options",options:Tr.map(g=>({label:pd(g),value:Wo(g)})),selectedIndex:Tn}),zo=()=>{I.isOptionsPromptActive()&&Zt===null&&I.setOptionsPrompt(gn())},xs=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Tn=0,I.setOptionsPrompt(gn())},Pn=()=>{if(Zt===null)return;let g=JE(Zt,en,En,Qn);I.setOptionsPrompt(g)},yi=()=>{Zt=null,en=[],Vn=[],En=[],Qn=0,I.setOptionsPrompt(null)},$l=async()=>{if(Zt!==null){yi();return}try{let v=await w.request(Cb,{sessionId:le}),x=qE(v.questions??[]);if(x.length===0){I.notify("no open questions");return}let R=zE(x);Zt=R,Qn=0,en=R.map(C=>WE(C.representative)),Vn=R.map(()=>!1),En=R.map(()=>!1),Pn()}catch(g){I.notify("clarifier unavailable"),ie({src:"questions",step:"list_failed",error:g.message})}},zs=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Pr.clear(),vi.clear(),_r();break;case"plan":i.planExpanded=!i.planExpanded,Gs=null,Si();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Ts.clear(),nS();break;case"mouse":{let v=!I.isMouseEnabled();I.setMouseEnabled(v),i.mouseEnabled=v;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}zo()},wi=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${pd(g)} is session-only \u2014 not saved`);return;case"thoughts":await ea("showThoughts",i.showThoughts);break;case"diffs":await ea("showFileUpdates",i.showFileUpdates);break;case"mouse":await ea("mouse",i.mouseEnabled);break;case"enter":await ea("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${pd(g)} ${Wo(g)}`)}catch(v){I.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},Gn=g=>{if(Zt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Tn=Math.max(0,Tn-1),zo(),!0;case"down":return Tn=Math.min(Tr.length-1,Tn+1),zo(),!0;case"enter":{let v=Tr[Tn];return v&&zs(v),!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 v=parseInt(g.ch,10)-1,x=Tr[v];return x&&(Tn=v,zs(x)),!0}if(g.ch==="s"||g.ch==="S"){let v=Tr[Tn];return v&&wi(v),!0}}return!0},bi=g=>{if(Zt===null)return!1;let v=QE(g,!0,Zt,en,Vn,En,Qn,le);switch(v.type){case"noop":return!0;case"row":return Qn=v.selectedRow,Pn(),!0;case"cycle":return en[v.selectedRow]=v.newValueIndex,Vn[v.selectedRow]=!0,En[v.selectedRow]=!1,Pn(),!0;case"dismiss-toggle":{let x=v.selectedRow;return En[x]?(En[x]=!1,Vn[x]=!1):(En[x]=!0,Vn[x]=!0),Pn(),!0}case"discard":return yi(),!0;case"save":{let x=v.dispatches;return yi(),x.length===0||(async()=>{let R=0,C=0,$=0;for(let D of x)try{await w.request(D.method,D.params),D.type==="dismiss"?C++:R++}catch(Z){$++,ie({src:"questions",step:"dispatch_failed",method:D.method,error:Z.message})}let z=[];R>0&&z.push(`${R} answered`),C>0&&z.push(`${C} dismissed`),$>0&&z.push(`${$} failed`),z.length>0&&I.notify(`clarifier: ${z.join(", ")}`)})(),!0}}return!1},qt=()=>{if(!k){k=!0,_?(_.cancel(),_=null,F=null):F!==null&&(fs(t,F).catch(()=>{}),F=null),process.off("SIGINT",jo),process.platform!=="win32"&&process.off("SIGCONT",Xt),Be!==null&&(clearInterval(Be),Be=null),mt!==null&&(clearInterval(mt),mt=null);for(let g of Yt.values())clearTimeout(g);Yt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Wr(Ss,jt).catch(()=>{}),y.close().catch(()=>{})}},Ks=(g=0)=>{qt(),ft&&(ft(null),ft=null),g!==0&&process.exit(g)},Ft=async()=>{if(ie({src:"switch-session",step:"entered",finishSessionNull:ft===null}),!ft)return;_?(_.cancel(),_=null,F=null):F!==null&&(fs(t,F).catch(()=>{}),F=null),Mo(),I.setSynthesisIndicator(null);let g=De.state().buffer.join(`
256
+ `);g.replace(/\s+$/,"").length>0&&Kn(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Wr(Ss,jt).catch(()=>{});let v=!1;try{let x=null,R=null;for(;x===null;){let D=await Dn(t,{includeNonInteractive:!0}),Z=s.agentId??i.lastChosenAgent??e.defaultAgent,Re=Z?e.defaultModels?.[Z]:void 0,Se=[];try{Se=await Qr(t)}catch{}let ae=await $p(n,{cwd:Ne,sessions:D,config:e,target:t,currentSessionId:le,prefs:o,...Z?{composerAgentId:Z}:{},...Re?{composerModel:Re}:{},...Se.length>0?{availableAgents:Se}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){v=!0,Ks(0);return}if(ae.kind==="new"){x={choice:ae,sessions:D};break}if(ae.kind==="fork"){let Fn=await jv(n,t,ae,D);if(Fn.kind==="cancel")return;if(Fn.kind==="back")continue;x={choice:{kind:"attach",sessionId:Fn.ctx.sessionId,...Fn.ctx.agentId?{agentId:Fn.ctx.agentId}:{}},sessions:D},R={readonly:!1,cwd:Fn.ctx.cwd},Fn.ctx.resumeHint!==void 0&&(R.resumeHint=Fn.ctx.resumeHint);break}let we=D.find(Fn=>Fn.sessionId===ae.sessionId);if(!(we!==void 0&&!!we.importedFromMachine&&!we.upstreamSessionId&&ae.readonly!==!0)){if(t.isLocal&&we&&!we.importedFromMachine&&ae.readonly!==!0&&!(await za(we.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let Xo=await di(n,we,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Xo.kind==="cancel")return;if(Xo.kind==="back")continue;x={choice:ae,sessions:D},R={readonly:!1,cwd:Xo.path,resumeHint:{agentId:ae.agentId??we.agentId??"",cwd:Xo.path,upstreamSessionId:""}};break}x={choice:ae,sessions:D};break}let ts={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let Go=await Hv(n,t,we,ae,ts);if(Go.kind==="cancel")return;Go.kind!=="back"&&(x={choice:ae,sessions:D},R={readonly:ts.readonly===!0,cwd:Go.ctx.cwd},Go.ctx.resumeHint!==void 0&&(R.resumeHint=Go.ctx.resumeHint))}let{choice:C}=x,$=ft;if(ft=null,qt(),v=!0,C.kind==="new"){let{sessionId:D,agentId:Z,...Re}=s,Se={...Re,cwd:C.cwd??Ne,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Se.initialPrompt=C.prompt),C.attachments&&C.attachments.length>0&&(Se.initialAttachments=C.attachments),C.agentId!==void 0&&(Se.agentId=C.agentId,i.lastChosenAgent=C.agentId),C.model!==void 0&&(Se.model=C.model),C.installStatus!==void 0&&(Se.installStatus=C.installStatus),$(Se);return}if(C.kind!=="attach")return;let z={...s,sessionId:C.sessionId,cwd:R?.cwd??Ne,readonly:R?.readonly??C.readonly===!0};C.agentId!==void 0&&(z.agentId=C.agentId),R?.resumeHint!==void 0?z.resumeHint=R.resumeHint:delete z.resumeHint,C.installStatus!==void 0?z.installStatus=C.installStatus:delete z.installStatus,$(z)}finally{!v&&ft&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},Er=async(g="next")=>{if(!ft)return;let x=(await Dn(t)).filter(Se=>Se.status==="warm");if(x.length<=1)return;let R=x.findIndex(Se=>Se.sessionId===le),z=((R===-1?0:R)+(g==="prev"?-1:1)+x.length)%x.length,D=x[z],Z=ft;ft=null,qt();let Re={...s,sessionId:D.sessionId,cwd:Ne,readonly:!1,resolved:D};D.agentId!==void 0&&(Re.agentId=D.agentId),Z(Re)},Ko=async g=>{if(!ft)return;let v=await Dn(t,{includeNonInteractive:!0}),x=g.trim();if(!x){I.notify("usage: /session <id|next|prev>");return}let R=x.startsWith(Dt)?[x]:[x,Dt+x],C=v.find(D=>R.includes(D.sessionId));if(!C){let D=v.filter(Z=>R.some(Re=>Z.sessionId.startsWith(Re)));if(D.length===1)C=D[0];else if(D.length>1){I.notify(`ambiguous session id: ${x} (${D.length} matches)`);return}}if(!C){I.notify(`no session matches: ${x}`);return}if(C.sessionId===le){I.notify("already on that session");return}let $=ft;ft=null,qt();let z={...s,sessionId:C.sessionId,cwd:C.cwd??Ne,readonly:!1,resolved:C};C.agentId!==void 0&&(z.agentId=C.agentId),delete z.resumeHint,$(z)},As=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ot(g.text,g.attachments,g.displayText):Cs(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Cs(g.text,g.attachments,g.displayText):Ot(g.text,g.attachments,g.displayText);return;case"queue-edit":{let v=et(g.index);if(!v)return;let x=[];g.text.length>0&&x.push({type:"text",text:g.text});for(let R of g.attachments)x.push({type:"image",data:R.data,mimeType:R.mimeType});w.request("hydra-acp/prompt/update",{sessionId:le,messageId:v,prompt:x}).then(R=>{let C=R;!C.updated&&C.reason!=="ok"&&I.notify(`queue edit skipped (${C.reason})`)}).catch(R=>{I.notify(`queue edit failed: ${R.message}`)});return}case"queue-remove":{let v=et(g.index);if(!v)return;w.request("hydra-acp/prompt/cancel",{sessionId:le,messageId:v}).then(x=>{let R=x;!R.cancelled&&R.reason!=="ok"&&I.notify(`queue cancel skipped (${R.reason})`)}).catch(x=>{I.notify(`queue cancel failed: ${x.message}`)});return}case"cancel":{if(I.isOverlayOpen()){_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay();return}if(g.prefill&&Ct){let v=te.size===0,x=De.state().buffer.every(R=>R==="");v&&x&&(Gt={text:Ct.text,attachments:Ct.attachments})}Ct?Ct.cancel():j>0&&Ho(),Uo();return}case"exit":Cr();return;case"plan-toggle":Rs(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":Ft().catch(v=>{ie({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":Er("next").catch(()=>{});return;case"prev-live-session":Er("prev").catch(()=>{});return;case"toggle-options":xs();return;case"toggle-questions":$l();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 v=!I.isMouseEnabled();I.setMouseEnabled(v),i.mouseEnabled=v,I.notify(v?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":gi();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":M(g.source);return}},T=async g=>{if(!hn){I.notify("agent does not accept image attachments");return}let v=0;for(let x of g){if(x.startsWith("data:")){let C=rp(x);if(!C){I.notify("unsupported data: URI");continue}if(C.sizeBytes>ms){I.notify(`image too large (${xn(C.sizeBytes)}, max ${xn(ms)})`);continue}De.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),v++;continue}let R=Ja(x);if(!R){I.notify(`unsupported image type: ${ci.basename(x)}`);continue}try{let C=await Lp.readFile(x);if(C.length>ms){I.notify(`image too large (${xn(C.length)}, max ${xn(ms)})`);continue}De.addAttachment({mimeType:R,data:C.toString("base64"),name:ci.basename(x),sizeBytes:C.length}),v++}catch(C){I.notify(`cannot read ${ci.basename(x)}: ${C.message}`)}}v>0&&(I.setAttachments(De.state().attachments),I.refreshPrompt())},M=async(g="clipboard")=>{let v=g==="primary"?await Bb():await pl();if(!v.ok){I.notify(v.reason);return}if(v.kind==="image"){if(!hn){I.notify("agent does not accept image attachments");return}De.addAttachment(v.attachment),I.setAttachments(De.state().attachments),I.refreshPrompt();return}let x=De.feed({type:"paste",text:v.text});for(let R of x)As(R);I.refreshPrompt()},U=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Q=(g,v)=>{let x=Array.isArray(v)?v:[],R="",C=0;for(let $ of x){if(!$||typeof $!="object")continue;let z=$;z.type==="text"&&typeof z.text=="string"?R+=z.text:z.type==="image"&&(C+=1)}return{messageId:g,text:Te(R),attachmentCount:C}},te=new Map,oe=[],me=new Map,He=new Set,Je=null,rt=()=>{let g=[...te.values()],v=g.map(U);I.setQueuedPrompts(v),I.setBanner({queued:g.length}),De.setQueue(g.map(x=>x.text))},et=g=>[...te.values()][g]?.messageId;if(qs&&qs.length>0){for(let g of qs){if(g.position===0){V=g.messageId;continue}te.set(g.messageId,Q(g.messageId,g.prompt))}te.size>0&&rt()}let Cs=(g,v,x)=>{I.scrollToBottom(),!Js(g)&&(Kn(g,x),Ys(g,v,x))},Ot=(g,v,x)=>{if(I.scrollToBottom(),Js(g))return;if(Kn(g,x),!bs||V===void 0){Ys(g,v,x);return}let R=V,C=[];g.length>0&&C.push({type:"text",text:g});for(let D of v)C.push({type:"image",data:D.data,mimeType:D.mimeType});let $={text:g,displayText:x??g,attachments:v,flushed:!1};oe.push($);let z=()=>{let D=oe.indexOf($);D>=0&&oe.splice(D,1),$.messageId!==void 0&&me.delete($.messageId)};w.request("hydra-acp/prompt/amend",{sessionId:le,targetMessageId:R,prompt:C}).then(D=>{let Z=D;if(Z.amended&&Z.reason==="ok"){ee(1);return}if(z(),Z.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),De.setBuffer(g,v),I.refreshPrompt();return}if(Z.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),De.setBuffer(g,v),I.refreshPrompt();return}if(Z.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),De.setBuffer(g,v),I.refreshPrompt();return}}).catch(D=>{z(),I.notify(`amend failed: ${D.message}`),De.setBuffer(g,v),I.refreshPrompt()})},Rs=async g=>{if(ks.length===0){I.notify("no modes advertised by agent");return}let v=I.currentModeId(),x=ks.findIndex($=>$.id===v),R=x===-1?0:(x+1)%ks.length,C=ks[R]?.id;if(C){I.setBanner({currentMode:C});try{await w.request("session/set_mode",{sessionId:le,modeId:C})}catch($){I.notify(`set_mode failed: ${$.message}`)}}},Js=g=>{let v=g.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
257
+ `))return!1;let x=v.indexOf(" ");switch(x===-1?v:v.slice(0,x)){case"/quit":case"/exit":return Cr(),!0;case"/clear":return Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Mn=null,yn.clear(),Ts.clear(),Es.clear(),Pr.clear(),Qs.clear(),Xn.clear(),I.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let $ of Lo)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"});if(Ws.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let $ of Ws)C.push({prefix:" ",body:` ${$.name.padEnd(12)} ${$.description??""}`,bodyStyle:"info"})}return I.appendLines(C),!0}case"/agent":{let C=x===-1?"":v.slice(x+1).trim(),$=Ze();if(!$)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let D=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let Z of $.options){let Re=Z.value===$.currentValue?"* ":" ";D.push({prefix:" ",body:`${Re}${Z.value.padEnd(16)} ${Z.name}`,bodyStyle:"info"})}return I.appendLines(D),!0}let z=$.options.find(D=>D.value===C)?.value;if(!z){let D=C.toLowerCase(),Z=$.options.filter(Re=>Re.value.toLowerCase().startsWith(D));Z.length===1&&(z=Z[0].value)}return z?z===$.currentValue?(I.notify(`already on agent ${z}`),!0):(I.notify(`switching to ${z}\u2026`),w.request("session/set_config_option",{sessionId:le,configId:"agent",value:z}).catch(D=>{I.notify(`set_config_option failed: ${D.message}`)}),!0):(I.notify(`unknown agent: ${C}`),!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 Ft().catch(C=>{ie({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=x===-1?"":v.slice(x+1).trim();return C?C==="next"||C==="prev"?(Er(C).catch($=>{I.notify(`session ${C} failed: ${$.message}`)}),!0):(Ko(C).catch($=>{I.notify(`session switch failed: ${$.message}`)}),!0):(Ft().catch($=>{ie({src:"switch-session-failed",stack:$ instanceof Error?$.stack??$.message:String($)})}),!0)}case"/rename":{let C=x===-1?"":v.slice(x+1).trim(),$=C.length>0?`/hydra title ${C}`:"/hydra title";return Kn(v,v),Ys($,[],v),!0}case"/btw":{let C=x===-1?"":v.slice(x+1).trim();if(!C)return I.isOverlayOpen()?(_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(le==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let $=N;_&&(_.cancel(),_=null);let z=null;F!==null&&!B?z=F:F!==null&&(fs(t,F).catch(()=>{}),F=null),B=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let D=new ll({getMaxWidth:()=>{let ae=I.width();return ae>0?ae:void 0}});D.on("changed",()=>{I.setBtwOverlayContent(D.getLines())});let Z={};D.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let Re=ae=>{D.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},Se={};return z!==null&&(Se.reuseSessionId=z),Pb(t,le,C,Se).then(ae=>{if($!==N){ae.cancel();return}_=ae,F=ae.sessionId,I.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",we=>{if($===N)if(we.kind==="update"){D.append(we.update);let ot=cs(we.update);if(ot&&ot.kind==="usage-update"){let ts=!1;ot.used!==void 0&&Z.used!==ot.used&&(Z.used=ot.used,ts=!0),ot.size!==void 0&&Z.size!==ot.size&&(Z.size=ot.size,ts=!0),ot.costAmount!==void 0&&Z.costAmount!==ot.costAmount&&(Z.costAmount=ot.costAmount,ts=!0),ot.costCurrency!==void 0&&Z.costCurrency!==ot.costCurrency&&(Z.costCurrency=ot.costCurrency,ts=!0),ts&&I.setBtwOverlayMeta({usage:{...Z}})}}else we.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),_=null):we.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),_=null,F=null):we.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Re(`btw errored: ${we.error.message}`),F!==null&&fs(t,F).catch(()=>{}),_=null,F=null)})}).catch(ae=>{if($!==N)return;let we=ae instanceof Error?ae.message:String(ae);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Re(`btw startup failed: ${we}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${we}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(le==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=x===-1?"":v.slice(x+1).trim(),$=le;return(async()=>{try{let z=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent($)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!z.ok){let we=await z.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${z.status} ${we}`.trim(),bodyStyle:"info"}]);return}let D=await z.text(),Z=new Date().toISOString().replace(/[:.]/g,"-"),Re=`hydra-${pt($)}-${Z}.md`,Se=C.length>0?tt(C):Re,ae=ci.resolve(Se);await Lp.mkdir(ci.dirname(ae),{recursive:!0}),await Lp.writeFile(ae,D,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(z){I.appendLines([{prefix:" ",body:`/export failed: ${z.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Ys=async(g,v,x)=>{let R=[];g.length>0&&R.push({type:"text",text:g});for(let Se of v)R.push({type:"image",data:Se.data,mimeType:Se.mimeType});ee(1);let C={text:g,displayText:x??g,attachments:v,flushed:!1};oe.push(C),Wn=!1;let $=!1,z=null,D=Se=>{typeof ce<"u"&&ce!==null&&ce.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Se,bodyStyle:"tool-status-fail"}])},Z=!1;Ct={text:g,attachments:v,cancel:()=>{if(Wn){Wn=!1,Z=!0,D("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),w.request("hydra-acp/session/force_cancel",{sessionId:le}).catch(ae=>{D(`force-stop failed: ${ae.message}`)});return}if($)return;$=!0,w.notify("session/cancel",{sessionId:le}).catch(()=>{});let Se=Date.now();z=setTimeout(()=>{Ct!==null&&(li>=Se||(Wn=!0,D("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Po)}};let Re;try{let Se=await w.request("session/prompt",{sessionId:le,prompt:R});Se&&typeof Se.stopReason=="string"&&(Re=Se.stopReason)}catch(Se){let ae=oe.indexOf(C);ae>=0&&oe.splice(ae,1),C.messageId!==void 0&&me.delete(C.messageId),Z?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:Se.message,bodyStyle:"tool-status-fail"}])}finally{if(Ct=null,z!==null&&(clearTimeout(z),z=null),ee(-1),C.flushed&&Je===C){let Se=C.messageId!==void 0&&He.has(C.messageId);Se&&C.messageId!==void 0&&He.delete(C.messageId);let ae={kind:"turn-complete"};Re!==void 0&&(ae.stopReason=Re),Se&&(ae.amended=!0),E(ae),Je=null}if(Gt!==null){let{text:Se,attachments:ae}=Gt;Gt=null,De.state().buffer.every(ot=>ot==="")&&(De.setBuffer(Se,ae),I.refreshPrompt())}}},Ye=new Map,yn=new Map,Ts=new Map,Wt=new Map,tn=[],Vs=0,Lt=`tools:${Vs}`,Es=new Map,Pr=new Map,vi=new Set,Mr=new Map,Qs=new Map,Xn=new Map,qe=null,nn=null,Mn=null,Zn=null,Gs=null,Fl=e.tui.maxToolItems,Jo=e.tui.maxPlanItems,Xs=()=>({maxPlanItems:Gs??i.planExpanded?1/0:Jo}),Si=()=>{if(Zn===null)return;let g=pr(Zn,Xs());g.length>0&&I.upsertLines("plan",[{body:""},...g])},L="",K=null,ue=0,J=()=>{if(K===null)return;let g=I.width(),v=hr(L,g>0?{maxWidth:g}:void 0);v.length!==0&&I.upsertLines(K,v)},he=g=>{g.length!==0&&(K===null&&(I.ensureSeparator(),K=`agent:${ue}`,ue+=1,L=""),L+=g,J())},de=()=>{K=null,L=""},Pe="",Ae=null,ze=0,dt=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),sn=()=>{if(Ae===null||Pe.length===0)return;let g=go(Pe);g.length!==0&&I.upsertLines(Ae,g)},es=g=>{let v=Qs.get(g);if(v===void 0)return[];let x=go(v.text);return v.workerTaskId&&x.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"dim"}),x},gt=(g,v)=>{g.length!==0&&(Ae===null&&(I.ensureSeparator("thought"),Ae=`thought:${ze}`,ze+=1,Pe=""),Pe+=g,Qs.set(Ae,{text:Pe,workerTaskId:v}),sn())},xe=()=>{Ae=null,Pe=""},St=g=>tP({...g,collapsedLimit:Fl}),_n=g=>Pr.get(g)??i.toolsExpanded,it=()=>{if(qe===null)return;let{lines:g,rowOwners:v}=St({order:tn,states:Ye,startedAt:qe,endedAt:nn,stopReason:Mn,expanded:_n(Lt),perToolExpanded:vi});I.upsertLines(Lt,g),Mr.set(Lt,v)},$n=g=>{let v=Es.get(g);if(!v)return;let{lines:x,rowOwners:R}=St({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:_n(g),perToolExpanded:vi});I.upsertLines(g,x),Mr.set(g,R)},_r=()=>{qe!==null&&!Es.has(Lt)&&it();for(let g of Es.keys())$n(g)},Yo=()=>{qe!==null&&Es.set(Lt,{order:[...tn],states:new Map(Ye),startedAt:qe,endedAt:nn??Date.now(),stopReason:Mn,rowOwners:Mr.get(Lt)??[]})},hd=()=>{Vs+=1,Lt=`tools:${Vs}`,qe=Date.now(),nn=null,Mn=null,it()};function Vo(g){if(!g||typeof g!="object")return null;let v=g,x=Array.isArray(v.content)?v.content:void 0;if(!x)return null;let R=[],C=$=>{if(typeof $=="string"){R.push({text:wt($)});return}if($&&typeof $=="object"){let z=$;typeof z.__hydraBlob=="string"&&R.push({hash:z.__hydraBlob})}};for(let $ of x){if(!$||typeof $!="object")continue;let z=$;if(z.type==="content"&&z.content&&typeof z.content=="object"){let D=z.content;if(D.text!==void 0){C(D.text);continue}}if(z.type==="text"&&z.text!==void 0){C(z.text);continue}z.text!==void 0&&C(z.text)}return R.length>0?R:null}let Ke=(g,v)=>{let x=v.map($=>"text"in $?$.text:"").join(`
258
+ `);if(x.length===0)return;let{text:R,truncated:C}=nw(x);g.resultText=R,g.resultTruncated=C},yt=new Set,$r=(g,v)=>{!v.some(R=>"hash"in R)||yt.has(g)||(yt.add(g),(async()=>{let R=await Promise.all(v.map(async $=>"text"in $?$:{text:await Ol($.hash)??""}));yt.delete(g);let C=Ye.get(g);if(!C)for(let $ of Es.values()){let z=$.states.get(g);if(z){C=z;break}}if(C){Ke(C,R),Ye.has(g)&&it();for(let[$,z]of Es)z.states.has(g)&&$n($);I.repaintNow()}})().catch(()=>{yt.delete(g)}))},Qo=(g,v,x,R,C,$,z,D,Z,Re)=>{let Se=!Ye.has(g),ae=Ye.get(g),we=ae??{initialTitle:v??"tool",latestTitle:v??"tool",status:x??"pending",startedAt:Date.now()};if(!ae&&Z!==void 0&&(we.workerTaskId=Z),ae&&v!==void 0&&(we.latestTitle=v),$!==void 0&&we.detail===void 0&&(we.detail=$),z!==void 0&&we.detailFull===void 0&&(we.detailFull=z),D!==void 0&&D.length>0&&(we.locations=D),ae&&x!==void 0&&(we.status=x),ae||(we.status=x??"pending"),we.endedAt===void 0&&Tf(we.status)&&(we.endedAt=Date.now()),R!==void 0&&(we.errorText=R),C!==void 0&&(we.editDiff=C),Re!==void 0){let ot=Vo(Re);ot!==null&&(Ke(we,ot),ot.some(ts=>"hash"in ts)&&$r(g,ot))}Ye.set(g,we),Se&&(qe===null&&(Vs+=1,Lt=`tools:${Vs}`,qe=Date.now(),nn=null,Mn=null),tn.push(g))},Ol=async g=>{try{let v=await w.request("hydra-acp/session/tool_content",{sessionId:le,hash:g});return typeof v?.content=="string"?v.content:null}catch{return null}},md=new Set,eS=(g,v)=>{md.has(g)||v.oldRef===void 0&&v.newRef===void 0||(md.add(g),(async()=>{let[x,R]=await Promise.all([v.oldRef?Ol(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?Ol(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&x===null||v.newRef!==void 0&&R===null){md.delete(g);let Re=Cf(v,"diff",{deferredStatus:"error"});Re.length>0&&(I.upsertLines(`editdiff:${g}`,Re),I.repaintNow());return}let $={...v.path!==void 0?{path:v.path}:{},oldText:x??"",newText:R??""};yn.set(g,$);let z=Ye.get(g);z?.editDiff&&(z.editDiff=$),md.delete(g);let D=Ts.get(g),Z=D===void 0?i.showFileUpdates:D?"diff":"edit";Z!=="none"&&(gd(g,$,Z==="diff"?"diff":"edit"),I.repaintNow())})())},gd=(g,v,x)=>{let R=`editdiff:${g}`,C=Cf(v,x);if(C.length===0){I.removeKey(R);return}I.upsertLines(R,C),x==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&I.notifyWhenVisible(R)},tS=g=>{if(!g.startsWith("editdiff:"))return;let v=g.slice(9),x=yn.get(v);x&&(x.oldRef!==void 0||x.newRef!==void 0)&&eS(v,x)},Wp=g=>{let v=`editdiff:${g}`,x=i.showFileUpdates,R=Ye.get(g),C;if(x==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let z=Ts.get(g);C=z!==void 0?z?"diff":"edit":x==="diff"?"diff":"edit"}if(C===null){I.removeKey(v);return}let $=R.editDiff;yn.set(g,$),gd(g,$,C)},nS=()=>{let g=i.showFileUpdates;for(let[v,x]of yn){let R=`editdiff:${v}`,C=Ts.get(v),$=C===void 0?g:C?"diff":"edit";if($==="none"){I.removeKey(R);continue}gd(v,x,$==="diff"?"diff":"edit")}},sS=g=>{if(!g.path)return null;let v=wt(g.oldText).split(`
259
259
  `),x=wt(g.newText).split(`
260
- `),R=0,C=Math.min(v.length,x.length);for(;R<C&&v[R]===x[R];)R++;let $=x[R];if(!$)return null;let z=ci.isAbsolute(g.path)?g.path:ci.resolve(Ne,g.path),D;try{D=LE(z,"utf8")}catch{return null}let Z=D.split(`
261
- `);for(let Re=0;Re<Z.length;Re++)if(Z[Re]===$)return Re+1;return null},nS=(g,v)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),R=yn.get(x),$=Ye.get(x)?.locations?.[0],z=$?.path??R?.path;if(!z)return!1;let D=null;$?.line!==void 0?D=$.line:R&&(D=tS(R));let Z=D===null?"":`:${D}`;return I.tryOpenPathString(z+Z)}if(g.startsWith("tools:")){if(v===0)return!1;let x=Mr.get(g),R=x?x[v]:void 0;if(!R)return!1;let C=Ye.get(R),$=C?.locations?.[0];if($){let D=$.line===void 0?"":`:${$.line}`;if(I.tryOpenPathString($.path+D))return!0}let z=C?.detailFull??C?.detail;if(z)return I.tryOpenPathString(z)}return!1},sS=(g,v)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),R=yn.get(x);if(!R)return;let C=Rs.get(x)??i.showFileUpdates==="diff";Rs.set(x,!C),gd(x,R,C?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(Zn===null)return;Gs=!(Gs??i.planExpanded),Si(),I.repaintNow();return}if(g.startsWith("tools:")){if(v===0){let C=Pr.get(g)??i.toolsExpanded;Pr.set(g,!C),g===Lt&&qe!==null?it():_n(g),I.repaintNow();return}let x=Mr.get(g);if(!x)return;let R=x[v];if(!R)return;QE(R,vi),_n(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Qs.has(g))return;let x=Xn.get(g);if(x!==void 0){Xn.delete(g),I.setRunCollapsed(x,!1,es(g)),I.repaintNow();return}let R=I.contiguousRun(g,new Set(Qs.keys()));if(R.length===0)return;let C=R[0];Xn.set(C,R),I.setRunCollapsed(R,!0,[dt()]),I.repaintNow();return}};S=(g,v)=>{if(g.kind==="available-commands"){Ws=g.commands,ad();return}if(g.kind==="available-modes"){Ss=g.modes;return}if(g.kind==="config-options"){xr=g.options;let R=g.options.find($=>$.id==="agent");R&&R.currentValue&&R.currentValue!==at&&(at=R.currentValue,I.setSessionbar({agent:R.currentValue}));let C=g.options.find($=>$.id==="mode");C&&(Ss=C.options.map($=>({id:$.value,name:$.name??$.value,...$.description!==void 0?{description:$.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!==at&&(at=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 R=!1;g.used!==void 0&&Tt.used!==g.used&&(Tt.used=g.used,R=!0),g.size!==void 0&&Tt.size!==g.size&&(Tt.size=g.size,R=!0),g.costAmount!==void 0&&Tt.costAmount!==g.costAmount&&(Tt.costAmount=g.costAmount,R=!0),g.costCurrency!==void 0&&Tt.costCurrency!==g.costCurrency&&(Tt.costCurrency=g.costCurrency,R=!0),R&&I.setSessionbar({usage:{...Tt}});return}if(g.kind==="user-text"){We&&Kn(g.text),de(),xe(),qe!==null&&(nn=Date.now(),it()),Je=null,I.ensureSeparator();let R=pr(g);R.length>0&&I.appendLines(R),Yo(),I.clearKey("plan"),Zn=null,Gs=null,Ye.clear(),Wt.clear(),tn.length=0,nn=null,hd(),I.redraw();return}if(g.kind==="agent-text"){xe(),K===null&&H(g.workerTaskId),he(g.text);return}if(g.kind==="agent-thought"){de(),Ae===null&&H(g.workerTaskId),gt(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),xe();let R=Wt.get(g.toolCallId),C={plan:g.plan??R?.plan??"",status:g.status??R?.status};if(Wt.set(g.toolCallId,C),C.plan.length===0)return;let $=aw(C);$.length>0&&I.upsertLines(g.toolCallId,$);return}if(g.kind==="tool-call"){de(),xe(),Ye.has(g.toolCallId)||H(g.workerTaskId),Qo(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),it(),Wp(g.toolCallId);return}if(g.kind==="plan"){de(),xe(),Zn=g;let R=pr(g,Xs());R.length>0&&I.upsertLines("plan",[{body:""},...R]);let C=g.entries.length>0&&g.entries.every($=>($.status??"pending")==="completed");I.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){de(),xe(),Qo(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),g.upstreamInterrupted&&(Ee=!0),it(),Wp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let x=pr(g);if(x.length>0&&I.appendLines(x),g.kind==="turn-complete"){V=void 0,de(),xe();let R=g.amended?"amended":g.stopReason;if(!g.amended&&Ee&&(R===void 0||R==="end_turn")&&(R="error"),Zn!==null&&R!==void 0&&R!=="end_turn"){let C=pr({...Zn,stopped:!0,amended:g.amended===!0},Xs());C.length>0&&I.upsertLines("plan",[{body:""},...C])}Zn=null,Gs=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),qe!==null?(nn=Date.now(),Pn=R??null,it(),Yo()):R!==void 0&&R!=="end_turn"&&R!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${R}`,bodyStyle:"tool-status-fail"}]),Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Pn=null,Ee=!1,I.ensureSeparator(),Pv({pendingTurns:j,queueSize:te.size,ownTurnInFlight:Ct!==null,hasInFlightHead:V!==void 0,replayDraining:A,amended:g.amended===!0})&&ee(-j)}};let zp=b;b=[];let yd=[];for(let{event:g}of zp)g.kind==="user-text"&&typeof g.text=="string"&&yd.push(g.text);I.pauseRepaint(),A=!0;try{for(let{event:g,rawUpdate:v}of zp)S(g,v)}finally{A=!1,I.resumeRepaint()}if(yd.length>0){let g=Ju(jt,yd);g!==jt&&(jt=g,mn=Ju(mn,yd),De.setHistory(Yd(Qt,mn)),Wr(vs,jt).catch(()=>{}))}We=!0,(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json(),x=v.compactionState?.status;if(x==="requested"||x==="running"?I.setCompactionIndicator("compacting..."):(x==="swap_pending"||x==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!Fo||v.shouldCompact!==!0)return;let R=v.approxTokens??0;G=!0,I.setCompactionPrompt({message:`This session has ~${xg(R)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rd()):v.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),zn!==void 0&&j>0?(ye=zn,I.setBanner({status:"busy",elapsedMs:Date.now()-zn}),Be===null&&(Be=gs()),qe===null&&hd(),qe=zn,it()):zn===void 0&&j>0&&ee(-j);let rS=()=>{if(Ce){let g=Ce.resolve;Ce=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),xe()},Kp=()=>{qe!==null&&(nn=Date.now(),Pn="reconnect-recovery-failed",it(),Yo(),Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Pn=null)};return m=g=>{ie({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},h=async()=>{if(ie({src:"reconnect",step:"begin",sessionId:le}),t.isLocal)try{let D=await Bt(await Ie());(D.baseUrl!==t.baseUrl||D.wsUrl!==t.wsUrl)&&(ie({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:D.baseUrl}),t.baseUrl=D.baseUrl,t.wsUrl=D.wsUrl,t.display=D.display)}catch(D){ie({src:"reconnect",step:"target-refresh-failed",message:D instanceof Error?D.message:String(D)})}rS();let g={jsonrpc:"2.0",id:`tui-reinit-${$v()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ve}}};ie({src:"reconnect",step:"initialize-send"});try{await y.request(g),ie({src:"reconnect",step:"initialize-ok"})}catch(D){ie({src:"reconnect",step:"initialize-fail",message:D.message})}let v=fn!==void 0,x={jsonrpc:"2.0",id:`tui-reattach-${$v()}`,method:"session/attach",params:{sessionId:le,historyPolicy:v?"after_message":"none",...v?{afterMessageId:fn}:{},clientInfo:{name:"hydra-acp-tui",version:ve},...(()=>{let D={};return At!==void 0&&(D.resume={upstreamSessionId:At,agentId:at,cwd:Ne}),e.tui.toolContent==="references"&&(D.toolContent="references"),Object.keys(D).length>0?{_meta:{[Mt]:D}}:{}})()}};pn=[];let R,C,$;ie({src:"reconnect",step:"attach-send",useAfterMessage:v,lastSeenMessageId:fn});try{let D=await y.request(x);if(ie({src:"reconnect",step:"attach-resp",hasError:!!D.error}),D.error)throw new Error(D.error.message);$=Ev(D.result),R=$.appliedPolicy,$.clientId!==void 0&&(Cn=$.clientId)}catch(D){C=D,ie({src:"reconnect",step:"attach-fail",message:C.message})}let z=pn??[];if(pn=null,C)Kp(),I.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(v&&R!=="after_message")Kp(),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{A=!0;try{for(let D of z)Ht(D)}finally{A=!1}}if($){let D=Mv({daemonTurnStartedAt:$.turnStartedAt,pendingTurns:j});D.pendingTurnsDelta!==0&&ee(D.pendingTurnsDelta),D.banner==="busy"&&D.busySince!==void 0?(ye=D.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-D.busySince}),Be===null&&(Be=gs())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:j>0?"busy":"ready",elapsedMs:j>0?0:void 0});ie({src:"reconnect",step:"end"})},w.onClose(g=>{g&&n.red(`
260
+ `),R=0,C=Math.min(v.length,x.length);for(;R<C&&v[R]===x[R];)R++;let $=x[R];if(!$)return null;let z=ci.isAbsolute(g.path)?g.path:ci.resolve(Ne,g.path),D;try{D=DE(z,"utf8")}catch{return null}let Z=D.split(`
261
+ `);for(let Re=0;Re<Z.length;Re++)if(Z[Re]===$)return Re+1;return null},rS=(g,v)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),R=yn.get(x),$=Ye.get(x)?.locations?.[0],z=$?.path??R?.path;if(!z)return!1;let D=null;$?.line!==void 0?D=$.line:R&&(D=sS(R));let Z=D===null?"":`:${D}`;return I.tryOpenPathString(z+Z)}if(g.startsWith("tools:")){if(v===0)return!1;let x=Mr.get(g),R=x?x[v]:void 0;if(!R)return!1;let C=Ye.get(R),$=C?.locations?.[0];if($){let D=$.line===void 0?"":`:${$.line}`;if(I.tryOpenPathString($.path+D))return!0}let z=C?.detailFull??C?.detail;if(z)return I.tryOpenPathString(z)}return!1},iS=(g,v)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),R=yn.get(x);if(!R)return;let C=Ts.get(x)??i.showFileUpdates==="diff";Ts.set(x,!C),gd(x,R,C?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(Zn===null)return;Gs=!(Gs??i.planExpanded),Si(),I.repaintNow();return}if(g.startsWith("tools:")){if(v===0){let C=Pr.get(g)??i.toolsExpanded;Pr.set(g,!C),g===Lt&&qe!==null?it():$n(g),I.repaintNow();return}let x=Mr.get(g);if(!x)return;let R=x[v];if(!R)return;ZE(R,vi),$n(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Qs.has(g))return;let x=Xn.get(g);if(x!==void 0){Xn.delete(g),I.setRunCollapsed(x,!1,es(g)),I.repaintNow();return}let R=I.contiguousRun(g,new Set(Qs.keys()));if(R.length===0)return;let C=R[0];Xn.set(C,R),I.setRunCollapsed(R,!0,[dt()]),I.repaintNow();return}};S=(g,v)=>{if(g.kind==="available-commands"){Ws=g.commands,ad();return}if(g.kind==="available-modes"){ks=g.modes;return}if(g.kind==="config-options"){xr=g.options;let R=g.options.find($=>$.id==="agent");R&&R.currentValue&&R.currentValue!==at&&(at=R.currentValue,I.setSessionbar({agent:R.currentValue}));let C=g.options.find($=>$.id==="mode");C&&(ks=C.options.map($=>({id:$.value,name:$.name??$.value,...$.description!==void 0?{description:$.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!==at&&(at=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 R=!1;g.used!==void 0&&Tt.used!==g.used&&(Tt.used=g.used,R=!0),g.size!==void 0&&Tt.size!==g.size&&(Tt.size=g.size,R=!0),g.costAmount!==void 0&&Tt.costAmount!==g.costAmount&&(Tt.costAmount=g.costAmount,R=!0),g.costCurrency!==void 0&&Tt.costCurrency!==g.costCurrency&&(Tt.costCurrency=g.costCurrency,R=!0),R&&I.setSessionbar({usage:{...Tt}});return}if(g.kind==="user-text"){We&&Kn(g.text),de(),xe(),qe!==null&&(nn=Date.now(),it()),Je=null,I.ensureSeparator();let R=pr(g);R.length>0&&I.appendLines(R),Yo(),I.clearKey("plan"),Zn=null,Gs=null,Ye.clear(),Wt.clear(),tn.length=0,nn=null,hd(),I.redraw();return}if(g.kind==="agent-text"){xe(),K===null&&H(g.workerTaskId),he(g.text);return}if(g.kind==="agent-thought"){de(),Ae===null&&H(g.workerTaskId),gt(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),xe();let R=Wt.get(g.toolCallId),C={plan:g.plan??R?.plan??"",status:g.status??R?.status};if(Wt.set(g.toolCallId,C),C.plan.length===0)return;let $=dw(C);$.length>0&&I.upsertLines(g.toolCallId,$);return}if(g.kind==="tool-call"){de(),xe(),Ye.has(g.toolCallId)||H(g.workerTaskId),Qo(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),it(),Wp(g.toolCallId);return}if(g.kind==="plan"){de(),xe(),Zn=g;let R=pr(g,Xs());R.length>0&&I.upsertLines("plan",[{body:""},...R]);let C=g.entries.length>0&&g.entries.every($=>($.status??"pending")==="completed");I.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){de(),xe(),Qo(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,v),g.upstreamInterrupted&&(Ee=!0),it(),Wp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let x=pr(g);if(x.length>0&&I.appendLines(x),g.kind==="turn-complete"){V=void 0,de(),xe();let R=g.amended?"amended":g.stopReason;if(!g.amended&&Ee&&(R===void 0||R==="end_turn")&&(R="error"),Zn!==null&&R!==void 0&&R!=="end_turn"){let C=pr({...Zn,stopped:!0,amended:g.amended===!0},Xs());C.length>0&&I.upsertLines("plan",[{body:""},...C])}Zn=null,Gs=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),qe!==null?(nn=Date.now(),Mn=R??null,it(),Yo()):R!==void 0&&R!=="end_turn"&&R!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${R}`,bodyStyle:"tool-status-fail"}]),Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Mn=null,Ee=!1,I.ensureSeparator(),Mv({pendingTurns:j,queueSize:te.size,ownTurnInFlight:Ct!==null,hasInFlightHead:V!==void 0,replayDraining:A,amended:g.amended===!0})&&ee(-j)}};let zp=b;b=[];let yd=[];for(let{event:g}of zp)g.kind==="user-text"&&typeof g.text=="string"&&yd.push(g.text);I.pauseRepaint(),A=!0;try{for(let{event:g,rawUpdate:v}of zp)S(g,v)}finally{A=!1,I.resumeRepaint()}if(yd.length>0){let g=Ju(jt,yd);g!==jt&&(jt=g,mn=Ju(mn,yd),De.setHistory(Yd(Qt,mn)),Wr(Ss,jt).catch(()=>{}))}We=!0,(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json(),x=v.compactionState?.status;if(x==="requested"||x==="running"?I.setCompactionIndicator("compacting..."):(x==="swap_pending"||x==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!Fo||v.shouldCompact!==!0)return;let R=v.approxTokens??0;G=!0,I.setCompactionPrompt({message:`This session has ~${xg(R)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(le)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let v=await g.json();v.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rd()):v.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),zn!==void 0&&j>0?(ye=zn,I.setBanner({status:"busy",elapsedMs:Date.now()-zn}),Be===null&&(Be=ys()),qe===null&&hd(),qe=zn,it()):zn===void 0&&j>0&&ee(-j);let oS=()=>{if(Ce){let g=Ce.resolve;Ce=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),xe()},Kp=()=>{qe!==null&&(nn=Date.now(),Mn="reconnect-recovery-failed",it(),Yo(),Ye.clear(),Wt.clear(),tn.length=0,qe=null,nn=null,Mn=null)};return m=g=>{ie({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},h=async()=>{if(ie({src:"reconnect",step:"begin",sessionId:le}),t.isLocal)try{let D=await Bt(await Ie());(D.baseUrl!==t.baseUrl||D.wsUrl!==t.wsUrl)&&(ie({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:D.baseUrl}),t.baseUrl=D.baseUrl,t.wsUrl=D.wsUrl,t.display=D.display)}catch(D){ie({src:"reconnect",step:"target-refresh-failed",message:D instanceof Error?D.message:String(D)})}oS();let g={jsonrpc:"2.0",id:`tui-reinit-${Fv()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ve}}};ie({src:"reconnect",step:"initialize-send"});try{await y.request(g),ie({src:"reconnect",step:"initialize-ok"})}catch(D){ie({src:"reconnect",step:"initialize-fail",message:D.message})}let v=fn!==void 0,x={jsonrpc:"2.0",id:`tui-reattach-${Fv()}`,method:"session/attach",params:{sessionId:le,historyPolicy:v?"after_message":"none",...v?{afterMessageId:fn}:{},clientInfo:{name:"hydra-acp-tui",version:ve},...(()=>{let D={};return At!==void 0&&(D.resume={upstreamSessionId:At,agentId:at,cwd:Ne}),e.tui.toolContent==="references"&&(D.toolContent="references"),Object.keys(D).length>0?{_meta:{[Mt]:D}}:{}})()}};pn=[];let R,C,$;ie({src:"reconnect",step:"attach-send",useAfterMessage:v,lastSeenMessageId:fn});try{let D=await y.request(x);if(ie({src:"reconnect",step:"attach-resp",hasError:!!D.error}),D.error)throw new Error(D.error.message);$=Pv(D.result),R=$.appliedPolicy,$.clientId!==void 0&&(Rn=$.clientId)}catch(D){C=D,ie({src:"reconnect",step:"attach-fail",message:C.message})}let z=pn??[];if(pn=null,C)Kp(),I.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(v&&R!=="after_message")Kp(),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{A=!0;try{for(let D of z)Ht(D)}finally{A=!1}}if($){let D=_v({daemonTurnStartedAt:$.turnStartedAt,pendingTurns:j});D.pendingTurnsDelta!==0&&ee(D.pendingTurnsDelta),D.banner==="busy"&&D.busySince!==void 0?(ye=D.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-D.busySince}),Be===null&&(Be=ys())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:j>0?"busy":"ready",elapsedMs:j>0?0:void 0});ie({src:"reconnect",step:"end"})},w.onClose(g=>{g&&n.red(`
262
262
  connection lost: ${g.message}
263
- `),Ks(g?1:0)}),process.on("SIGINT",jo),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&As(s.initialPrompt??"",s.initialAttachments??[]),await Do}async function eP(n,e,t,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),s.resolved!==void 0&&(a.resolved=s.resolved),a}if(s.forceNew)return await Bv(n,t,s,i)!=="ok"?null:Lv(s,o,e);if(s.resume){let a=Rv();if(a){let u=(await Dn(t,{all:!0,includeNonInteractive:!0})).find(f=>f.sessionId===a);if(u)return{sessionId:u.sessionId,agentId:u.agentId??"",cwd:u.cwd??o,resolved:u}}let c=await Dn(t,{cwd:o,all:!0}),d=Oc(c,o);return d?{sessionId:d.sessionId,agentId:d.agentId??"",cwd:o,resolved:d}:(n.yellow(`No sessions found for ${o}.
264
- `),null)}for(;;){let a=await Dn(t,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await Qr(t)}catch{}let u=await $p(n,{cwd:o,sessions:a,config:e,target:t,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(u.kind==="abort"||u.kind==="exit")return null;if(u.kind==="new"){u.agentId!==void 0&&(s.agentId=u.agentId,i.lastChosenAgent=u.agentId),u.model!==void 0&&(s.model=u.model),u.prompt!==void 0&&(s.initialPrompt=u.prompt),u.attachments&&u.attachments.length>0&&(s.initialAttachments=u.attachments),u.cwd!==void 0&&(o=u.cwd,s.cwd=u.cwd);let w=u.installStatus,b=await Bv(n,t,s,i,()=>{w&&(w.finalize(),w=void 0)});if(b==="cancel")return w&&w.finalize(),null;if(b==="back"){w&&w.finalize();continue}let S=Lv(s,o,e);return w&&(S.installStatus=w),S}if(u.kind==="fork"){let w=await Uv(n,t,u,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=u.readonly===!0;let f=u.installStatus,p=()=>{f&&(f.finalize(),f=void 0)},h=a.find(w=>w.sessionId===u.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await Dv(n,t,h,u,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(t.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await za(h.cwd)).ok){p();let b=await di(n,h,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(b.kind==="cancel")return null;if(b.kind==="back")continue;let S=u.agentId??h.agentId??"";return{sessionId:u.sessionId,agentId:S,cwd:b.path,resumeHint:{agentId:S,cwd:b.path,upstreamSessionId:""}}}let y={sessionId:u.sessionId,agentId:u.agentId??"",cwd:o};return f&&(y.installStatus=f),h!==void 0&&(y.resolved=h),y}}async function Dv(n,e,t,s,r){for(;;){let i=await av(n,t);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??t.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:t.cwd}}}let o=await Hv(n,e,s.agentId??t.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await di(n,t);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 Hv(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let s;try{s=await Qr(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(s.length===0||s.some(i=>i.id===t))return{kind:"ok",agentId:t,changed:!1};let r=await Ka(n,s,t,{title:"Agent not available here",intro:`Source agent "${t}" 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 Uv(n,e,t,s){let r=s.find(u=>u.sessionId===t.sourceSessionId),i=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,o=t.sourceCwd,a=await Hv(n,e,t.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 di(n,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??t.sourceAgentId??"",l;try{l=await Fc(e,t.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return n.red(`
263
+ `),Ks(g?1:0)}),process.on("SIGINT",jo),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&Cs(s.initialPrompt??"",s.initialAttachments??[]),await Do}async function sP(n,e,t,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),s.resolved!==void 0&&(a.resolved=s.resolved),a}if(s.forceNew)return await Nv(n,t,s,i)!=="ok"?null:Bv(s,o,e);if(s.resume){let a=Tv();if(a){let u=(await Dn(t,{all:!0,includeNonInteractive:!0})).find(f=>f.sessionId===a);if(u)return{sessionId:u.sessionId,agentId:u.agentId??"",cwd:u.cwd??o,resolved:u}}let c=await Dn(t,{cwd:o,all:!0}),d=Oc(c,o);return d?{sessionId:d.sessionId,agentId:d.agentId??"",cwd:o,resolved:d}:(n.yellow(`No sessions found for ${o}.
264
+ `),null)}for(;;){let a=await Dn(t,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await Qr(t)}catch{}let u=await $p(n,{cwd:o,sessions:a,config:e,target:t,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(u.kind==="abort"||u.kind==="exit")return null;if(u.kind==="new"){u.agentId!==void 0&&(s.agentId=u.agentId,i.lastChosenAgent=u.agentId),u.model!==void 0&&(s.model=u.model),u.prompt!==void 0&&(s.initialPrompt=u.prompt),u.attachments&&u.attachments.length>0&&(s.initialAttachments=u.attachments),u.cwd!==void 0&&(o=u.cwd,s.cwd=u.cwd);let w=u.installStatus,b=await Nv(n,t,s,i,()=>{w&&(w.finalize(),w=void 0)});if(b==="cancel")return w&&w.finalize(),null;if(b==="back"){w&&w.finalize();continue}let S=Bv(s,o,e);return w&&(S.installStatus=w),S}if(u.kind==="fork"){let w=await jv(n,t,u,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=u.readonly===!0;let f=u.installStatus,p=()=>{f&&(f.finalize(),f=void 0)},h=a.find(w=>w.sessionId===u.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await Hv(n,t,h,u,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(t.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await za(h.cwd)).ok){p();let b=await di(n,h,{defaultCwd:tt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(b.kind==="cancel")return null;if(b.kind==="back")continue;let S=u.agentId??h.agentId??"";return{sessionId:u.sessionId,agentId:S,cwd:b.path,resumeHint:{agentId:S,cwd:b.path,upstreamSessionId:""}}}let y={sessionId:u.sessionId,agentId:u.agentId??"",cwd:o};return f&&(y.installStatus=f),h!==void 0&&(y.resolved=h),y}}async function Hv(n,e,t,s,r){for(;;){let i=await dv(n,t);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??t.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:t.cwd}}}let o=await Uv(n,e,s.agentId??t.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await di(n,t);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 Uv(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let s;try{s=await Qr(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(s.length===0||s.some(i=>i.id===t))return{kind:"ok",agentId:t,changed:!1};let r=await Ka(n,s,t,{title:"Agent not available here",intro:`Source agent "${t}" 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 jv(n,e,t,s){let r=s.find(u=>u.sessionId===t.sourceSessionId),i=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,o=t.sourceCwd,a=await Uv(n,e,t.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 di(n,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??t.sourceAgentId??"",l;try{l=await Fc(e,t.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return n.red(`
265
265
  fork failed: ${u.message}
266
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Lv(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function Bv(n,e,t,s,r){if(t.agentId||await rh())return"ok";let i;try{i=await Qr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Ie(),a=s.lastChosenAgent??o.defaultAgent,c=await Ka(n,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(t.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await Ri(c.agentId)}catch{}return"ok"}function tP(n,e){ie({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Np,YE,VE,Ov,jv=Y(()=>{"use strict";jr();_t();Vf();Ge();ep();Dr();Yr();xa();na();Tb();is();be();Hr();cn();il();Xf();Vd();Ma();Pb();Mb();wv();Pp();Gc();Tp();Cp();sp();Yf();vv();Ap();of();cp();ul();hl();kv();Tv();Il();Ep();_v();or();yo();Np="dismiss";YE=12e4;VE=[["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"],["Alt+P","previous 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"]];Ov=!1});var qv={};Ll(qv,{runTui:()=>Nv});var Wv=Y(()=>{"use strict";jv()});import{readFileSync as nP}from"fs";import{fileURLToPath as sP}from"url";import{dirname as rP,resolve as iP}from"path";var Jp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),oS=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Yp(n){for(let e of Object.keys(n))if(!Jp.has(e)&&!oS.has(e))return e}function Bl(n){let e=[],t={},s=0;for(;s<n.length;){let r=n[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);t[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(Jp.has(o)){t[o]=!0,s+=1;continue}let a=n[s+1];if(a!==void 0&&!a.startsWith("--")){t[o]=a,s+=2;continue}t[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:t}}function aS(n,e){let t=n[e];if(typeof t=="string")return t}function ki(n,e){return n[e]===!0||n[e]==="true"}var dS="HYDRA_ACP_";function cS(n){return dS+n.toUpperCase().replace(/-/g,"_")}function kt(n,e){let t=aS(n,e);return t!==void 0?t:process.env[cS(e)]}Ge();Dr();async function Sh(n,e){let t=typeof n=="string"&&n.trim().length>0?n.trim():void 0;if(t===void 0)return;if(t.startsWith("hydra://")){let i=ql(t);return{target:await bh(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ie();return{target:await Bt(s),sessionId:t,fromUrl:!1}}function eu(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_SESSION;if(typeof t=="string"&&t.length>0)return t}Hr();be();Ge();Es();import*as xh from"fs/promises";async function Ah(n){if(await xh.mkdir(O.home(),{recursive:!0}),await bd(),!await Ai()){let t=xi();await Ci(t),process.stdout.write(`Initialized ${O.authToken()}
266
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Bv(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function Nv(n,e,t,s,r){if(t.agentId||await rh())return"ok";let i;try{i=await Qr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Ie(),a=s.lastChosenAgent??o.defaultAgent,c=await Ka(n,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(t.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await Ri(c.agentId)}catch{}return"ok"}function rP(n,e){ie({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Np,GE,XE,Lv,qv=Y(()=>{"use strict";jr();_t();Vf();Ge();ep();Dr();Yr();xa();na();Eb();os();be();Hr();cn();il();Xf();Vd();Ma();Mb();_b();bv();Pp();Gc();Tp();Cp();sp();Yf();Sv();Ap();of();cp();ul();hl();Iv();Ev();Il();Ep();$v();or();yo();Np="dismiss";GE=12e4;XE=[["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"],["Alt+P","previous 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"]];Lv=!1});var Wv={};Ll(Wv,{runTui:()=>Dv});var zv=Y(()=>{"use strict";qv()});import{readFileSync as iP}from"fs";import{fileURLToPath as oP}from"url";import{dirname as aP,resolve as dP}from"path";var Jp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),dS=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Yp(n){for(let e of Object.keys(n))if(!Jp.has(e)&&!dS.has(e))return e}function Bl(n){let e=[],t={},s=0;for(;s<n.length;){let r=n[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);t[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(Jp.has(o)){t[o]=!0,s+=1;continue}let a=n[s+1];if(a!==void 0&&!a.startsWith("--")){t[o]=a,s+=2;continue}t[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:t}}function cS(n,e){let t=n[e];if(typeof t=="string")return t}function ki(n,e){return n[e]===!0||n[e]==="true"}var lS="HYDRA_ACP_";function uS(n){return lS+n.toUpperCase().replace(/-/g,"_")}function kt(n,e){let t=cS(n,e);return t!==void 0?t:process.env[uS(e)]}Ge();Dr();async function Sh(n,e){let t=typeof n=="string"&&n.trim().length>0?n.trim():void 0;if(t===void 0)return;if(t.startsWith("hydra://")){let i=ql(t);return{target:await bh(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Ie();return{target:await Bt(s),sessionId:t,fromUrl:!1}}function eu(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_SESSION;if(typeof t=="string"&&t.length>0)return t}Hr();be();Ge();Ps();import*as xh from"fs/promises";async function Ah(n){if(await xh.mkdir(O.home(),{recursive:!0}),await bd(),!await Ai()){let t=xi();await Ci(t),process.stdout.write(`Initialized ${O.authToken()}
267
267
  Service token: ${t}
268
268
  `);return}if(ki(n,"rotate-token")){let t=xi();await Ci(t),process.stdout.write(`Rotated token in ${O.authToken()}
269
269
  New token: ${t}
270
270
  `);return}process.stdout.write(`Service token already exists at ${O.authToken()}.
271
271
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
272
- `)}be();Ei();Ge();Es();import{setTimeout as SC}from"timers/promises";import Iy from"chalk";import*as yy from"fs";import*as ls from"fs/promises";import*as wy from"net";import*as ro from"path";import*as by from"tls";import oC from"fastify";import aC from"@fastify/websocket";var Ch="acp.v1";function Rh(n,e){return n.has(Ch)?Ch:!1}Ge();import my from"pino";import dC from"pino-roll";be();import*as Pt from"fs/promises";import{createHash as VS}from"crypto";import{gzip as QS,gunzip as GS}from"zlib";import{promisify as Th}from"util";var Eh=Th(QS),XS=Th(GS),Ph=/^[A-Za-z0-9_-]+$/,ZS=/^[a-f0-9]{64}$/,tu=!0;function Mh(n){tu=n}function xd(n,e){return Ph.test(n)?e===void 0||ZS.test(e):!1}function Ad(n,e){return`${O.toolBlobFile(n,e)}.gz`}async function nu(n,e){if(!xd(n))return null;let t=VS("sha256").update(e,"utf8").digest("hex"),s=Ad(n,t),r=O.toolBlobFile(n,t);for(let a of[s,r])try{return await Pt.access(a),t}catch{}await Pt.mkdir(O.toolsDir(n),{recursive:!0});let i=tu?s:r,o=tu?await Eh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Pt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function oa(n,e){if(!xd(n,e))return null;try{let t=await Pt.readFile(Ad(n,e));return(await XS(t)).toString("utf8")}catch{}try{return await Pt.readFile(O.toolBlobFile(n,e),"utf8")}catch{return null}}async function _h(n,e){if(!xd(n,e))return null;try{return await Pt.readFile(Ad(n,e))}catch{}try{let t=await Pt.readFile(O.toolBlobFile(n,e));return await Eh(t)}catch{return null}}async function $h(n,e,t){if(!xd(n,e))return;let s=Ad(n,e);try{await Pt.access(s);return}catch{}await Pt.mkdir(O.toolsDir(n),{recursive:!0}),await Pt.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Fh(n){Ph.test(n)&&await Pt.rm(O.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}be();Ge();Or();_i();import*as zh from"fs/promises";import*as Rd from"path";import{z as fe}from"zod";be();_i();import*as on from"fs/promises";import*as ss from"path";import{spawn as ok}from"child_process";var du=n=>{process.stderr.write(n+`
272
+ `)}be();Ei();Ge();Ps();import{setTimeout as xC}from"timers/promises";import xy from"chalk";import*as yy from"fs";import*as us from"fs/promises";import*as wy from"net";import*as ro from"path";import*as by from"tls";import dC from"fastify";import cC from"@fastify/websocket";var Ch="acp.v1";function Rh(n,e){return n.has(Ch)?Ch:!1}Ge();import my from"pino";import lC from"pino-roll";be();import*as Pt from"fs/promises";import{createHash as GS}from"crypto";import{gzip as XS,gunzip as ZS}from"zlib";import{promisify as Th}from"util";var Eh=Th(XS),ek=Th(ZS),Ph=/^[A-Za-z0-9_-]+$/,tk=/^[a-f0-9]{64}$/,tu=!0;function Mh(n){tu=n}function xd(n,e){return Ph.test(n)?e===void 0||tk.test(e):!1}function Ad(n,e){return`${O.toolBlobFile(n,e)}.gz`}async function nu(n,e){if(!xd(n))return null;let t=GS("sha256").update(e,"utf8").digest("hex"),s=Ad(n,t),r=O.toolBlobFile(n,t);for(let a of[s,r])try{return await Pt.access(a),t}catch{}await Pt.mkdir(O.toolsDir(n),{recursive:!0});let i=tu?s:r,o=tu?await Eh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Pt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function oa(n,e){if(!xd(n,e))return null;try{let t=await Pt.readFile(Ad(n,e));return(await ek(t)).toString("utf8")}catch{}try{return await Pt.readFile(O.toolBlobFile(n,e),"utf8")}catch{return null}}async function _h(n,e){if(!xd(n,e))return null;try{return await Pt.readFile(Ad(n,e))}catch{}try{let t=await Pt.readFile(O.toolBlobFile(n,e));return await Eh(t)}catch{return null}}async function $h(n,e,t){if(!xd(n,e))return;let s=Ad(n,e);try{await Pt.access(s);return}catch{}await Pt.mkdir(O.toolsDir(n),{recursive:!0}),await Pt.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Fh(n){Ph.test(n)&&await Pt.rm(O.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}be();Ge();Or();_i();import*as zh from"fs/promises";import*as Rd from"path";import{z as fe}from"zod";be();_i();import*as on from"fs/promises";import*as rs from"path";import{spawn as dk}from"child_process";var du=n=>{process.stderr.write(n+`
273
273
  `)};function cu(n){du=n??(e=>process.stderr.write(e+`
274
- `))}async function Hh(n){let e=bn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=O.agentNpmInstallDir(n.agentId,e,n.version),s=uk(n.packageSpec),r=fk(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=ss.join(t,"node_modules",".bin",n.bin);if(await Ur(o))return o;if(await Ur(t)){let u=await Dh(i);if(u)return u.binPath}await ak({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Dh(i);if(a)return a.binPath;let c=await jh(t,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 ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${l}`)}async function ak(n){await on.mkdir(ss.dirname(n.installDir),{recursive:!0});let e=await on.mkdtemp(`${n.installDir}.partial-`);try{du(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),au(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await lk({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await on.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Ur(n.installDir)){await on.rm(e,{recursive:!0,force:!0}).catch(()=>{}),au(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}du(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),au(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await on.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function au(n,e){if(n)try{n(e)}catch{}}var dk=5,ck=25;function lk(n){return Uh(n,0)}async function Uh(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=ok("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){t();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${d})
275
- stderr: ${l}`:`npm install ${n.packageSpec} failed (${d})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<dk)return await new Promise(r=>setTimeout(r,ck*(e+1))),Uh(n,e+1);throw t}}function uk(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function fk(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function jh(n,e){let t=ss.join(n,"node_modules",e,"package.json");try{let s=await on.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Dh(n){let e=ss.join(n.installDir,"node_modules",".bin"),t=ss.join(e,n.hint);if(await Ur(t))return{binName:n.hint,binPath:t};let s=await jh(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=ss.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=ss.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=ss.join(e,n.basename);if(await Ur(r))return{binName:n.basename,binPath:r}}}async function Ur(n){try{return await on.access(n),!0}catch{return!1}}var pk=fe.object({package:fe.string(),bin:fe.string().optional(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),$i=fe.object({archive:fe.string().url().optional(),cmd:fe.string().optional(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),hk=fe.object({"darwin-aarch64":$i.optional(),"darwin-x86_64":$i.optional(),"linux-aarch64":$i.optional(),"linux-x86_64":$i.optional(),"windows-x86_64":$i.optional(),"windows-aarch64":$i.optional()}),mk=fe.object({package:fe.string(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),gk=fe.object({command:fe.string(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),yk=fe.object({command:fe.string().optional(),url:fe.string().optional(),description:fe.string().optional()}),wk=fe.object({npx:pk.optional(),binary:hk.optional(),uvx:mk.optional(),exec:gk.optional()}),bk=fe.object({id:fe.string(),name:fe.string(),version:fe.string().optional(),description:fe.string().optional(),authors:fe.array(fe.string()).optional(),license:fe.string().optional(),icon:fe.string().optional(),repository:fe.string().optional(),website:fe.string().optional(),distribution:wk,onboarding:yk.optional(),requiredEnv:fe.array(fe.string().min(1)).optional()}),qh=fe.object({version:fe.string(),agents:fe.array(bk),extensions:fe.array(fe.unknown()).optional()}),Cd=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;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=>lu(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,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:tt(t.command??e),args:t.args?.map(tt),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:vk(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=qh.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await wn(O.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=qh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await rn(O.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function vk(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function lu(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Fi(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await uu(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function uu(n){let e=bn();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=iu(n.distribution.binary,e);if(s?.cmd){let r=Rd.resolve(O.agentInstallDir(n.id,e,t),s.cmd);if(await Wh(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??lu(n)??s.package,i=O.agentNpmInstallDir(n.id,e,t),o=Rd.join(i,"node_modules",".bin",r);if(await Wh(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Wh(n){try{return await zh.access(n),!0}catch{return!1}}async function vn(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??lu(n)??r.package,a=t.onInstallProgress;return{command:await Hh({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=iu(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${bn()??"this platform"}.`);let i=t.onInstallProgress,o=await Nh({agentId:n.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(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Ak}from"child_process";import*as Fd from"fs";import*as am from"path";_t();function $d(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
274
+ `))}async function Hh(n){let e=vn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=O.agentNpmInstallDir(n.agentId,e,n.version),s=pk(n.packageSpec),r=hk(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=rs.join(t,"node_modules",".bin",n.bin);if(await Ur(o))return o;if(await Ur(t)){let u=await Dh(i);if(u)return u.binPath}await ck({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Dh(i);if(a)return a.binPath;let c=await jh(t,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 ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${l}`)}async function ck(n){await on.mkdir(rs.dirname(n.installDir),{recursive:!0});let e=await on.mkdtemp(`${n.installDir}.partial-`);try{du(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),au(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await fk({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await on.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Ur(n.installDir)){await on.rm(e,{recursive:!0,force:!0}).catch(()=>{}),au(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}du(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),au(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await on.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function au(n,e){if(n)try{n(e)}catch{}}var lk=5,uk=25;function fk(n){return Uh(n,0)}async function Uh(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=dk("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){t();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${d})
275
+ stderr: ${l}`:`npm install ${n.packageSpec} failed (${d})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<lk)return await new Promise(r=>setTimeout(r,uk*(e+1))),Uh(n,e+1);throw t}}function pk(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function hk(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function jh(n,e){let t=rs.join(n,"node_modules",e,"package.json");try{let s=await on.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Dh(n){let e=rs.join(n.installDir,"node_modules",".bin"),t=rs.join(e,n.hint);if(await Ur(t))return{binName:n.hint,binPath:t};let s=await jh(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=rs.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=rs.join(e,i);if(await Ur(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=rs.join(e,n.basename);if(await Ur(r))return{binName:n.basename,binPath:r}}}async function Ur(n){try{return await on.access(n),!0}catch{return!1}}var mk=fe.object({package:fe.string(),bin:fe.string().optional(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),$i=fe.object({archive:fe.string().url().optional(),cmd:fe.string().optional(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),gk=fe.object({"darwin-aarch64":$i.optional(),"darwin-x86_64":$i.optional(),"linux-aarch64":$i.optional(),"linux-x86_64":$i.optional(),"windows-x86_64":$i.optional(),"windows-aarch64":$i.optional()}),yk=fe.object({package:fe.string(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),wk=fe.object({command:fe.string(),args:fe.array(fe.string()).optional(),env:fe.record(fe.string()).optional()}),bk=fe.object({command:fe.string().optional(),url:fe.string().optional(),description:fe.string().optional()}),vk=fe.object({npx:mk.optional(),binary:gk.optional(),uvx:yk.optional(),exec:wk.optional()}),Sk=fe.object({id:fe.string(),name:fe.string(),version:fe.string().optional(),description:fe.string().optional(),authors:fe.array(fe.string()).optional(),license:fe.string().optional(),icon:fe.string().optional(),repository:fe.string().optional(),website:fe.string().optional(),distribution:vk,onboarding:bk.optional(),requiredEnv:fe.array(fe.string().min(1)).optional()}),qh=fe.object({version:fe.string(),agents:fe.array(Sk),extensions:fe.array(fe.unknown()).optional()}),Cd=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;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=>lu(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,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:tt(t.command??e),args:t.args?.map(tt),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:kk(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=qh.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await wn(O.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=qh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await rn(O.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function kk(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function lu(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Fi(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await uu(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function uu(n){let e=vn();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=iu(n.distribution.binary,e);if(s?.cmd){let r=Rd.resolve(O.agentInstallDir(n.id,e,t),s.cmd);if(await Wh(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??lu(n)??s.package,i=O.agentNpmInstallDir(n.id,e,t),o=Rd.join(i,"node_modules",".bin",r);if(await Wh(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Wh(n){try{return await zh.access(n),!0}catch{return!1}}async function Sn(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??lu(n)??r.package,a=t.onInstallProgress;return{command:await Hh({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=iu(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${vn()??"this platform"}.`);let i=t.onInstallProgress,o=await Nh({agentId:n.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(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Rk}from"child_process";import*as Fd from"fs";import*as am from"path";_t();function $d(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
276
276
  `);for(;c!==-1;){let d=t.slice(0,c).trim();if(t=t.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:q.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=t.indexOf(`
277
277
  `)}}),n.on("end",()=>o()),n.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let c=JSON.stringify(a)+`
278
- `;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()}}}jr();be();var Ck=4096,nr=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??Ck,this.killEscalationMs=e.killEscalationMs??Rk,this.logger=e.logger,this.fileLog=Tk(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
278
+ `;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()}}}jr();be();var Tk=4096,nr=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??Tk,this.killEscalationMs=e.killEscalationMs??Ek,this.logger=e.logger,this.fileLog=Pk(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
279
279
  `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=$d(t.stdout,t.stdin);this.connection=new zt(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
280
280
  `),this.connection.fail(new Error(i))}),t.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
281
281
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
282
- stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Ak(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
282
+ stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Rk(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
283
283
  `),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()} ---
284
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},Rk=2e3;function Tk(n){try{let e=O.agentLogFile(n);Fd.mkdirSync(am.dirname(e),{recursive:!0});let t=Fd.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}Od();import*as Kr from"fs/promises";import*as lg from"os";import*as va from"path";import{customAlphabet as YI}from"nanoid";yu();is();Lu();be();Or();import*as _s from"fs/promises";import{z as os}from"zod";var kI=os.object({version:os.literal(1),agentId:os.string(),upstreamSessionId:os.string(),deletedAt:os.string(),upstreamUpdatedAt:os.string().optional(),cwd:os.string().optional(),title:os.string().optional(),reason:os.enum(["user","expired"]).optional(),interactive:os.boolean().optional()}),qd=class{async add(e){let t={version:1,...e};await rn(O.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await _s.access(O.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=O.tombstoneFile(e,t),r=await wn(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return kI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await _s.unlink(O.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await _s.rmdir(O.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await _s.readdir(O.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await _s.readdir(O.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Bm(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as Qm from"fs/promises";_t();cn();Ud();Nd();var AI=12e4;async function Dm(n,e,t){let s=n.timeoutMs??AI,r,i,o=!1;try{let a=(async()=>{r=nr.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ve}}),d=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(l,r.pid),n.modelId){let h=RI(d);if(h.size===0||h.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=CI(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=t(f);if(!p){let h=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function zd(n){let e=ji(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
284
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},Ek=2e3;function Pk(n){try{let e=O.agentLogFile(n);Fd.mkdirSync(am.dirname(e),{recursive:!0});let t=Fd.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}Od();import*as Kr from"fs/promises";import*as lg from"os";import*as va from"path";import{customAlphabet as QI}from"nanoid";yu();os();Lu();be();Or();import*as _s from"fs/promises";import{z as as}from"zod";var xI=as.object({version:as.literal(1),agentId:as.string(),upstreamSessionId:as.string(),deletedAt:as.string(),upstreamUpdatedAt:as.string().optional(),cwd:as.string().optional(),title:as.string().optional(),reason:as.enum(["user","expired"]).optional(),interactive:as.boolean().optional()}),qd=class{async add(e){let t={version:1,...e};await rn(O.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await _s.access(O.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=O.tombstoneFile(e,t),r=await wn(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return xI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await _s.unlink(O.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await _s.rmdir(O.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await _s.readdir(O.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await _s.readdir(O.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Bm(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as Qm from"fs/promises";_t();cn();Ud();Nd();var RI=12e4;async function Dm(n,e,t){let s=n.timeoutMs??RI,r,i,o=!1;try{let a=(async()=>{r=nr.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ve}}),d=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(l,r.pid),n.modelId){let h=EI(d);if(h.size===0||h.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=TI(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=t(f);if(!p){let h=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function zd(n){let e=ji(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
285
285
 
286
286
  ${e}
287
287
 
@@ -293,7 +293,7 @@ ${e}
293
293
 
294
294
  ${Eu}`:`${t}
295
295
 
296
- ${Eu}`;return Dm(n,s,Om)}function CI(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function RI(n){let e=new Set;Nm(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Nm(e,t.availableModels),e}function Nm(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}Du();be();var TI=2,Kd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??TI}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,t){if(this.stopped)return;let s=t?.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 t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(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 t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.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 vn(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=O.sessionDir(e);if(await Qm.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,w,b=0,S,k=Date.now(),A={targetAgentId:r},E=H=>this.opts.onCompactionStateChange?.(e,H,A)??Promise.resolve(),P=H=>{this.opts.broadcastHydraCompaction?.(e,H,A)};await E({status:"requested",requestedAt:k}),P({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let H=await this.opts.histories.load(e,{maxEntries:1/0});if(H.length===y)break;let _=await Hm({agentId:c,cwd:p,plan:l,history:H,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(B,N)=>{E({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:B,pid:N??0}})},onFailure:B=>{S=B}});if(_){let B=Jm(_.synopsis,H);B&&Ym(B)&&(await this.opts.persistSynopsis(e,B,H.length),w=B,b=H.length,S=void 0,await E({status:"running",requestedAt:k,iter:m}),P({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:H.length}),await this.opts.onSynthesisArtifact?.(e,B,b,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Vm(B)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=H.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(w)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${b} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let H=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:k,iter:m,lastError:H}),P({sessionUpdate:"hydra_compaction",phase:"failed",error:H})}}catch(H){let _=H instanceof Error?H.message:String(H);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await E({status:"failed",requestedAt:k,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let h=await zd({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=Jm(h.synopsis,o);m&&Ym(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=${Vm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function Jm(n,e){let t=Wm(e),s=qm(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Ym(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Vm(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}be();import*as Fe from"fs/promises";import{createReadStream as $I}from"fs";import{createGunzip as FI,gzip as OI,gunzip as LI}from"zlib";import{createInterface as BI}from"readline";import{promisify as ng}from"util";function Gm(n){return n==="summary"?"summary":"inline"}var Hu=256;function Xm(n,e){return e!=="summary"?n:n.map(EI)}function EI(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(Zm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Uu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...n,params:{...t,update:i}}}function PI(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function Zm(n){if(PI(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Uu(e.text)),typeof e.content=="string"?t.content=Uu(e.content):e.content&&typeof e.content=="object"&&(t.content=Zm(e.content)),t}function Uu(n){if(typeof n=="string"&&n.length>Hu){let e=n.length-Hu;return`${n.slice(0,Hu)}\u2026[+${e} chars omitted from summary export]`}return n}var MI=2048;function eg(n){let e=new Set,t=s=>{if(tg(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function tg(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function _I(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Wu(n,e){if(!_I(n))return n;let t=n.params,s=t.update,r=await ju(s,e);return{...n,params:{...t,update:r}}}async function ju(n,e){if(typeof n=="string"){if(n.length<=MI)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await ju(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await ju(r,e);return t}return n}async function zu(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await qu(t,e);return s===t?n:{...n,params:s}}async function qu(n,e){if(tg(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await qu(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await qu(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var NI=ng(OI),DI=ng(LI),HI=/^history\.jsonl\.(\d+)(\.gz)?$/,Bn=/^[A-Za-z0-9_-]+$/,UI=1e3,jI=1e7,qI=10,Jd=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??UI,this.archiveMaxBytes=e.archiveMaxBytes??jI,this.archiveTiers=e.archiveTiers??qI}async append(e,t){if(Bn.test(e))return this.enqueue(e,async()=>{await Fe.mkdir(O.sessionDir(e),{recursive:!0});let s=await Wu(t,i=>nu(e,i)),r=JSON.stringify(s)+`
296
+ ${Eu}`;return Dm(n,s,Om)}function TI(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function EI(n){let e=new Set;Nm(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Nm(e,t.availableModels),e}function Nm(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}Du();be();var PI=2,Kd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??PI}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,t){if(this.stopped)return;let s=t?.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 t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(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 t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.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 Sn(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=O.sessionDir(e);if(await Qm.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,w,b=0,S,k=Date.now(),A={targetAgentId:r},E=H=>this.opts.onCompactionStateChange?.(e,H,A)??Promise.resolve(),P=H=>{this.opts.broadcastHydraCompaction?.(e,H,A)};await E({status:"requested",requestedAt:k}),P({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let H=await this.opts.histories.load(e,{maxEntries:1/0});if(H.length===y)break;let _=await Hm({agentId:c,cwd:p,plan:l,history:H,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(B,N)=>{E({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:B,pid:N??0}})},onFailure:B=>{S=B}});if(_){let B=Jm(_.synopsis,H);B&&Ym(B)&&(await this.opts.persistSynopsis(e,B,H.length),w=B,b=H.length,S=void 0,await E({status:"running",requestedAt:k,iter:m}),P({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:H.length}),await this.opts.onSynthesisArtifact?.(e,B,b,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Vm(B)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=H.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(w)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${b} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let H=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:k,iter:m,lastError:H}),P({sessionUpdate:"hydra_compaction",phase:"failed",error:H})}}catch(H){let _=H instanceof Error?H.message:String(H);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await E({status:"failed",requestedAt:k,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let h=await zd({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=Jm(h.synopsis,o);m&&Ym(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=${Vm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function Jm(n,e){let t=Wm(e),s=qm(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Ym(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Vm(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}be();import*as Fe from"fs/promises";import{createReadStream as OI}from"fs";import{createGunzip as LI,gzip as BI,gunzip as NI}from"zlib";import{createInterface as DI}from"readline";import{promisify as ng}from"util";function Gm(n){return n==="summary"?"summary":"inline"}var Hu=256;function Xm(n,e){return e!=="summary"?n:n.map(MI)}function MI(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(Zm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Uu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...n,params:{...t,update:i}}}function _I(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function Zm(n){if(_I(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Uu(e.text)),typeof e.content=="string"?t.content=Uu(e.content):e.content&&typeof e.content=="object"&&(t.content=Zm(e.content)),t}function Uu(n){if(typeof n=="string"&&n.length>Hu){let e=n.length-Hu;return`${n.slice(0,Hu)}\u2026[+${e} chars omitted from summary export]`}return n}var $I=2048;function eg(n){let e=new Set,t=s=>{if(tg(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function tg(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function FI(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Wu(n,e){if(!FI(n))return n;let t=n.params,s=t.update,r=await ju(s,e);return{...n,params:{...t,update:r}}}async function ju(n,e){if(typeof n=="string"){if(n.length<=$I)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await ju(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await ju(r,e);return t}return n}async function zu(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await qu(t,e);return s===t?n:{...n,params:s}}async function qu(n,e){if(tg(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await qu(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await qu(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var HI=ng(BI),UI=ng(NI),jI=/^history\.jsonl\.(\d+)(\.gz)?$/,Bn=/^[A-Za-z0-9_-]+$/,qI=1e3,WI=1e7,zI=10,Jd=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??qI,this.archiveMaxBytes=e.archiveMaxBytes??WI,this.archiveTiers=e.archiveTiers??zI}async append(e,t){if(Bn.test(e))return this.enqueue(e,async()=>{await Fe.mkdir(O.sessionDir(e),{recursive:!0});let s=await Wu(t,i=>nu(e,i)),r=JSON.stringify(s)+`
297
297
  `;await Fe.appendFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(Bn.test(e))return this.enqueue(e,async()=>{await Fe.mkdir(O.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await Wu(i,o=>nu(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
298
298
  `)+`
299
299
  `;await Fe.writeFile(O.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(Bn.test(e))return this.enqueue(e,async()=>{let s;try{s=await Fe.readFile(O.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=s.split(`
@@ -301,56 +301,56 @@ ${Eu}`;return Dm(n,s,Om)}function CI(n){if(!n||typeof n!="object")return"";let e
301
301
  `)+`
302
302
  `,{encoding:"utf8",mode:384})})}async spillToArchive(e,t){let s=t.join(`
303
303
  `)+`
304
- `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=O.historyArchiveFile(e,r);await Fe.mkdir(O.sessionDir(e),{recursive:!0}),await Fe.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await Fe.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?(await this.sealArchive(e,r),this.nextArchiveIndex.set(e,r+1)):this.nextArchiveIndex.set(e,r),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let s=O.historyArchiveFile(e,t),r;try{r=await Fe.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await NI(r);await Fe.writeFile(s+".gz",i,{mode:384});try{await Fe.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let s=await this.listArchiveIndices(e),r=s.length===0?0:s[s.length-1],i=r===0?1:r;if(r>0){let o=O.historyArchiveFile(e,r),a=o+".gz",c=!1;try{await Fe.access(a),c=!0}catch{c=!1}if(c)i=r+1;else try{(await Fe.stat(o)).size>=this.archiveMaxBytes&&(i=r+1)}catch{i=r}}return this.nextArchiveIndex.set(e,i),i}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let s=await this.listArchiveIndices(e),i=(s.includes(t)?s.length:s.length+1)-this.archiveTiers,o=0;for(;i>0&&o<s.length;){let a=s[o];a!==t&&(await this.unlinkArchive(e,a),i-=1),o+=1}}async unlinkArchive(e,t){let s=O.historyArchiveFile(e,t);for(let r of[s,s+".gz"])try{await Fe.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await Fe.readdir(O.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=new Set;for(let r of t){let i=HI.exec(r);if(!i)continue;let o=Number.parseInt(i[1],10);Number.isFinite(o)&&o>0&&s.add(o)}return[...s].sort((r,i)=>r-i)}async listArchives(e){if(!Bn.test(e))return[];let t=await this.listArchiveIndices(e),s=[];for(let r of t){let i=O.historyArchiveFile(e,r),o=i+".gz",a=i;try{await Fe.access(o),a=o}catch{a=i}s.push({index:r,path:a})}return s}async loadArchives(e){if(!Bn.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let s=await this.listArchives(e),r=[];for(let{path:i}of s){let o;try{if(i.endsWith(".gz")){let a=await Fe.readFile(i);o=(await DI(a)).toString("utf8")}else o=await Fe.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
305
- `)){if(a.length===0)continue;let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object"||Array.isArray(c))continue;let d=c;typeof d.method=="string"&&typeof d.recordedAt=="number"&&r.push({method:d.method,params:d.params,recordedAt:d.recordedAt})}}return r}async*streamFile(e){let t;try{t=$I(e)}catch(o){if(o.code==="ENOENT")return;throw o}if(await new Promise(o=>{let a=!1,c=d=>{a||(a=!0,o(d))};t.once("error",d=>{d.code==="ENOENT"?c(!0):(t.destroy(),c(!1))}),t.once("readable",()=>c(!1)),t.once("end",()=>c(!1))}))return;let r=e.endsWith(".gz")?t.pipe(FI()):t,i=BI({input:r,crlfDelay:1/0});try{for await(let o of i){if(o.length===0)continue;let a;try{a=JSON.parse(o)}catch{continue}if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a;typeof c.method=="string"&&typeof c.recordedAt=="number"&&(yield{method:c.method,params:c.params,recordedAt:c.recordedAt})}}finally{i.close(),t.destroy()}}async getArchiveLineCounts(e){if(!Bn.test(e))return[];let t=this.archiveLineCounts.get(e),s=await this.listArchives(e);if(t&&t.length===s.length&&t.every((i,o)=>i.index===s[o].index&&i.path===s[o].path))return t;let r=[];for(let{index:i,path:o}of s){let a=t?.find(d=>d.index===i&&d.path===o);if(a){r.push(a);continue}let c=0;for await(let d of this.streamFile(o))c+=1;r.push({index:i,path:o,lineCount:c})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,s){return zu(t,async r=>{let i=s.get(r);if(i!==void 0)return i;let o=await oa(e,r);return s.set(r,o),o})}async*iterRecallNewestFirst(e){if(!Bn.test(e))return;let t=this.writeQueues.get(e);t&&await t;let s=await this.getArchiveLineCounts(e),r=0;for(let d of s)r+=d.lineCount;let i=new Map,o=[];for await(let d of this.streamFile(O.historyFile(e)))o.push(d);for(let d=o.length-1;d>=0;d--){let l=await this.hydrateEntry(e,o[d],i);yield{entryId:r+d,entry:l}}let a=new Array(s.length),c=0;for(let d=0;d<s.length;d++)a[d]=c,c+=s[d].lineCount;for(let d=s.length-1;d>=0;d--){let l=s[d],u=[];for await(let p of this.streamFile(l.path))u.push(p);let f=a[d];for(let p=u.length-1;p>=0;p--){let h=await this.hydrateEntry(e,u[p],i);yield{entryId:f+p,entry:h}}}}async rangeSlice(e,t,s){if(!Bn.test(e))return[];if(s<t)return[];let r=this.writeQueues.get(e);r&&await r;let i=await this.getArchiveLineCounts(e),o=0;for(let l of i)o+=l.lineCount;let a=[],c=new Map,d=0;for(let l of i){let u=d,f=d+l.lineCount;if(d=f,f<=t)continue;if(u>s)break;let p=0;for await(let h of this.streamFile(l.path)){let m=u+p;if(p+=1,m<t)continue;if(m>s)break;let y=await this.hydrateEntry(e,h,c);a.push({entryId:m,entry:y})}}if(s>=o){let l=Math.max(t-o,0),u=s-o,f=0;for await(let p of this.streamFile(O.historyFile(e))){if(f>u)break;if(f>=l){let h=await this.hydrateEntry(e,p,c);a.push({entryId:o+f,entry:h})}f+=1}}return a}async getRecallTotalCount(e){if(!Bn.test(e))return 0;let t=await this.getArchiveLineCounts(e),s=0;for(let i of t)s+=i.lineCount;let r=0;for await(let i of this.streamFile(O.historyFile(e)))r+=1;return s+r}async load(e,t={}){if(!Bn.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Fe.readFile(O.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
306
- `)){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=t.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 oa(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await zu(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Bn.test(e))return this.enqueue(e,async()=>{try{await Fe.unlink(O.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let t=await this.listArchiveIndices(e);for(let s of t)await this.unlinkArchive(e,s);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await Fh(e);try{await Fe.rmdir(O.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};be();Ge();Vd();zr();Bd();_t();_t();cn();xu();var ig=900*1e3,VI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qd=YI(VI,16),Gd=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>nr.spawn(a)),this.store=s??new jd,this.tombstones=r.tombstones??new qd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Jd({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new 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,t,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:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,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 t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.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`),t.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(t,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,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,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 Fi(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Qd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new zi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),forkHook:i=>this.forkSession(r.sessionId,i??{}),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 t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=q.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=q.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await vn(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:Oi,clientInfo:{name:"hydra",version:ve}});o=m.agentCapabilities,i.authMethods=wa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),rr(m,i)}let a;try{let m=og(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===q.AuthRequired)throw await i.kill().catch(()=>{}),rr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
307
- `),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=Xu(a??{}),d=e.agentModes??Vu(Gu(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 Bi({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=Yu(a??{}),f=Vu(Qu(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 Ni({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 zi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels: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),forkHook:m=>this.forkSession(h.sessionId,m??{}),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 t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Bi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ni({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new zi({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,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),forkHook:d=>this.forkSession(c.sessionId,d??{}),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 Kr.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:tt(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=q.AgentNotInstalled,p}let s=await vn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:lg.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}})}catch(p){throw await r.kill().catch(()=>{}),rr(p,r)}if(r.authMethods=wa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=O.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(QI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Bm(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=`${Dt}${Qd()}`,w=new Date().toISOString(),b=p.updatedAt??w,S={sessionId:y,lineageId:fa(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(S.title=p.title);let k=Ou(S);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),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),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=q.AgentNotInstalled,i}let s=await vn(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}}),o=i.agentCapabilities;r.authMethods=wa(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=Yu(a),l=Qu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ui(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(w=>w.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Gu(a),p=Xu(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(()=>{}),rr(dg(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=q.AgentNotInstalled,o}let r=await vn(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}}),a=o.agentCapabilities;i.authMethods=wa(o.authMethods);let c=og(t.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),l=Yu(d),u=Vu(Qu(d)),f=Gu(d),p=Xu(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(()=>{}),rr(dg(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let 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 t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=q.AgentNotInstalled,c}let i=await vn(r,[],{npmRegistry:this.npmRegistry}),o=t??tt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}});a.authMethods=wa(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),rr(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=q.AgentNotInstalled,s}return vn(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Vi({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(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:ug(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=GI(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return oa(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:XI(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=qi(r.update.prompt),o=Ru(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Dt))return;let t=Dt+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=q.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,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 t=this.sessions.get(e);if(t){let a=await ba(t.sessionId),c=Vi({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:d,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await ba(s.sessionId),i=Vi(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 t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>ba(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Vi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt: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=>ba(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Vi(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=fa(),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=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await cg(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of eg(o)){let l=await _h(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=q.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Dt}${Qd()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=q.SessionNotFound,S}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=q.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=t.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(t.forkAt!==void 0){let S=Hd(o,t.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw k.code=q.InvalidParams,k}c=t.forkAt,a=o.slice(0,S+1)}else{let S=ex(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let k=Hd(o,t.forkAt);if(k<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=q.InvalidParams,A}c=t.forkAt,a=o.slice(0,k+1)}else c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=q.AgentNotInstalled,k}f=S,u=s.currentModel,l="running"}let h=await cg(e),m=d==="synthesis",y={...s,lineageId:fa(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},w=ya({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:ve,machine:Li()}),b=`${Dt}${Qd()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await vn(f,[],{npmRegistry:this.npmRegistry}),k=await zd({agentId:r,cwd:t.cwd??O.sessionDir(e),plan:S,history:a,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(b,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(b,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:b,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await $h(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Kr.utimes(O.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Wr(O.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await ba(e),i=Vi(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:t,...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 t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);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,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}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,t,s){let r=this.get(e);if(r){if(t){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=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;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(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 t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Sm(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<ig),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${ig/1e3}s)`),await ca(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await ca(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function QI(n,e){if(typeof n!="string"||n.length===0)return!1;let t=va.resolve(n),s=va.resolve(e);return t===s||t.startsWith(s+va.sep)}function GI(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),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 Ou({sessionId:n.sessionId,lineageId:e?.lineageId??fa(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:ug(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function ug(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function XI(n){return n?{...n}:void 0}function og(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Xd(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=ZI(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Yu(n){return Xd(n,{nestedKey:"models",configId:"model",fromObject:e=>as(e.currentModelId)??as(e.currentModel)??as(e.modelId)??as(e.model),fromConfig:e=>as(e.currentValue)})}function rr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==q.AuthRequired)return n;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=q.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function ag(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function dg(n,e,t,s){if(n&&typeof n=="object"&&n.code===q.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${ag(s.cwd)} && ${[s.command,...s.args].map(ag).join(" ")})`:"";if(!o&&!a)return n;let c=[i?r:`agent ${t} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
308
- `));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function wa(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,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 as(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function ZI(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Vu(n){return n.length>0?n:void 0}function Qu(n){return Xd(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Wi(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Wi(e.options);return t.length>0?t:void 0}})??[]}function Gu(n){return Xd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=la(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=la(e.options);return t.length>0?t:void 0}})??[]}function Xu(n){return Xd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>as(e.currentModeId)??as(e.currentMode)??as(e.modeId)??as(e.mode),fromConfig:e=>as(e.currentValue)})}function ex(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function cg(n){try{let e=await Kr.readFile(O.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
309
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function ba(n){try{let e=await Kr.stat(O.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Vi(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===qr?!1:e?!0:void 0}import{spawn as tx}from"child_process";import*as ec from"fs";import*as $s from"fs/promises";import*as tc from"path";import nx from"pino-roll";var Zd=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Ge();var sx=1e3,rx=6e4,Zu=3e3,Qi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??sx,this.restartCapMs=r.restartCapMs??rx;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await $s.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},Zu);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Sa(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Sa(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Zu);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Zd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await $s.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let i=await $s.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&ef(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Zu;for(;Date.now()<i&&ef(r);)await new Promise(o=>setTimeout(o,50));if(ef(r))try{process.kill(r,"SIGKILL")}catch{}}await $s.unlink(s).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=tc.dirname(this.adapter.paths.logFile(r.name)),a;try{await $s.mkdir(o,{recursive:!0}),a=await nx({file:tc.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
304
+ `,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=O.historyArchiveFile(e,r);await Fe.mkdir(O.sessionDir(e),{recursive:!0}),await Fe.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await Fe.stat(i)).size}catch{o=0}o>=this.archiveMaxBytes?(await this.sealArchive(e,r),this.nextArchiveIndex.set(e,r+1)):this.nextArchiveIndex.set(e,r),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let s=O.historyArchiveFile(e,t),r;try{r=await Fe.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await HI(r);await Fe.writeFile(s+".gz",i,{mode:384});try{await Fe.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let s=await this.listArchiveIndices(e),r=s.length===0?0:s[s.length-1],i=r===0?1:r;if(r>0){let o=O.historyArchiveFile(e,r),a=o+".gz",c=!1;try{await Fe.access(a),c=!0}catch{c=!1}if(c)i=r+1;else try{(await Fe.stat(o)).size>=this.archiveMaxBytes&&(i=r+1)}catch{i=r}}return this.nextArchiveIndex.set(e,i),i}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let s=await this.listArchiveIndices(e),i=(s.includes(t)?s.length:s.length+1)-this.archiveTiers,o=0;for(;i>0&&o<s.length;){let a=s[o];a!==t&&(await this.unlinkArchive(e,a),i-=1),o+=1}}async unlinkArchive(e,t){let s=O.historyArchiveFile(e,t);for(let r of[s,s+".gz"])try{await Fe.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await Fe.readdir(O.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=new Set;for(let r of t){let i=jI.exec(r);if(!i)continue;let o=Number.parseInt(i[1],10);Number.isFinite(o)&&o>0&&s.add(o)}return[...s].sort((r,i)=>r-i)}async listArchives(e){if(!Bn.test(e))return[];let t=await this.listArchiveIndices(e),s=[];for(let r of t){let i=O.historyArchiveFile(e,r),o=i+".gz",a=i;try{await Fe.access(o),a=o}catch{a=i}s.push({index:r,path:a})}return s}async loadArchives(e){if(!Bn.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let s=await this.listArchives(e),r=[];for(let{path:i}of s){let o;try{if(i.endsWith(".gz")){let a=await Fe.readFile(i);o=(await UI(a)).toString("utf8")}else o=await Fe.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
305
+ `)){if(a.length===0)continue;let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object"||Array.isArray(c))continue;let d=c;typeof d.method=="string"&&typeof d.recordedAt=="number"&&r.push({method:d.method,params:d.params,recordedAt:d.recordedAt})}}return r}async*streamFile(e){let t;try{t=OI(e)}catch(o){if(o.code==="ENOENT")return;throw o}if(await new Promise(o=>{let a=!1,c=d=>{a||(a=!0,o(d))};t.once("error",d=>{d.code==="ENOENT"?c(!0):(t.destroy(),c(!1))}),t.once("readable",()=>c(!1)),t.once("end",()=>c(!1))}))return;let r=e.endsWith(".gz")?t.pipe(LI()):t,i=DI({input:r,crlfDelay:1/0});try{for await(let o of i){if(o.length===0)continue;let a;try{a=JSON.parse(o)}catch{continue}if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a;typeof c.method=="string"&&typeof c.recordedAt=="number"&&(yield{method:c.method,params:c.params,recordedAt:c.recordedAt})}}finally{i.close(),t.destroy()}}async getArchiveLineCounts(e){if(!Bn.test(e))return[];let t=this.archiveLineCounts.get(e),s=await this.listArchives(e);if(t&&t.length===s.length&&t.every((i,o)=>i.index===s[o].index&&i.path===s[o].path))return t;let r=[];for(let{index:i,path:o}of s){let a=t?.find(d=>d.index===i&&d.path===o);if(a){r.push(a);continue}let c=0;for await(let d of this.streamFile(o))c+=1;r.push({index:i,path:o,lineCount:c})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,s){return zu(t,async r=>{let i=s.get(r);if(i!==void 0)return i;let o=await oa(e,r);return s.set(r,o),o})}async*iterRecallNewestFirst(e){if(!Bn.test(e))return;let t=this.writeQueues.get(e);t&&await t;let s=await this.getArchiveLineCounts(e),r=0;for(let d of s)r+=d.lineCount;let i=new Map,o=[];for await(let d of this.streamFile(O.historyFile(e)))o.push(d);for(let d=o.length-1;d>=0;d--){let l=await this.hydrateEntry(e,o[d],i);yield{entryId:r+d,entry:l}}let a=new Array(s.length),c=0;for(let d=0;d<s.length;d++)a[d]=c,c+=s[d].lineCount;for(let d=s.length-1;d>=0;d--){let l=s[d],u=[];for await(let p of this.streamFile(l.path))u.push(p);let f=a[d];for(let p=u.length-1;p>=0;p--){let h=await this.hydrateEntry(e,u[p],i);yield{entryId:f+p,entry:h}}}}async rangeSlice(e,t,s){if(!Bn.test(e))return[];if(s<t)return[];let r=this.writeQueues.get(e);r&&await r;let i=await this.getArchiveLineCounts(e),o=0;for(let l of i)o+=l.lineCount;let a=[],c=new Map,d=0;for(let l of i){let u=d,f=d+l.lineCount;if(d=f,f<=t)continue;if(u>s)break;let p=0;for await(let h of this.streamFile(l.path)){let m=u+p;if(p+=1,m<t)continue;if(m>s)break;let y=await this.hydrateEntry(e,h,c);a.push({entryId:m,entry:y})}}if(s>=o){let l=Math.max(t-o,0),u=s-o,f=0;for await(let p of this.streamFile(O.historyFile(e))){if(f>u)break;if(f>=l){let h=await this.hydrateEntry(e,p,c);a.push({entryId:o+f,entry:h})}f+=1}}return a}async getRecallTotalCount(e){if(!Bn.test(e))return 0;let t=await this.getArchiveLineCounts(e),s=0;for(let i of t)s+=i.lineCount;let r=0;for await(let i of this.streamFile(O.historyFile(e)))r+=1;return s+r}async load(e,t={}){if(!Bn.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Fe.readFile(O.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
306
+ `)){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=t.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 oa(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await zu(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Bn.test(e))return this.enqueue(e,async()=>{try{await Fe.unlink(O.historyFile(e))}catch(s){if(s.code!=="ENOENT")throw s}let t=await this.listArchiveIndices(e);for(let s of t)await this.unlinkArchive(e,s);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await Fh(e);try{await Fe.rmdir(O.sessionDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};be();Ge();Vd();zr();Bd();_t();_t();cn();xu();var ig=900*1e3,GI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qd=QI(GI,16),Gd=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>nr.spawn(a)),this.store=s??new jd,this.tombstones=r.tombstones??new qd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Jd({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:r.sessionHistoryArchiveMaxBytes,archiveTiers:r.sessionHistoryArchiveTiers}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new 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,t,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:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,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 t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.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`),t.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(t,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,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,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 Fi(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Qd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new zi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),forkHook:i=>this.forkSession(r.sessionId,i??{}),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 t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=q.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=q.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await Sn(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:Oi,clientInfo:{name:"hydra",version:ve}});o=m.agentCapabilities,i.authMethods=wa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),rr(m,i)}let a;try{let m=og(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===q.AuthRequired)throw await i.kill().catch(()=>{}),rr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
307
+ `),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=Xu(a??{}),d=e.agentModes??Vu(Gu(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 Bi({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=Yu(a??{}),f=Vu(Qu(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 Ni({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 zi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels: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),forkHook:m=>this.forkSession(h.sessionId,m??{}),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 t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Bi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ni({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new zi({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,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),forkHook:d=>this.forkSession(c.sessionId,d??{}),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 Kr.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:tt(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=q.AgentNotInstalled,p}let s=await Sn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:lg.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}})}catch(p){throw await r.kill().catch(()=>{}),rr(p,r)}if(r.authMethods=wa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=O.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(XI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Bm(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=`${Dt}${Qd()}`,w=new Date().toISOString(),b=p.updatedAt??w,S={sessionId:y,lineageId:fa(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(S.title=p.title);let k=Ou(S);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),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),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=q.AgentNotInstalled,i}let s=await Sn(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}}),o=i.agentCapabilities;r.authMethods=wa(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=Yu(a),l=Qu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ui(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(w=>w.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Gu(a),p=Xu(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(()=>{}),rr(dg(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=q.AgentNotInstalled,o}let r=await Sn(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}}),a=o.agentCapabilities;i.authMethods=wa(o.authMethods);let c=og(t.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),l=Yu(d),u=Vu(Qu(d)),f=Gu(d),p=Xu(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(()=>{}),rr(dg(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let 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 t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=q.AgentNotInstalled,c}let i=await Sn(r,[],{npmRegistry:this.npmRegistry}),o=t??tt(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Oi,clientInfo:{name:"hydra",version:ve}});a.authMethods=wa(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),rr(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=q.AgentNotInstalled,s}return Sn(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Vi({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(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:ug(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=ZI(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return oa(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:ex(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=qi(r.update.prompt),o=Ru(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Dt))return;let t=Dt+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=q.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,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 t=this.sessions.get(e);if(t){let a=await ba(t.sessionId),c=Vi({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:d,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await ba(s.sessionId),i=Vi(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 t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>ba(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Vi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt: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=>ba(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Vi(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=fa(),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=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await cg(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of eg(o)){let l=await _h(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=q.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Dt}${Qd()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=q.SessionNotFound,S}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=q.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=t.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(t.forkAt!==void 0){let S=Hd(o,t.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw k.code=q.InvalidParams,k}c=t.forkAt,a=o.slice(0,S+1)}else{let S=nx(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let k=Hd(o,t.forkAt);if(k<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=q.InvalidParams,A}c=t.forkAt,a=o.slice(0,k+1)}else c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=q.AgentNotInstalled,k}f=S,u=s.currentModel,l="running"}let h=await cg(e),m=d==="synthesis",y={...s,lineageId:fa(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},w=ya({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:ve,machine:Li()}),b=`${Dt}${Qd()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await Sn(f,[],{npmRegistry:this.npmRegistry}),k=await zd({agentId:r,cwd:t.cwd??O.sessionDir(e),plan:S,history:a,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(b,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(b,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:b,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await $h(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Kr.utimes(O.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Wr(O.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await ba(e),i=Vi(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:t,...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 t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);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,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}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,t,s){let r=this.get(e);if(r){if(t){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=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;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(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 t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Sm(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<ig),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${ig/1e3}s)`),await ca(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await ca(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function XI(n,e){if(typeof n!="string"||n.length===0)return!1;let t=va.resolve(n),s=va.resolve(e);return t===s||t.startsWith(s+va.sep)}function ZI(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),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 Ou({sessionId:n.sessionId,lineageId:e?.lineageId??fa(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:ug(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function ug(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function ex(n){return n?{...n}:void 0}function og(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Xd(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=tx(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Yu(n){return Xd(n,{nestedKey:"models",configId:"model",fromObject:e=>ds(e.currentModelId)??ds(e.currentModel)??ds(e.modelId)??ds(e.model),fromConfig:e=>ds(e.currentValue)})}function rr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==q.AuthRequired)return n;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=q.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function ag(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function dg(n,e,t,s){if(n&&typeof n=="object"&&n.code===q.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${ag(s.cwd)} && ${[s.command,...s.args].map(ag).join(" ")})`:"";if(!o&&!a)return n;let c=[i?r:`agent ${t} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
308
+ `));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function wa(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,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 ds(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function tx(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Vu(n){return n.length>0?n:void 0}function Qu(n){return Xd(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Wi(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Wi(e.options);return t.length>0?t:void 0}})??[]}function Gu(n){return Xd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=la(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=la(e.options);return t.length>0?t:void 0}})??[]}function Xu(n){return Xd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ds(e.currentModeId)??ds(e.currentMode)??ds(e.modeId)??ds(e.mode),fromConfig:e=>ds(e.currentValue)})}function nx(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function cg(n){try{let e=await Kr.readFile(O.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
309
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function ba(n){try{let e=await Kr.stat(O.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Vi(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===qr?!1:e?!0:void 0}import{spawn as sx}from"child_process";import*as ec from"fs";import*as $s from"fs/promises";import*as tc from"path";import rx from"pino-roll";var Zd=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Ge();var ix=1e3,ox=6e4,Zu=3e3,Qi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??ix,this.restartCapMs=r.restartCapMs??ox;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await $s.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},Zu);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Sa(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Sa(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw Sa(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Zu);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Zd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await $s.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let i=await $s.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&ef(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Zu;for(;Date.now()<i&&ef(r);)await new Promise(o=>setTimeout(o,50));if(ef(r))try{process.kill(r,"SIGKILL")}catch{}}await $s.unlink(s).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=tc.dirname(this.adapter.paths.logFile(r.name)),a;try{await $s.mkdir(o,{recursive:!0}),a=await rx({file:tc.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
310
310
  `);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
311
- `),a.end();return}let f=tt(l),p=[...u,...r.args].map(tt),h;try{h=tx(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
311
+ `),a.end();return}let f=tt(l),p=[...u,...r.args].map(tt),h;try{h=sx(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
312
312
  `),a.end(),this.scheduleRestart(e,t);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{ec.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
313
313
  `,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${y.message}
314
314
  `)}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}
315
315
  `)}),h.on("exit",(y,w)=>{try{ec.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${w??"null"}
316
316
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof y=="number"?y:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let b=e.exitWaiters.splice(0);for(let k of b)k();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let S=e.breaker.recordExit(y,r.name,this.adapter.kind);if(typeof S=="object"){e.failureReason=S.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${S.tripped}
317
- `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ef(n){try{return process.kill(n,0),!0}catch{return!1}}function Sa(n,e){return n.code=e,n}be();var ix={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:O.extensionsDir,logFile:O.extensionLogFile,pidFile:O.extensionPidFile}},nc=class extends Qi{constructor(e,t,s={}){super(e,ix,t,s)}};be();var ox={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:O.transformersDir,logFile:O.transformerLogFile,pidFile:O.transformerPidFile}},sc=class extends Qi{connected=new Map;constructor(e,t,s={}){super(e,ox,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var rc=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};be();Ei();_i();be();_i();import*as Ia from"fs/promises";import*as ic from"path";var ka=n=>{process.stderr.write(n+`
317
+ `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ef(n){try{return process.kill(n,0),!0}catch{return!1}}function Sa(n,e){return n.code=e,n}be();var ax={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:O.extensionsDir,logFile:O.extensionLogFile,pidFile:O.extensionPidFile}},nc=class extends Qi{constructor(e,t,s={}){super(e,ax,t,s)}};be();var dx={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:O.transformersDir,logFile:O.transformerLogFile,pidFile:O.transformerPidFile}},sc=class extends Qi{connected=new Map;constructor(e,t,s={}){super(e,dx,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var rc=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};be();Ei();_i();be();_i();import*as Ia from"fs/promises";import*as ic from"path";var ka=n=>{process.stderr.write(n+`
318
318
  `)};function tf(n){ka=n??(e=>process.stderr.write(e+`
319
- `))}async function fg(n,e){let t=bn();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=ic.join(O.agentsDir(),t),a;try{a=await Ia.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ka(`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=ic.join(o,d),p;try{p=await Ia.readdir(f,{withFileTypes:!0})}catch(h){ka(`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=ic.join(f,m);try{await Ia.rm(y,{recursive:!0,force:!0}),ka(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(w){ka(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function pg(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await uu(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function nf(n){let e=n.maxDeletions??200,t=(p,h)=>{n.logger&&n.logger[p](`session-gc: ${h}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,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 n.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,t("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(n.verbose||d>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${d} ${p} session(s) older than ${ax(n.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 hg(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await nf({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function ax(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}cn();xa();be();Or();import*as yg from"path";import{createHash as cx,randomBytes as lx,timingSafeEqual as ux}from"crypto";var wg="hydra_session_",fx=3600*24*30,mg=12,px=32,hx=50;function mx(){return yg.join(O.home(),"session-tokens.json")}function gg(n){return cx("sha256").update(n).digest("hex")}function bg(n){return lx(n).toString("hex")}function gx(){return bg(mg).slice(0,mg*2)}function yx(){return`${wg}${bg(px)}`}var oc=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=mx(),s=await wn(t);s&&Array.isArray(s.records)&&(e=s.records.filter(wx));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=yx(),s=gg(t),r=gx(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:fx,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:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(wg))return;let t=gg(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!ux(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},hx))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>rn(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 wx(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}Es();var vg="Bearer ",ac=class{constructor(e){this.token=e}token;async validate(e){return bx(e,this.token)?"service":void 0}},dc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},cc=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Sg(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(vg)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(vg.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function kg(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var lc=class{tokens=new Map;mint(e,t){let s=xi();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function bx(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var uc=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};Od();be();Ge();of();zr();hc();import*as lf from"fs";import*as jg from"os";import*as qg from"path";import*as uf from"readline";or();is();function mc(n,e={}){let t=Jx(n),s=Yx(t),r=[];Vx(r,n),Qx(r,t,s,e.includeTools??!1);let i=r.join(`
319
+ `))}async function fg(n,e){let t=vn();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=ic.join(O.agentsDir(),t),a;try{a=await Ia.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ka(`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=ic.join(o,d),p;try{p=await Ia.readdir(f,{withFileTypes:!0})}catch(h){ka(`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=ic.join(f,m);try{await Ia.rm(y,{recursive:!0,force:!0}),ka(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(w){ka(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function pg(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await uu(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function nf(n){let e=n.maxDeletions??200,t=(p,h)=>{n.logger&&n.logger[p](`session-gc: ${h}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,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 n.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,t("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(n.verbose||d>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${d} ${p} session(s) older than ${cx(n.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 hg(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await nf({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function cx(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}cn();xa();be();Or();import*as yg from"path";import{createHash as ux,randomBytes as fx,timingSafeEqual as px}from"crypto";var wg="hydra_session_",hx=3600*24*30,mg=12,mx=32,gx=50;function yx(){return yg.join(O.home(),"session-tokens.json")}function gg(n){return ux("sha256").update(n).digest("hex")}function bg(n){return fx(n).toString("hex")}function wx(){return bg(mg).slice(0,mg*2)}function bx(){return`${wg}${bg(mx)}`}var oc=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=yx(),s=await wn(t);s&&Array.isArray(s.records)&&(e=s.records.filter(vx));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=bx(),s=gg(t),r=wx(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:hx,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:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(wg))return;let t=gg(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!px(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},gx))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>rn(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 vx(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}Ps();var vg="Bearer ",ac=class{constructor(e){this.token=e}token;async validate(e){return Sx(e,this.token)?"service":void 0}},dc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},cc=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Sg(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(vg)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(vg.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function kg(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var lc=class{tokens=new Map;mint(e,t){let s=xi();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function Sx(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var uc=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};Od();be();Ge();of();zr();hc();import*as lf from"fs";import*as jg from"os";import*as qg from"path";import*as uf from"readline";or();os();function mc(n,e={}){let t=Vx(n),s=Qx(t),r=[];Gx(r,n),Xx(r,t,s,e.includeTools??!1);let i=r.join(`
320
320
  `);return i.endsWith(`
321
321
  `)||(i+=`
322
- `),i}function Jx(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=ds(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Yx(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Vx(n,e){let t=e.session,s=pt(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Zi(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${df(a.size)}`:void 0;c.push(d?`${df(a.used)} / ${d} tokens`:`${df(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 ")}`)}n.push(i.join(`
323
- `)),n.push("")}function Qx(n,e,t,s){if(!e.some(p=>Gx(p.event))){n.push("_No conversation history recorded._"),n.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)n.push(p);n.push(""),a=[]}},u=()=>{l(),o.length>0&&($g(n,o.trimEnd(),"*"),n.push(""),o=""),i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},f=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{u(),n.push("---"),n.push(""),r+=1,$g(n,p.text,"**"),n.push(""),d=!0;break}case"agent-text":f(),i+=p.text;break;case"agent-thought":{f(),i.length>0&&(n.push(i.trimEnd()),n.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(f(),(i.length>0||o.length>0)&&u(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=t.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${Zx(h.status)} ${Xx(h)}`);break}case"tool-call-update":break;case"plan":{f(),u(),n.push("**Plan:**"),n.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";n.push(`- ${m} ${Zi(h.content)}`)}n.push("");break}case"mode-changed":f(),u(),n.push(`_mode: ${Zi(p.mode)}_`),n.push("");break;case"model-changed":f(),u(),n.push(`_model: ${Zi(p.model)}_`),n.push("");break;case"turn-complete":u();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}u()}function Gx(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Xx(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Zi(n.title)}${t}`}function Zx(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function $g(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
324
- `);for(let a=0;a<o.length;a++){let c=o[a],d=Zi(c);n.push(a===0&&a===o.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===o.length-1?`${d}${t}`:d)}r<s.length-1&&n.push("")}}function Zi(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function df(n){return n.toLocaleString("en-US")}_t();cn();ta();or();function eA(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,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=>tA(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function tA(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Fg(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Fg(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Fg(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function nA(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var sA=5,rA=200,Og=30;async function Ng(n,e,t={}){let s=eA(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??sA,i=t.maxSessions??rA,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.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 n.loadHistory(u.sessionId).catch(()=>[]),p=iA(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 iA(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=oA(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function oA(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let c=aA(a).filter(d=>nA(t,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:fA(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 aA(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=gc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?wt(s.text):gc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(lA(s))return[];let i=gc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=uA(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return dA(s);default:return[]}}function dA(n){let e=Lg(n,"name"),t=Lg(n,"title"),s=[];if(t!==void 0){let a=Te(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Bg(r);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Bg(i);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=cA(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function cA(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=Te(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=Te(s);if(r.length>0)return r}}return null}function lA(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function gc(n){if(typeof n=="string")return wt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?wt(e.text):""}function uA(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=gc(t);s.length>0&&e.push(s)}return e.join("")}function Lg(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Bg(n){try{return JSON.stringify(n)}catch{return""}}function fA(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Og),c=Math.min(s.length,o+i.length+Og),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Hg}from"crypto";function Dg(n){let e=Hg(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function cf(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Dg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Dg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=eo(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function eo(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Hg(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var yc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Ug(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Lr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Wg(n,e,t,s={}){n.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})}}),n.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)}),n.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 Ng(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=tt(u.cwd??t.cwd),p=u.agentId??t.agentId,h=eo(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})}}),n.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 nf({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),n.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()}),n.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=>qg.join(jg.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),n.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(w){return l.code(409).send({error:w.message}),l}}),n.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()}),n.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()}),n.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":Gm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=ya({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:ve,machine:Li(),hydraHost:Ug(t)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),l.code(200).send(y)}),n.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(b=>b.trim()).filter(b=>b.length>0)):void 0,w=Gi(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:Xi(b.hunks)}))),l.code(200).send(w)}),n.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)}),n.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=ya({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:ve,machine:Li(),hydraHost:Ug(t)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(mc(h,{includeTools:y}))}),n.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=tt(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===q.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===q.InvalidParams||y.code===q.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.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=Nn(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===q.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),n.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),w=!1,b,k=await e.getHistory(f).catch(()=>[])??[];if(k.length>0&&t.compaction){let A=h??0,E=k.length,H=k.slice(A).reduce((N,j)=>N+JSON.stringify(j.params).length,0);b=rf(H);let _=p?.currentModel,F=k.at(-1).recordedAt,B=p?.currentUsage;w=Ig({summarizedThroughEntry:A,totalEntries:E,unsummarizedChars:H,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:F,nowMs:Date.now(),config:t.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),n.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})}),n.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})}}),n.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,w,b=!1,S=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
322
+ `),i}function Vx(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=cs(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Qx(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Gx(n,e){let t=e.session,s=pt(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Zi(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${df(a.size)}`:void 0;c.push(d?`${df(a.used)} / ${d} tokens`:`${df(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 ")}`)}n.push(i.join(`
323
+ `)),n.push("")}function Xx(n,e,t,s){if(!e.some(p=>Zx(p.event))){n.push("_No conversation history recorded._"),n.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)n.push(p);n.push(""),a=[]}},u=()=>{l(),o.length>0&&($g(n,o.trimEnd(),"*"),n.push(""),o=""),i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},f=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{u(),n.push("---"),n.push(""),r+=1,$g(n,p.text,"**"),n.push(""),d=!0;break}case"agent-text":f(),i+=p.text;break;case"agent-thought":{f(),i.length>0&&(n.push(i.trimEnd()),n.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(f(),(i.length>0||o.length>0)&&u(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=t.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${tA(h.status)} ${eA(h)}`);break}case"tool-call-update":break;case"plan":{f(),u(),n.push("**Plan:**"),n.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";n.push(`- ${m} ${Zi(h.content)}`)}n.push("");break}case"mode-changed":f(),u(),n.push(`_mode: ${Zi(p.mode)}_`),n.push("");break;case"model-changed":f(),u(),n.push(`_model: ${Zi(p.model)}_`),n.push("");break;case"turn-complete":u();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}u()}function Zx(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function eA(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Zi(n.title)}${t}`}function tA(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function $g(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
324
+ `);for(let a=0;a<o.length;a++){let c=o[a],d=Zi(c);n.push(a===0&&a===o.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===o.length-1?`${d}${t}`:d)}r<s.length-1&&n.push("")}}function Zi(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function df(n){return n.toLocaleString("en-US")}_t();cn();ta();or();function nA(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,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=>sA(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function sA(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Fg(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Fg(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Fg(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function rA(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var iA=5,oA=200,Og=30;async function Ng(n,e,t={}){let s=nA(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??iA,i=t.maxSessions??oA,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.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 n.loadHistory(u.sessionId).catch(()=>[]),p=aA(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 aA(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=dA(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function dA(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let c=cA(a).filter(d=>rA(t,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:hA(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 cA(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=gc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?wt(s.text):gc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(fA(s))return[];let i=gc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=pA(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return lA(s);default:return[]}}function lA(n){let e=Lg(n,"name"),t=Lg(n,"title"),s=[];if(t!==void 0){let a=Te(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Bg(r);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Bg(i);if(a.length>0){let c={kind:"tool-input",text:Te(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=uA(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function uA(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=Te(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=Te(s);if(r.length>0)return r}}return null}function fA(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function gc(n){if(typeof n=="string")return wt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?wt(e.text):""}function pA(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=gc(t);s.length>0&&e.push(s)}return e.join("")}function Lg(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Bg(n){try{return JSON.stringify(n)}catch{return""}}function hA(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Og),c=Math.min(s.length,o+i.length+Og),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Hg}from"crypto";function Dg(n){let e=Hg(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function cf(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Dg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Dg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=eo(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function eo(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Hg(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var yc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Ug(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Lr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Wg(n,e,t,s={}){n.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})}}),n.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)}),n.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 Ng(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=tt(u.cwd??t.cwd),p=u.agentId??t.agentId,h=eo(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})}}),n.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 nf({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),n.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()}),n.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=>qg.join(jg.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),n.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(w){return l.code(409).send({error:w.message}),l}}),n.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()}),n.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()}),n.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":Gm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=ya({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:ve,machine:Li(),hydraHost:Ug(t)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),l.code(200).send(y)}),n.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(b=>b.trim()).filter(b=>b.length>0)):void 0,w=Gi(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:Xi(b.hunks)}))),l.code(200).send(w)}),n.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)}),n.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=ya({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:ve,machine:Li(),hydraHost:Ug(t)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(mc(h,{includeTools:y}))}),n.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=tt(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===q.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===q.InvalidParams||y.code===q.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.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=Nn(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===q.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),n.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),w=!1,b,k=await e.getHistory(f).catch(()=>[])??[];if(k.length>0&&t.compaction){let A=h??0,E=k.length,H=k.slice(A).reduce((N,j)=>N+JSON.stringify(j.params).length,0);b=rf(H);let _=p?.currentModel,F=k.at(-1).recordedAt,B=p?.currentUsage;w=Ig({summarizedThroughEntry:A,totalEntries:E,unsummarizedChars:H,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:F,nowMs:Date.now(),config:t.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),n.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})}),n.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})}}),n.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,w,b=!1,S=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
325
325
  `):(k.push(E),k.length>S&&k.shift()))})),d.raw.on("close",()=>{w?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(E){throw w?.(),E}}else{let E=await e.getHistory(h);if(E===void 0)return l.code(404).send({error:"session not found"}),l;y=E}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let A=new Set;for(let E of y??[]){l.raw.write(JSON.stringify(E)+`
326
326
  `);let P=E;typeof P.recordedAt=="number"&&A.add(String(P.recordedAt))}for(;k.length>0;){let E=k.splice(0,k.length);for(let P of E){let H=P,_=typeof H.recordedAt=="number"?String(H.recordedAt):"";_&&A.has(_)||l.raw.write(JSON.stringify(P)+`
327
327
  `)}}return b=!0,w||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 w=m.update.sessionUpdate;return typeof w!="string"||!l.has(w)?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=uf.createInterface({input:lf.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}n.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(!yc.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...yc].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}),w=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let b=[];for(let S of w)try{let k=O.historyFile(S.sessionId),A=await a(S.sessionId,k,h,m);A.exhausted||b.push(A)}catch(k){if(k.code==="ENOENT")continue;throw k}d.raw.on("close",()=>{for(let S of b)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;b.length>0;){let S=-1,k=1/0;for(let E=0;E<b.length;E++){let P=b[E];P.current!==null&&P.current.ts<k&&(k=P.current.ts,S=E)}if(S===-1)break;let A=b[S];if(l.raw.write(JSON.stringify(A.current.row)+`
328
328
  `),await c(A),A.exhausted){try{A.rl.close()}catch{}b.splice(S,1)}}}catch(S){for(let k of b)try{k.rl.close()}catch{}throw S}return l.raw.end(),l}),n.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(E=>E.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let E of y)if(!yc.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...yc].join(", ")}`}),l;let w=new Set(y),b;if(f.since!==void 0&&f.since.trim().length>0){let E=new Date(f.since);if(isNaN(E.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;b=E.getTime()}let S=O.historyFile(p),k=lf.createReadStream(S),A=uf.createInterface({input:k,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let E of A){let P=typeof E=="string"?E.trim():"";if(P.length===0)continue;let H;try{H=JSON.parse(P)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!H||typeof H!="object"||Array.isArray(H)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let _=H;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let F=_.params;if(typeof F.update!="object"||F.update===null||Array.isArray(F.update))continue;let B=F.update,N=B.sessionUpdate;if(typeof N!="string"||!w.has(N)||b!==void 0&&_.recordedAt<b)continue;let j={ts:new Date(_.recordedAt).toISOString(),kind:N,update:B};B.messageId!==void 0&&B.messageId!==null&&(j.messageId=B.messageId),l.raw.write(JSON.stringify(j)+`
329
- `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),n.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??[]}}),n.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 w of y)w.source===u.source&&p.push({...w,sessionId:h.sessionId})}return{flags:p}}),n.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 w=e.get(f);if(w){if(m.length>0&&y.length>0)w.clearAttentionFlag(m,y);else{let E=Array.from(w.listAttentionFlags()).map(P=>`${P.source}::${P.reason}`);for(let P of E)w.clearAttentionFlag(P.split("::")[0],P.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let b=e.store,S=await b.read(f);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],A;if(m.length>0&&y.length>0){let E=`${m}::${y}`;A=k.filter(P=>`${P.source}::${P.reason}`!==E)}else A=[];if(A.length===k.length&&A.every((E,P)=>E.source===k[P].source&&E.reason===k[P].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:A}),l.code(204).send()})}_t();function zg(n,e,t,s={}){n.get("/v1/agents",async()=>Fi(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await vn(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})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await t.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===q.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function Kg(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pA=/^[A-Za-z0-9._-]+$/;function wc(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=t.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(i,o)=>{let a=i.body??{},c=hA(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=t.register(c.config);o.code(201).send(d)}catch(d){Ra(o,d)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(c){Ra(o,c)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await t.startByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await t.stopByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await t.restartByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}})}function Ra(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function hA(n){let e=n.name;if(typeof e!="string"||!pA.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function Jg(n,e){wc(n,"extension",e)}function Yg(n,e){wc(n,"transformer",e)}function Vg(n,e){n.get("/v1/config",async()=>e)}import{z as to}from"zod";be();import*as ar from"fs/promises";import*as Zg from"path";import{randomBytes as mA,scrypt as gA,timingSafeEqual as yA}from"crypto";import{promisify as wA}from"util";var ey=wA(gA);function ff(){return Zg.join(O.home(),"password-hash")}var Qg=32768,Gg=8,Xg=1,bA=64,vA=16,ty=128*1024*1024;async function ny(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=mA(vA),t=await ey(n,e,bA,{N:Qg,r:Gg,p:Xg,maxmem:ty}),s=`scrypt$${Qg}$${Gg}$${Xg}$${e.toString("hex")}$${t.toString("hex")}
330
- `;await ar.mkdir(O.home(),{recursive:!0}),await ar.writeFile(ff(),s,{encoding:"utf8",mode:384})}async function bc(){try{return(await ar.readFile(ff(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function vc(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ar.readFile(ff(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let c=await ey(n,o,a.length,{N:s,r,p:i,maxmem:ty});return c.length!==a.length?!1:yA(c,a)}var SA=to.object({password:to.string().min(1),label:to.string().min(1).max(256).optional(),ttlSec:to.number().int().positive().optional()}),kA=to.object({id:to.string().optional()}).optional();function sy(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=IA(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=SA.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await bc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await vc(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=kA.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function IA(n){return n.ip||"unknown"}jr();no();import{nanoid as pf}from"nanoid";Bd();_t();cn();import{randomBytes as iy}from"crypto";import*as oy from"os";import*as ay from"path";function re(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function TA(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let 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 ln(n,e,t){let s=n.get(e);if(!s)throw re(q.SessionNotFound,t??`session ${e} not found`);return s}async function Sc(n,e){let t=eo(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=iy(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],c=cf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),d;try{d=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(d),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,u=n.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return BA(d,n),cy(d.sessionId,n),d}function dy(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=kg({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=cs(t),a=new zt(o),c={clientId:`hydra_client_${pf(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 re(q.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Kh.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)),LA()}),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 w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return 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 p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let S={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(S.outputSchema=b.outputSchema),S}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,y),{ok:!0,registered:y.length}});let f=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw re(q.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(!e.manager)throw re(q.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=f(p);if(!e.manager)throw re(q.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(m.value===void 0)throw re(q.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw re(q.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw re(q.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(!e.manager)throw re(q.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw re(q.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{u.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async f=>{let p=f??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw re(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw re(-32602,"emit_message requires method");let b=ln(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return b.dischargeClaim(S,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw re(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw re(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw re(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw re(-32602,"hydra-acp/session/request_permission requires sessionId");return ln(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>_A(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let p=f??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,S=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let P=e.manager.get(y);P&&(m=P.cwd)}if(!m)throw re(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:S,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,b=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let u=async(f,p)=>{let h=f??{};if(typeof h.sessionId!="string")throw re(q.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async f=>(await u(f,"session/delete"),{})),a.onRequest("session/close",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw re(q.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async f=>{let{id:p,existed:h}=await u(f,"hydra-acp/session/delete");if(!h)throw re(q.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw re(-32602,"await_child requires childSessionId");let w=ln(e.manager,h,`child session ${h} not found`);return new Promise(b=>{let A=[],E=[],P=0,H=!1,_,F,B=!1,N=()=>{B||(B=!0,clearTimeout(j),_?.(),F?.(),b(H?{entries:A,truncated:!0}:{entries:A}))};_=w.onBroadcast(G=>{let X=TA(G);for(A.push(G),E.push(X),P+=X;A.length>0&&(A.length>1e3||P>1048576);)A.shift(),P-=E.shift()??0,H=!0;m==="turn_complete"&&G.params?.update?.sessionUpdate==="turn_complete"&&N()});let j=setTimeout(N,y);typeof j.unref=="function"&&j.unref(),F=w.onClose(()=>N())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw re(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>$A(f,i.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>FA(f,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let p=f??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw re(q.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 re(q.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>EA(u,e)),a.onRequest("logout",async u=>PA(u,e)),a.onRequest("session/new",async u=>{let f=Jh.parse(u),p=an(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(N=>typeof N=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,w,b=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=iy(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...f.mcpServers??[],j]}let S,k,A=eo(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=cf({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ry(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(N){throw w!==void 0&&w.abandon(N instanceof Error?N:void 0),k!==void 0&&k.abandon(N instanceof Error?N:void 0),A!==void 0&&A.abandon(N instanceof Error?N:void 0),N}if(y!==void 0&&w!==void 0&&e.mcpTokenRegistry!==void 0){let N=y,j=e.mcpTokenRegistry;w.complete(P),P.onClose(()=>{j.unbind(N)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=S,j=e.mcpTokenRegistry;k.complete(P),P.onClose(()=>{j.unbind(N)})}A!==void 0&&A.bindToSession(P),cy(P.sessionId,e);let H,_;try{Ac(c,P,P.sessionId),H=Ta(a,P,c),{entries:_}=await P.attach(H,"full")}catch(N){throw await P.close({deleteRecord:!1}).catch(()=>{}),N}c.attached.set(P.sessionId,{sessionId:P.sessionId,clientId:H.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of _){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let F=kc(P),B=Ic(P);return{sessionId:P.sessionId,...F?{modes:F}:{},...B?{models:B}:{},configOptions:P.buildConfigOptions(),_meta:xc(e.manager,P,{clientId:H.clientId})}}),a.onRequest("session/attach",async u=>{let f=Vh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=an(f._meta),m=h.resume,y=h.readonly===!0,w=h.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(b);if(!S&&y){let B=await e.manager.loadFromDisk(b);if(!B)throw re(q.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(b),j=f.clientId??`cli_${pf(8)}`;c.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${j} attachedCount=${c.attached.size} replayed=${N.length}`);for(let G of N)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:N.length,_meta:OA(B)}}let k=!S;if(!S){let B=await e.manager.loadFromDisk(b),N=B;if(m&&(N={...B,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}:{}}),!N)throw re(q.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw re(q.SessionNotFound,`session ${f.sessionId} was deleted`);let j=N.originatingClient?N:{...N,originatingClient:c.clientInfo},G=w!==void 0?{...j,forwardedEnv:w}:j;S=await Sc(e,{...G,onInstallProgress:ry(a)})}Ac(c,S,S.sessionId);let A=Ta(a,S,c,f.clientInfo,f.clientId),E=h.replayMode==="drip",{entries:P,appliedPolicy:H}=await S.attach(A,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(S.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${H} replayed=${P.length} readonly=${y}${E?" replayMode=drip":""}`),E){let B=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,N=750;(async()=>{let j=null;for(let G of P){let X=typeof G.recordedAt=="number"?G.recordedAt:null;if(j!==null&&X!==null){let V=Math.min(N,Math.max(0,(X-j)/B));V>0&&await new Promise(ye=>setTimeout(ye,V))}X!==null&&(j=X);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let B=0;B<P.length&&!a.isClosed();B++){let N=P[B],j=a.notify(N.method,N.params).catch(()=>{});(B+1)%200===0&&await j}S.replayPendingPermissions(A);let _=kc(S),F=Ic(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:H,replayed:P.length,..._?{modes:_}:{},...F?{models:F}:{},configOptions:S.buildConfigOptions(),_meta:xc(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=Qh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw re(q.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:{[Mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Gh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==qr).map(Xh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw re(q.InternalError,"agent registry unavailable");return Fi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw re(q.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=Zh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),re(q.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 re(q.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Sc(e,m);let y=Ta(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=Md.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.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=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=Md.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=tm.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),ln(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Md.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),ln(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=nm.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),ln(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=sm.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw re(q.SessionNotFound,"not attached to session");return ln(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 re(q.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 re(q.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Sc(e,S)}Ac(c,m,m.sessionId);let y=Ta(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=kc(m),b=Ic(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:xc(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 re(q.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw re(q.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Sc(e,k)}Ac(c,m,m.sessionId);let y=Ta(a,m,c),{entries:w}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of w){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let b=kc(m),S=Ic(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:xc(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=MA(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),re(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId: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 re(q.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw re(q.InvalidParams,"session/set_mode requires string modeId");let h=ln(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=w=>re(q.InvalidParams,w),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=ln(e.manager,f.sessionId),y=m.buildConfigOptions().find(w=>w.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(w=>w.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 re(q.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw re(q.MethodNotFound,`Method not found: ${f}`);return d(y,f),ln(e.manager,y).forwardRequest(f,u)})})}async function EA(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw re(q.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let 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 re(q.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,k)=>{if(!Array.isArray(S))throw re(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let A of S)if(typeof A!="string")throw re(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&ay.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,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(w[S]=k);Object.assign(w,h.env);let b=oy.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw rr(p,a)}}async function PA(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function ry(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(_d,t).catch(()=>{})}}function kc(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Ic(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function MA(n,e){if(!n||typeof n!="object")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:q.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Ui(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(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:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:q.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function _A(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw re(q.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw re(q.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw re(q.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ln(t.manager,r).addTransformer(i),{ok:!0}}async function $A(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw re(q.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw re(q.InvalidParams,"hydra-acp/attention/set requires string reason");return ln(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function FA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw re(q.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw re(q.InvalidParams,"hydra-acp/attention/clear requires string reason");return ln(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function OA(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[Mt]:Ed(e,t)}}function xc(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return aa(e.agentMeta,Ed(s,r))}function LA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ve},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:aa(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function BA(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function cy(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Ta(n,e,t,s,r){return{clientId:r??`cli_${pf(8)}`,connection:n,clientInfo:s}}function Ac(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var Cc=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as NA}from"crypto";import{McpServer as DA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as HA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as $t}from"zod";function hf(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function Kt(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var ly="Bearer ";function so(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(ly))return;let t=e.slice(ly.length).trim();return t.length>0?t:void 0}function UA(n){let e=new DA({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:$t.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return Kt(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:$t.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return Kt(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:$t.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:$t.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:$t.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return Kt(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:$t.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:$t.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return Kt({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:$t.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:$t.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:$t.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:$t.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:$t.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:$t.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:$t.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:$t.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:$t.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return Kt(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return Kt(t)}),e}var jA=1e4;function uy(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=UA(a),l=new HA({sessionIdGenerator:()=>NA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=so(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),jA)}),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}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Nd();import{randomUUID as qA}from"crypto";import{McpServer as WA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as zA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as dr}from"zod";function KA(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function JA(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function YA(n){let e=new WA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:dr.string().min(1).describe("Case-insensitive substring to search for."),limit:dr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:dr.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Kt({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=[],a=t.toLowerCase();for await(let{entryId:d,entry:l}of i.iterRecallNewestFirst()){let u=hf(l);if(!u)continue;let{kind:f}=u;if(f==="tool_call"&&!r)continue;let p=ji([l]),h=p.toLowerCase().indexOf(a);if(h<0)continue;let m=KA(f),y=JA(p,h),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(o.push({entryId:d,speaker:m,snippet:y,timestamp:w}),o.length>=s)break}o.sort((d,l)=>d.entryId-l.entryId);let c=o.length>=s;return Kt({matches:o,total_matched:o.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:dr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:dr.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return Kt({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<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getRecallTotalCount();if(o===0)return Kt({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),c=Math.min(s,o-1),d=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=await r.sliceRecallHistory(a,c),u=ji(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:dr.string().optional(),file_path:dr.string().optional(),limit:dr.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Kt({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 t=="string"&&t.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=new Map,d=Math.max(r*4,200);for await(let{entryId:p,entry:h}of i.iterRecallNewestFirst()){let m=hf(h);if(!m)continue;let{kind:y,update:w}=m;if(y!=="tool_call"&&y!=="tool_call_update")continue;let b=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:`__noid_${p}`,S=c.get(b);S||(S={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},c.set(b,S)),p<S.entryId&&(S.entryId=p),typeof w.name=="string"&&w.name.length>0?S.toolName=w.name:S.toolName==="(unnamed)"&&typeof w.title=="string"&&w.title.length>0&&(S.toolName=w.title);let k=w.rawInput;if(k&&typeof k=="object"&&!Array.isArray(k)&&Object.keys(k).length>0)for(let[A,E]of Object.entries(k))S.rawInput[A]===void 0&&(S.rawInput[A]=E);if(Array.isArray(w.locations))for(let A of w.locations){let E=A?.path;typeof E=="string"&&E.length>0&&!S.locations.includes(E)&&S.locations.push(E)}if(typeof w.status=="string"&&S.status==="in_progress"&&(S.status=w.status),h.recordedAt!==void 0&&S.timestamp===void 0&&(S.timestamp=String(h.recordedAt)),c.size>=d)break}let l=[...c.keys()].sort((p,h)=>c.get(p).entryId-c.get(h).entryId),u=[];for(let p of l){let h=c.get(p);if(t!==void 0&&h.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let y=s.toLowerCase(),w=["file_path","filePath","path"],b=!1;for(let S of w){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let S of h.locations)if(S.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),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 Kt({calls:u,truncated:f})}),e}var VA=1e4;function fy(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=YA(a),l=new zA({sessionIdGenerator:()=>qA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=so(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),VA)}),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}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var Rc=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as sC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as rC}from"crypto";import{Server as QA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as GA,ListToolsRequestSchema as XA}from"@modelcontextprotocol/sdk/types.js";function py(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new QA({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(XA,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(GA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,u=eC(l,c.sendNotification);try{let f=await r(),p=await tC(e.connection,n,d,a.params.arguments??{},f);return nC(p,d)}catch(f){return mf(f instanceof Error?f.message:String(f))}finally{u()}}),i}var ZA=15e3;function eC(n,e,t=ZA){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function tC(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function nC(n,e){if(n===null||typeof n!="object")return mf(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:mf(`extension ${e} omitted content array`)}function mf(n){return{content:[{type:"text",text:n}],isError:!0}}var iC=1e4;function hy(n,e,t){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let u of s.values()){let f=u.get(l);f!==void 0&&(u.delete(l),r(f))}}async function o(l,u){for(let[f,p]of s){if(e.lookup(f)?.session?.sessionId!==l)continue;let m=p.get(u);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(l=>{i(l)});async function a(l,u){let f=s.get(l);f===void 0&&(f=new Map,s.set(l,f),e.addDisposer(l,async()=>{let k=s.get(l);if(k!==void 0){s.delete(l);for(let A of k.values())await r(A)}}));let p=f.get(u);if(p!==void 0)return p.transport;let h=t.lookup(u);if(h===void 0)return;let b=py(u,h,async()=>{let k=e.lookup(l);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let A,E=new Promise(H=>{A=setTimeout(()=>H(void 0),iC)}),P=await Promise.race([k.sessionReady.catch(()=>{}),E]);if(A!==void 0&&clearTimeout(A),P===void 0)throw new Error("session not ready");return P.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async k=>{let A=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:k});if(!A||typeof A!="object")return;let E=A.tools;if(!Array.isArray(E))return;let P=[];for(let H of E){if(!H||typeof H!="object")continue;let _=H;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let F={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(F.outputSchema=_.outputSchema),P.push(F)}return P}}),S=new sC({sessionIdGenerator:()=>rC()});return await b.connect(S),f.set(u,{server:b,transport:S}),S}async function c(l,u){let f=so(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let h=l.params.name,m=await a(f,h);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${h}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let d={config:{skipAuth:!0}};return n.post("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.get("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.delete("/mcp/:name",d,async(l,u)=>{await c(l,u)}),{notifyToolListChanged:o}}async function vy(n,e){fC(n);let t=n.daemon.tls?await ls.readFile(tt(n.daemon.tls.key)):void 0,s=n.daemon.tls?await ls.readFile(tt(n.daemon.tls.cert)):void 0;await ls.mkdir(O.home(),{recursive:!0});let{stream:r,fileStream:i}=await lC(n.daemon.logLevel),o=oC({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(aC,{options:{handleProtocols:Rh}}),ou(ee=>{o.log.info(ee)}),cu(ee=>{o.log.info(ee)});let a=await oc.load(),c=new uc,d=new lc,l=new cc([new ac(e),new dc(a),d]),u=Sg({validator:l});o.addHook("onRequest",async(ee,ce)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await u(ee,ce)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Cd(n,{onFetched:()=>{fg(h,b)}});tf(ee=>o.log.info(ee));let m={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},y=ee=>nr.spawn({...ee,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Mh(n.compressToolContent);let w=new rc,b=new Gd(h,y,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:n.npmRegistry,extensionCommands:w,defaultCwd:n.defaultCwd}),S=new nc(Zp(n),void 0,{tokenRegistry:d}),k=new sc(eh(n),void 0,{tokenRegistry:d});Kg(o,ve,ir(n));let A=new Cc,E=new Rc,P,H=()=>{if(P!==void 0)return P;let ee=o.server.address();return P=`http://127.0.0.1:${ee&&typeof ee=="object"?ee.port:n.daemon.port}`,P};Wg(o,b,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:E,mcpTokenRegistry:A,getDaemonOrigin:H}),zg(o,h,b,{npmRegistry:n.npmRegistry}),Jg(o,S),Yg(o,k),Vg(o,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),sy(o,{store:a,rateLimiter:c}),uy(o,A),fy(o,A);let _=hy(o,A,E);dy(o,{validator:l,manager:b,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(ee,ce)=>S.reportVersion(ee,ce),onTransformerVersion:(ee,ce)=>k.reportVersion(ee,ce),transformers:k,extensionCommands:w,mcpTokenRegistry:A,extensionMcp:E,extensionMcpControls:_,getDaemonOrigin:H,registry:h});let F=!!n.daemon.tls;await o.listen({host:F?"127.0.0.1":n.daemon.host,port:F?0:n.daemon.port});let B=o.server.address(),N=B&&typeof B=="object"?B.port:n.daemon.port,j,G=n.daemon.host,X=N;if(F&&t&&s){j=uC({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:N,tlsOptions:{key:t,cert:s},logger:o.log});let ee=j.address();ee&&typeof ee=="object"&&(X=ee.port)}await ls.mkdir(O.home(),{recursive:!0}),await dh({pid:process.pid,host:G,port:X,loopbackPort:N,startedAt:new Date().toISOString()});let V={daemonUrl:`http://127.0.0.1:${N}`,daemonHost:"127.0.0.1",daemonPort:N,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${N}/acp`,hydraHome:O.home()};S.setContext(V),k.setContext(V),await S.start(),await k.start();try{await b.reconcilePermissionFlags()}catch(ee){o.log.warn(`permission flag reconcile failed: ${ee.message}`)}b.resurrectPendingQueues().catch(ee=>{o.log.warn(`queue replay scan failed: ${ee.message}`)}),b.resumePendingCompactions().catch(ee=>{o.log.warn(`compaction resume scan failed: ${ee.message}`)}),b.resumePendingAgentSwaps().catch(ee=>{o.log.warn(`agent-swap resume scan failed: ${ee.message}`)});let ye=n.daemon.agentSyncIntervalMinutes*60*1e3,Be=ye>0?pg({registry:h,manager:b,intervalMs:ye,logger:m}):void 0,mt=n.daemon.sessionGcIntervalMinutes*60*1e3,_e=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,gs=mt>0?hg({manager:b,intervalMs:mt,maxAgeMs:_e,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:d,shutdown:async()=>{gs&&gs(),Be&&Be(),clearInterval(f),clearInterval(p);let ee=async(ce,$e)=>{try{await $e()}catch(fn){o.log.warn(`shutdown step ${ce} failed: ${fn instanceof Error?fn.message:String(fn)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>S.stop()),await ee("transformers.stop",()=>k.stop()),await ee("manager.closeAll",()=>b.closeAll()),await ee("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await ee("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await ee("manager.flushMetaWrites",()=>b.flushMetaWrites()),await ee("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),ou(null),cu(null),tf(null),j&&await ee("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await ee("app.close",()=>o.close());try{yy.unlinkSync(O.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}var gy=20;async function cC(n,e){let t=ro.dirname(n),s=ro.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await ls.readdir(t)}catch{return}let o=[];for(let c of i){let d=c.match(r);d&&o.push({name:c,n:Number(d[1])})}if(o.length<=e)return;o.sort((c,d)=>c.n-d.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(c=>ls.unlink(ro.join(t,c.name))))}async function lC(n){await cC(O.logFile(),gy);let e=await dC({file:O.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:gy,removeOtherLogFiles:!0}}),t=my.destination(2);return{stream:my.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function uC(n){let e=by.createServer(n.tlsOptions,t=>{let s=wy.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function fC(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Yr();cn();xa();Ea();async function xy(n={}){let e=await Ie(),t=await Zo();if(await Tc(e)){let r=await ao();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
329
+ `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),n.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??[]}}),n.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 w of y)w.source===u.source&&p.push({...w,sessionId:h.sessionId})}return{flags:p}}),n.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 w=e.get(f);if(w){if(m.length>0&&y.length>0)w.clearAttentionFlag(m,y);else{let E=Array.from(w.listAttentionFlags()).map(P=>`${P.source}::${P.reason}`);for(let P of E)w.clearAttentionFlag(P.split("::")[0],P.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let b=e.store,S=await b.read(f);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],A;if(m.length>0&&y.length>0){let E=`${m}::${y}`;A=k.filter(P=>`${P.source}::${P.reason}`!==E)}else A=[];if(A.length===k.length&&A.every((E,P)=>E.source===k[P].source&&E.reason===k[P].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:A}),l.code(204).send()})}_t();function zg(n,e,t,s={}){n.get("/v1/agents",async()=>Fi(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await Sn(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})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await t.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===q.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function Kg(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var mA=/^[A-Za-z0-9._-]+$/;function wc(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=t.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(i,o)=>{let a=i.body??{},c=gA(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=t.register(c.config);o.code(201).send(d)}catch(d){Ra(o,d)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(c){Ra(o,c)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await t.startByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await t.stopByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await t.restartByName(a);o.code(200).send(c)}catch(c){Ra(o,c)}})}function Ra(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function gA(n){let e=n.name;if(typeof e!="string"||!mA.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function Jg(n,e){wc(n,"extension",e)}function Yg(n,e){wc(n,"transformer",e)}function Vg(n,e){n.get("/v1/config",async()=>e)}import{z as to}from"zod";be();import*as ar from"fs/promises";import*as Zg from"path";import{randomBytes as yA,scrypt as wA,timingSafeEqual as bA}from"crypto";import{promisify as vA}from"util";var ey=vA(wA);function ff(){return Zg.join(O.home(),"password-hash")}var Qg=32768,Gg=8,Xg=1,SA=64,kA=16,ty=128*1024*1024;async function ny(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=yA(kA),t=await ey(n,e,SA,{N:Qg,r:Gg,p:Xg,maxmem:ty}),s=`scrypt$${Qg}$${Gg}$${Xg}$${e.toString("hex")}$${t.toString("hex")}
330
+ `;await ar.mkdir(O.home(),{recursive:!0}),await ar.writeFile(ff(),s,{encoding:"utf8",mode:384})}async function bc(){try{return(await ar.readFile(ff(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function vc(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ar.readFile(ff(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let c=await ey(n,o,a.length,{N:s,r,p:i,maxmem:ty});return c.length!==a.length?!1:bA(c,a)}var IA=to.object({password:to.string().min(1),label:to.string().min(1).max(256).optional(),ttlSec:to.number().int().positive().optional()}),xA=to.object({id:to.string().optional()}).optional();function sy(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=AA(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=IA.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await bc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await vc(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=xA.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function AA(n){return n.ip||"unknown"}jr();no();import{nanoid as pf}from"nanoid";Bd();_t();cn();import{randomBytes as iy}from"crypto";import*as oy from"os";import*as ay from"path";function re(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function PA(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let 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 ln(n,e,t){let s=n.get(e);if(!s)throw re(q.SessionNotFound,t??`session ${e} not found`);return s}async function Sc(n,e){let t=eo(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=iy(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],c=cf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),d;try{d=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(d),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,u=n.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return DA(d,n),cy(d.sessionId,n),d}function dy(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=kg({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=ls(t),a=new zt(o),c={clientId:`hydra_client_${pf(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 re(q.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Kh.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)),NA()}),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 w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return 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 p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let S={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(S.outputSchema=b.outputSchema),S}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,y),{ok:!0,registered:y.length}});let f=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw re(q.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(!e.manager)throw re(q.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=f(p);if(!e.manager)throw re(q.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(m.value===void 0)throw re(q.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw re(q.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw re(q.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw re(q.InvalidParams,"key is required");if(!e.manager)throw re(q.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw re(q.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{u.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async f=>{let p=f??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw re(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw re(-32602,"emit_message requires method");let b=ln(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return b.dischargeClaim(S,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw re(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw re(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw re(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw re(-32602,"hydra-acp/session/request_permission requires sessionId");return ln(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>FA(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let p=f??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,S=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let P=e.manager.get(y);P&&(m=P.cwd)}if(!m)throw re(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:S,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,b=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let u=async(f,p)=>{let h=f??{};if(typeof h.sessionId!="string")throw re(q.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async f=>(await u(f,"session/delete"),{})),a.onRequest("session/close",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw re(q.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw re(q.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async f=>{let{id:p,existed:h}=await u(f,"hydra-acp/session/delete");if(!h)throw re(q.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw re(-32602,"await_child requires childSessionId");let w=ln(e.manager,h,`child session ${h} not found`);return new Promise(b=>{let A=[],E=[],P=0,H=!1,_,F,B=!1,N=()=>{B||(B=!0,clearTimeout(j),_?.(),F?.(),b(H?{entries:A,truncated:!0}:{entries:A}))};_=w.onBroadcast(G=>{let X=PA(G);for(A.push(G),E.push(X),P+=X;A.length>0&&(A.length>1e3||P>1048576);)A.shift(),P-=E.shift()??0,H=!0;m==="turn_complete"&&G.params?.update?.sessionUpdate==="turn_complete"&&N()});let j=setTimeout(N,y);typeof j.unref=="function"&&j.unref(),F=w.onClose(()=>N())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw re(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>OA(f,i.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>LA(f,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let p=f??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw re(q.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 re(q.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>MA(u,e)),a.onRequest("logout",async u=>_A(u,e)),a.onRequest("session/new",async u=>{let f=Jh.parse(u),p=an(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(N=>typeof N=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,w,b=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=iy(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...f.mcpServers??[],j]}let S,k,A=eo(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=cf({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ry(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(N){throw w!==void 0&&w.abandon(N instanceof Error?N:void 0),k!==void 0&&k.abandon(N instanceof Error?N:void 0),A!==void 0&&A.abandon(N instanceof Error?N:void 0),N}if(y!==void 0&&w!==void 0&&e.mcpTokenRegistry!==void 0){let N=y,j=e.mcpTokenRegistry;w.complete(P),P.onClose(()=>{j.unbind(N)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=S,j=e.mcpTokenRegistry;k.complete(P),P.onClose(()=>{j.unbind(N)})}A!==void 0&&A.bindToSession(P),cy(P.sessionId,e);let H,_;try{Ac(c,P,P.sessionId),H=Ta(a,P,c),{entries:_}=await P.attach(H,"full")}catch(N){throw await P.close({deleteRecord:!1}).catch(()=>{}),N}c.attached.set(P.sessionId,{sessionId:P.sessionId,clientId:H.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of _){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let F=kc(P),B=Ic(P);return{sessionId:P.sessionId,...F?{modes:F}:{},...B?{models:B}:{},configOptions:P.buildConfigOptions(),_meta:xc(e.manager,P,{clientId:H.clientId})}}),a.onRequest("session/attach",async u=>{let f=Vh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=an(f._meta),m=h.resume,y=h.readonly===!0,w=h.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(b);if(!S&&y){let B=await e.manager.loadFromDisk(b);if(!B)throw re(q.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(b),j=f.clientId??`cli_${pf(8)}`;c.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${j} attachedCount=${c.attached.size} replayed=${N.length}`);for(let G of N)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:N.length,_meta:BA(B)}}let k=!S;if(!S){let B=await e.manager.loadFromDisk(b),N=B;if(m&&(N={...B,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}:{}}),!N)throw re(q.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw re(q.SessionNotFound,`session ${f.sessionId} was deleted`);let j=N.originatingClient?N:{...N,originatingClient:c.clientInfo},G=w!==void 0?{...j,forwardedEnv:w}:j;S=await Sc(e,{...G,onInstallProgress:ry(a)})}Ac(c,S,S.sessionId);let A=Ta(a,S,c,f.clientInfo,f.clientId),E=h.replayMode==="drip",{entries:P,appliedPolicy:H}=await S.attach(A,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(S.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${H} replayed=${P.length} readonly=${y}${E?" replayMode=drip":""}`),E){let B=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,N=750;(async()=>{let j=null;for(let G of P){let X=typeof G.recordedAt=="number"?G.recordedAt:null;if(j!==null&&X!==null){let V=Math.min(N,Math.max(0,(X-j)/B));V>0&&await new Promise(ye=>setTimeout(ye,V))}X!==null&&(j=X);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let B=0;B<P.length&&!a.isClosed();B++){let N=P[B],j=a.notify(N.method,N.params).catch(()=>{});(B+1)%200===0&&await j}S.replayPendingPermissions(A);let _=kc(S),F=Ic(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:H,replayed:P.length,..._?{modes:_}:{},...F?{models:F}:{},configOptions:S.buildConfigOptions(),_meta:xc(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=Qh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw re(q.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:{[Mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Gh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==qr).map(Xh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw re(q.InternalError,"agent registry unavailable");return Fi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw re(q.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=Zh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),re(q.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 re(q.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Sc(e,m);let y=Ta(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=Md.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.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=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=Md.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=tm.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),ln(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Md.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),ln(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=nm.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),ln(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=sm.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw re(q.SessionNotFound,"not attached to session");return ln(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 re(q.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 re(q.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Sc(e,S)}Ac(c,m,m.sessionId);let y=Ta(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=kc(m),b=Ic(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:xc(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 re(q.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw re(q.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Sc(e,k)}Ac(c,m,m.sessionId);let y=Ta(a,m,c),{entries:w}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of w){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let b=kc(m),S=Ic(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:xc(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=$A(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),re(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId: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 re(q.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw re(q.InvalidParams,"session/set_mode requires string modeId");let h=ln(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=w=>re(q.InvalidParams,w),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=ln(e.manager,f.sessionId),y=m.buildConfigOptions().find(w=>w.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(w=>w.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 re(q.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw re(q.MethodNotFound,`Method not found: ${f}`);return d(y,f),ln(e.manager,y).forwardRequest(f,u)})})}async function MA(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw re(q.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let 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 re(q.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,k)=>{if(!Array.isArray(S))throw re(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let A of S)if(typeof A!="string")throw re(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&ay.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,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(w[S]=k);Object.assign(w,h.env);let b=oy.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw rr(p,a)}}async function _A(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function ry(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(_d,t).catch(()=>{})}}function kc(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Ic(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function $A(n,e){if(!n||typeof n!="object")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:q.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:q.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Ui(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(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:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:q.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function FA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw re(q.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw re(q.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw re(q.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ln(t.manager,r).addTransformer(i),{ok:!0}}async function OA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw re(q.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw re(q.InvalidParams,"hydra-acp/attention/set requires string reason");return ln(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function LA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw re(q.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw re(q.InvalidParams,"hydra-acp/attention/clear requires string reason");return ln(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function BA(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[Mt]:Ed(e,t)}}function xc(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return aa(e.agentMeta,Ed(s,r))}function NA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ve},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:aa(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function DA(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function cy(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Ta(n,e,t,s,r){return{clientId:r??`cli_${pf(8)}`,connection:n,clientInfo:s}}function Ac(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var Cc=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as HA}from"crypto";import{McpServer as UA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as jA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as $t}from"zod";function hf(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function Kt(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var ly="Bearer ";function so(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(ly))return;let t=e.slice(ly.length).trim();return t.length>0?t:void 0}function qA(n){let e=new UA({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:$t.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return Kt(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:$t.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return Kt(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:$t.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:$t.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:$t.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return Kt(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:$t.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:$t.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return Kt({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:$t.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:$t.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:$t.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:$t.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:$t.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:$t.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:$t.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:$t.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:$t.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return Kt(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return Kt(t)}),e}var WA=1e4;function uy(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=qA(a),l=new jA({sessionIdGenerator:()=>HA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=so(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),WA)}),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}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Nd();import{randomUUID as zA}from"crypto";import{McpServer as KA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as JA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as dr}from"zod";function YA(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function VA(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function QA(n){let e=new KA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:dr.string().min(1).describe("Case-insensitive substring to search for."),limit:dr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:dr.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Kt({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=[],a=t.toLowerCase();for await(let{entryId:d,entry:l}of i.iterRecallNewestFirst()){let u=hf(l);if(!u)continue;let{kind:f}=u;if(f==="tool_call"&&!r)continue;let p=ji([l]),h=p.toLowerCase().indexOf(a);if(h<0)continue;let m=YA(f),y=VA(p,h),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(o.push({entryId:d,speaker:m,snippet:y,timestamp:w}),o.length>=s)break}o.sort((d,l)=>d.entryId-l.entryId);let c=o.length>=s;return Kt({matches:o,total_matched:o.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:dr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:dr.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return Kt({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<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getRecallTotalCount();if(o===0)return Kt({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),c=Math.min(s,o-1),d=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=await r.sliceRecallHistory(a,c),u=ji(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:dr.string().optional(),file_path:dr.string().optional(),limit:dr.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Kt({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 t=="string"&&t.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=new Map,d=Math.max(r*4,200);for await(let{entryId:p,entry:h}of i.iterRecallNewestFirst()){let m=hf(h);if(!m)continue;let{kind:y,update:w}=m;if(y!=="tool_call"&&y!=="tool_call_update")continue;let b=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:`__noid_${p}`,S=c.get(b);S||(S={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},c.set(b,S)),p<S.entryId&&(S.entryId=p),typeof w.name=="string"&&w.name.length>0?S.toolName=w.name:S.toolName==="(unnamed)"&&typeof w.title=="string"&&w.title.length>0&&(S.toolName=w.title);let k=w.rawInput;if(k&&typeof k=="object"&&!Array.isArray(k)&&Object.keys(k).length>0)for(let[A,E]of Object.entries(k))S.rawInput[A]===void 0&&(S.rawInput[A]=E);if(Array.isArray(w.locations))for(let A of w.locations){let E=A?.path;typeof E=="string"&&E.length>0&&!S.locations.includes(E)&&S.locations.push(E)}if(typeof w.status=="string"&&S.status==="in_progress"&&(S.status=w.status),h.recordedAt!==void 0&&S.timestamp===void 0&&(S.timestamp=String(h.recordedAt)),c.size>=d)break}let l=[...c.keys()].sort((p,h)=>c.get(p).entryId-c.get(h).entryId),u=[];for(let p of l){let h=c.get(p);if(t!==void 0&&h.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let y=s.toLowerCase(),w=["file_path","filePath","path"],b=!1;for(let S of w){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let S of h.locations)if(S.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),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 Kt({calls:u,truncated:f})}),e}var GA=1e4;function fy(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=QA(a),l=new JA({sessionIdGenerator:()=>zA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=so(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),GA)}),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}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var Rc=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as iC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as oC}from"crypto";import{Server as XA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as ZA,ListToolsRequestSchema as eC}from"@modelcontextprotocol/sdk/types.js";function py(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new XA({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(eC,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(ZA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,u=nC(l,c.sendNotification);try{let f=await r(),p=await sC(e.connection,n,d,a.params.arguments??{},f);return rC(p,d)}catch(f){return mf(f instanceof Error?f.message:String(f))}finally{u()}}),i}var tC=15e3;function nC(n,e,t=tC){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function sC(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function rC(n,e){if(n===null||typeof n!="object")return mf(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:mf(`extension ${e} omitted content array`)}function mf(n){return{content:[{type:"text",text:n}],isError:!0}}var aC=1e4;function hy(n,e,t){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let u of s.values()){let f=u.get(l);f!==void 0&&(u.delete(l),r(f))}}async function o(l,u){for(let[f,p]of s){if(e.lookup(f)?.session?.sessionId!==l)continue;let m=p.get(u);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(l=>{i(l)});async function a(l,u){let f=s.get(l);f===void 0&&(f=new Map,s.set(l,f),e.addDisposer(l,async()=>{let k=s.get(l);if(k!==void 0){s.delete(l);for(let A of k.values())await r(A)}}));let p=f.get(u);if(p!==void 0)return p.transport;let h=t.lookup(u);if(h===void 0)return;let b=py(u,h,async()=>{let k=e.lookup(l);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let A,E=new Promise(H=>{A=setTimeout(()=>H(void 0),aC)}),P=await Promise.race([k.sessionReady.catch(()=>{}),E]);if(A!==void 0&&clearTimeout(A),P===void 0)throw new Error("session not ready");return P.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async k=>{let A=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:k});if(!A||typeof A!="object")return;let E=A.tools;if(!Array.isArray(E))return;let P=[];for(let H of E){if(!H||typeof H!="object")continue;let _=H;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let F={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(F.outputSchema=_.outputSchema),P.push(F)}return P}}),S=new iC({sessionIdGenerator:()=>oC()});return await b.connect(S),f.set(u,{server:b,transport:S}),S}async function c(l,u){let f=so(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let h=l.params.name,m=await a(f,h);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${h}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let d={config:{skipAuth:!0}};return n.post("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.get("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.delete("/mcp/:name",d,async(l,u)=>{await c(l,u)}),{notifyToolListChanged:o}}async function vy(n,e){hC(n);let t=n.daemon.tls?await us.readFile(tt(n.daemon.tls.key)):void 0,s=n.daemon.tls?await us.readFile(tt(n.daemon.tls.cert)):void 0;await us.mkdir(O.home(),{recursive:!0});let{stream:r,fileStream:i}=await fC(n.daemon.logLevel),o=dC({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(cC,{options:{handleProtocols:Rh}}),ou(ee=>{o.log.info(ee)}),cu(ee=>{o.log.info(ee)});let a=await oc.load(),c=new uc,d=new lc,l=new cc([new ac(e),new dc(a),d]),u=Sg({validator:l});o.addHook("onRequest",async(ee,ce)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await u(ee,ce)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Cd(n,{onFetched:()=>{fg(h,b)}});tf(ee=>o.log.info(ee));let m={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},y=ee=>nr.spawn({...ee,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Mh(n.compressToolContent);let w=new rc,b=new Gd(h,y,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:m,npmRegistry:n.npmRegistry,extensionCommands:w,defaultCwd:n.defaultCwd}),S=new nc(Zp(n),void 0,{tokenRegistry:d}),k=new sc(eh(n),void 0,{tokenRegistry:d});Kg(o,ve,ir(n));let A=new Cc,E=new Rc,P,H=()=>{if(P!==void 0)return P;let ee=o.server.address();return P=`http://127.0.0.1:${ee&&typeof ee=="object"?ee.port:n.daemon.port}`,P};Wg(o,b,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:E,mcpTokenRegistry:A,getDaemonOrigin:H}),zg(o,h,b,{npmRegistry:n.npmRegistry}),Jg(o,S),Yg(o,k),Vg(o,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),sy(o,{store:a,rateLimiter:c}),uy(o,A),fy(o,A);let _=hy(o,A,E);dy(o,{validator:l,manager:b,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(ee,ce)=>S.reportVersion(ee,ce),onTransformerVersion:(ee,ce)=>k.reportVersion(ee,ce),transformers:k,extensionCommands:w,mcpTokenRegistry:A,extensionMcp:E,extensionMcpControls:_,getDaemonOrigin:H,registry:h});let F=!!n.daemon.tls;await o.listen({host:F?"127.0.0.1":n.daemon.host,port:F?0:n.daemon.port});let B=o.server.address(),N=B&&typeof B=="object"?B.port:n.daemon.port,j,G=n.daemon.host,X=N;if(F&&t&&s){j=pC({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:N,tlsOptions:{key:t,cert:s},logger:o.log});let ee=j.address();ee&&typeof ee=="object"&&(X=ee.port)}await us.mkdir(O.home(),{recursive:!0}),await dh({pid:process.pid,host:G,port:X,loopbackPort:N,startedAt:new Date().toISOString()});let V={daemonUrl:`http://127.0.0.1:${N}`,daemonHost:"127.0.0.1",daemonPort:N,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${N}/acp`,hydraHome:O.home()};S.setContext(V),k.setContext(V),await S.start(),await k.start();try{await b.reconcilePermissionFlags()}catch(ee){o.log.warn(`permission flag reconcile failed: ${ee.message}`)}b.resurrectPendingQueues().catch(ee=>{o.log.warn(`queue replay scan failed: ${ee.message}`)}),b.resumePendingCompactions().catch(ee=>{o.log.warn(`compaction resume scan failed: ${ee.message}`)}),b.resumePendingAgentSwaps().catch(ee=>{o.log.warn(`agent-swap resume scan failed: ${ee.message}`)});let ye=n.daemon.agentSyncIntervalMinutes*60*1e3,Be=ye>0?pg({registry:h,manager:b,intervalMs:ye,logger:m}):void 0,mt=n.daemon.sessionGcIntervalMinutes*60*1e3,_e=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ys=mt>0?hg({manager:b,intervalMs:mt,maxAgeMs:_e,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:d,shutdown:async()=>{ys&&ys(),Be&&Be(),clearInterval(f),clearInterval(p);let ee=async(ce,$e)=>{try{await $e()}catch(fn){o.log.warn(`shutdown step ${ce} failed: ${fn instanceof Error?fn.message:String(fn)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>S.stop()),await ee("transformers.stop",()=>k.stop()),await ee("manager.closeAll",()=>b.closeAll()),await ee("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await ee("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await ee("manager.flushMetaWrites",()=>b.flushMetaWrites()),await ee("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),ou(null),cu(null),tf(null),j&&await ee("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await ee("app.close",()=>o.close());try{yy.unlinkSync(O.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}var gy=20;async function uC(n,e){let t=ro.dirname(n),s=ro.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await us.readdir(t)}catch{return}let o=[];for(let c of i){let d=c.match(r);d&&o.push({name:c,n:Number(d[1])})}if(o.length<=e)return;o.sort((c,d)=>c.n-d.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(c=>us.unlink(ro.join(t,c.name))))}async function fC(n){await uC(O.logFile(),gy);let e=await lC({file:O.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:gy,removeOtherLogFiles:!0}}),t=my.destination(2);return{stream:my.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function pC(n){let e=by.createServer(n.tlsOptions,t=>{let s=wy.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function hC(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Yr();cn();xa();Ea();async function Ay(n={}){let e=await Ie(),t=await Zo();if(await Tc(e)){let r=await ao();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
331
331
  `);return}if(ki(n,"foreground")){process.title="hydra-acp-daemon";let r=await vy(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
332
332
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
333
333
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
334
334
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
335
335
  `),process.exit(1)},i);c.unref();try{await r.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
336
336
  `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Ec(),await Pc(e);let s=await ao();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
337
- `)}async function Ay(){let n=await ao();if(!n){process.stdout.write(`No running daemon found.
337
+ `)}async function Cy(){let n=await ao();if(!n){process.stdout.write(`No running daemon found.
338
338
  `);return}try{process.kill(n.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${n.pid}
339
339
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
340
- `)}}async function Cy(){let n=await Ie();await Zo();let e=await ao();if(e&&Ln(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
340
+ `)}}async function Ry(){let n=await Ie();await Zo();let e=await ao();if(e&&bn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
341
341
  `);try{process.kill(e.pid,"SIGTERM")}catch(t){process.stderr.write(`Failed to signal daemon: ${t.message}
342
- `),process.exit(1)}await kC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
342
+ `),process.exit(1)}await AC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
343
343
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
344
344
  `);if(Ec(),await Pc(n),await Tc(n)){let t=await ao();process.stdout.write(`Daemon restarted on ${n.daemon.host}:${n.daemon.port}`+(t?` pid=${t.pid}`:"")+`
345
- `)}}async function kC(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!Ln(n))return!0;await SC(50)}return!1}async function Ry(n){await oo(O.currentLogFile(),n,"No daemon log file (daemon never ran?)")}async function Ty(){let n=await ao();if(!n){process.stdout.write(`Daemon: not running
345
+ `)}}async function AC(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!bn(n))return!0;await xC(50)}return!1}async function Ty(n){await oo(O.currentLogFile(),n,"No daemon log file (daemon never ran?)")}async function Ey(){let n=await ao();if(!n){process.stdout.write(`Daemon: not running
346
346
  `),process.stdout.write(`CLI version: ${ve}
347
- `);return}let e=Ln(n.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${n.pid} host=${n.host} port=${n.port} started=${n.startedAt}
347
+ `);return}let e=bn(n.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${n.pid} host=${n.host} port=${n.port} started=${n.startedAt}
348
348
  `);let t,s;if(e)try{let o=await Ie();t=await Jr(o),s=ir(o)}catch{}if(!t||t.version===void 0){process.stdout.write(`CLI version: ${ve}
349
349
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
350
350
  `);return}let r=t.version===ve,i=t.configDigest!==void 0&&s!==void 0&&t.configDigest===s;if(r&&i){process.stdout.write(`Version: ${ve}
351
351
  `);return}process.stdout.write(`CLI version: ${ve}
352
352
  `),process.stdout.write(`Daemon version: ${t.version}
353
- `),r||process.stdout.write(Iy.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Iy.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function ao(){return Ms()}Ge();Es();lr();Dr();ta();is();Ma();zr();import*as Sn from"fs/promises";import*as Uy from"os";import*as kn from"path";Nc();async function jy(n={}){let e=await Ie(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",r=(await Oe(`/v1/sessions${t}`,{expectStatus:200})).body,i=r.sessions,o=n.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
353
+ `),r||process.stdout.write(xy.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(xy.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function ao(){return ss()}Ge();Ps();lr();Dr();ta();os();Ma();zr();import*as kn from"fs/promises";import*as jy from"os";import*as In from"path";Nc();async function qy(n={}){let e=await Ie(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",r=(await Oe(`/v1/sessions${t}`,{expectStatus:200})).body,i=r.sessions,o=n.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
354
354
  `);return}if(a.length===0){if(o==="local"&&r.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
355
355
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
356
356
  `);return}process.stdout.write(`No active sessions.
@@ -358,39 +358,39 @@ ${Eu}`;return Dm(n,s,Om)}function CI(n){if(!n||typeof n!="object")return"";let e
358
358
  `);for(let y of f)process.stdout.write(ur(y,h,m,p)+`
359
359
  `);l>0&&process.stdout.write(`
360
360
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
361
- `)}async function qy(n){n||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
361
+ `)}async function Wy(n){n||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
362
362
  `),process.exit(2));let e=await Oe(`/v1/sessions/${n}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
363
363
  `),process.exit(1)),process.stdout.write(`Killed ${n}
364
- `)}async function Wy(n){n||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
364
+ `)}async function zy(n){n||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
365
365
  `),process.exit(2));let e=await Oe(`/v1/sessions/${n}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
366
366
  `),process.exit(1)),process.stdout.write(`Removed ${n}
367
- `)}async function zy(n){let e=n.maxAgeDays!==void 0?n.maxAgeDays:0,t={maxAgeDays:e};n.limit!==void 0&&(t.limit=n.limit),t.selection=n.keepUndecided?"explicit":"unpromoted";let r=(await Oe("/v1/sessions/collect",{method:"POST",body:t,expectStatus:200})).body;if(n.json){process.stdout.write(`${JSON.stringify(r,null,2)}
367
+ `)}async function Ky(n){let e=n.maxAgeDays!==void 0?n.maxAgeDays:0,t={maxAgeDays:e};n.limit!==void 0&&(t.limit=n.limit),t.selection=n.keepUndecided?"explicit":"unpromoted";let r=(await Oe("/v1/sessions/collect",{method:"POST",body:t,expectStatus:200})).body;if(n.json){process.stdout.write(`${JSON.stringify(r,null,2)}
368
368
  `);return}let i=n.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(r.considered===0){let a=e>0?` older than ${e}d`:"";process.stdout.write(`No ${i} sessions${a} found.
369
369
  `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${lo(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
370
370
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
371
371
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
372
- `)}async function Ky(n,e,t){n||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
372
+ `)}async function Jy(n,e,t){n||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
373
373
  `),process.exit(2));let s=await Fr(),r=await co(),i=t==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(n)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
374
374
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
375
375
  `)||process.stdout.write(`
376
- `);return}let c=e==="."?HC(o,n):e;await Sn.mkdir(kn.dirname(kn.resolve(c)),{recursive:!0}),await Sn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
377
- `)}async function Jy(n,e,t={}){n||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
378
- `),process.exit(2));let s=t.includeTools??!1,r,i,o=await OC(n);if(o!==null){let c=LC(o.raw);r=mc(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${kn.basename(n,kn.extname(n))}-${d}.md`}else{let c=await Fr(),d=await co(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(n)}/transcript`);s&&l.searchParams.set("tools","1");let u=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!u.ok){let p=await u.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${u.status}: ${p}
376
+ `);return}let c=e==="."?qC(o,n):e;await kn.mkdir(In.dirname(In.resolve(c)),{recursive:!0}),await kn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
377
+ `)}async function Yy(n,e,t={}){n||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
378
+ `),process.exit(2));let s=t.includeTools??!1,r,i,o=await NC(n);if(o!==null){let c=DC(o.raw);r=mc(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${In.basename(n,In.extname(n))}-${d}.md`}else{let c=await Fr(),d=await co(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(n)}/transcript`);s&&l.searchParams.set("tools","1");let u=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!u.ok){let p=await u.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${u.status}: ${p}
379
379
  `),process.exit(1)}r=await u.text();let f=new Date().toISOString().replace(/[:.]/g,"-");i=`hydra-${n}-${f}.md`}if(!e){process.stdout.write(r),r.endsWith(`
380
380
  `)||process.stdout.write(`
381
- `);return}let a=e==="."?i:e;await Sn.mkdir(kn.dirname(kn.resolve(a)),{recursive:!0}),await Sn.writeFile(a,r,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${a}
382
- `)}async function OC(n){try{if(!(await Sn.stat(n)).isFile())return null}catch{return null}let e=await Sn.readFile(n,"utf8");try{return{raw:JSON.parse(e)}}catch(t){process.stderr.write(`Failed to parse bundle file: ${t.message}
383
- `),process.exit(1)}}function LC(n){try{return Nn(n)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
384
- `),process.exit(1)}}async function Yy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
385
- `),process.exit(2));let t;if(e.cwd!==void 0){let a=kn.resolve(e.cwd);try{(await Sn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
381
+ `);return}let a=e==="."?i:e;await kn.mkdir(In.dirname(In.resolve(a)),{recursive:!0}),await kn.writeFile(a,r,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${a}
382
+ `)}async function NC(n){try{if(!(await kn.stat(n)).isFile())return null}catch{return null}let e=await kn.readFile(n,"utf8");try{return{raw:JSON.parse(e)}}catch(t){process.stderr.write(`Failed to parse bundle file: ${t.message}
383
+ `),process.exit(1)}}function DC(n){try{return Nn(n)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
384
+ `),process.exit(1)}}async function Vy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
385
+ `),process.exit(2));let t;if(e.cwd!==void 0){let a=In.resolve(e.cwd);try{(await kn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
386
386
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
387
- `),process.exit(1)}t=a}let s;n==="-"?s=await DC():s=await Sn.readFile(n,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
388
- `),process.exit(1)}if(e.info===!0){let a=await Ie();NC(r,a.tui.cwdColumnMaxWidth);return}let i=await Oe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...t!==void 0?{cwd:t}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
387
+ `),process.exit(1)}t=a}let s;n==="-"?s=await jC():s=await kn.readFile(n,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
388
+ `),process.exit(1)}if(e.info===!0){let a=await Ie();UC(r,a.tui.cwdColumnMaxWidth);return}let i=await Oe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...t!==void 0?{cwd:t}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
389
389
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
390
390
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
391
391
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
392
- `)}function BC(n){return{sessionId:n.session.sessionId,cwd:n.session.cwd,agentId:n.session.agentId,currentUsage:n.session.currentUsage,title:n.session.title,importedFromMachine:n.exportedFrom.machine,attachedClients:0,updatedAt:n.session.updatedAt,status:"cold",compactionState:n.session.compactionState}}function NC(n,e){let t;try{t=Nn(n)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
393
- `),process.exit(1)}let s=BC(t),r=ho(s),i={columns:Bc,cwdMaxWidth:e},o=mo([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(po,o,a,i)+`
392
+ `)}function HC(n){return{sessionId:n.session.sessionId,cwd:n.session.cwd,agentId:n.session.agentId,currentUsage:n.session.currentUsage,title:n.session.title,importedFromMachine:n.exportedFrom.machine,attachedClients:0,updatedAt:n.session.updatedAt,status:"cold",compactionState:n.session.compactionState}}function UC(n,e){let t;try{t=Nn(n)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
393
+ `),process.exit(1)}let s=HC(t),r=ho(s),i={columns:Bc,cwdMaxWidth:e},o=mo([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(po,o,a,i)+`
394
394
  `),process.stdout.write(ur(r,o,a,i)+`
395
395
  `);let c=t.session.upstreamSessionId??"-";process.stdout.write(`
396
396
  lineage: ${t.session.lineageId}
@@ -399,21 +399,21 @@ origin session: ${t.session.sessionId}
399
399
  origin upstream: ${c}
400
400
  history entries: ${t.history.length}`+(t.promptHistory?`, prompt history: ${t.promptHistory.length}
401
401
  `:`
402
- `))}async function DC(){let n=[];for await(let e of process.stdin)n.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(n).toString("utf8")}function HC(n,e){let t=n.headers.get("content-disposition");if(t){let r=t.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function Vy(n,e={}){let t=await Ie(),s;if(n!==void 0&&n.length>0)s=n;else{let d=await Bt(t),l=e.cwd?kn.resolve(e.cwd):process.cwd(),u=await Dn(d,{cwd:l,all:!0}),f=Oc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
403
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=UC(e.host,t),a=pt(s),c=ih({host:r,port:i,sessionId:a});process.stdout.write(c+`
402
+ `))}async function jC(){let n=[];for await(let e of process.stdin)n.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(n).toString("utf8")}function qC(n,e){let t=n.headers.get("content-disposition");if(t){let r=t.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function Qy(n,e={}){let t=await Ie(),s;if(n!==void 0&&n.length>0)s=n;else{let d=await Bt(t),l=e.cwd?In.resolve(e.cwd):process.cwd(),u=await Dn(d,{cwd:l,all:!0}),f=Oc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
403
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=WC(e.host,t),a=pt(s),c=ih({host:r,port:i,sessionId:a});process.stdout.write(c+`
404
404
  `),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.
405
- `)}function UC(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Hy(n,On);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Hy(e.daemon.publicHost,On);return{host:t,port:s,isFallback:!1}}return jC(e.daemon.host)?{host:qC(),port:e.daemon.port,isFallback:!1}:Lr(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function jC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function qC(){let n=Uy.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Hy(n,e){if(n.startsWith("[")){let s=n.indexOf("]");if(s>0){let r=n.slice(1,s),i=n.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 t=n.lastIndexOf(":");if(t>0&&n.indexOf(":")===t){let s=n.slice(0,t),r=Number(n.slice(t+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:n,port:e}}Ff();Nc();Pf();Ge();be();Ea();lr();var RR={extension:{singular:"extension",plural:"extensions",logFile:n=>O.extensionLogFile(n)},transformer:{singular:"transformer",plural:"transformers",logFile:n=>O.transformerLogFile(n)}};function Wc(n){if(n&&typeof n=="object"&&"error"in n){let e=n.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function wo(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function zc(n){let e=RR[n],t=`/v1/${e.plural}`;async function s(){let u=(await Oe(t,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
405
+ `)}function WC(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Uy(n,Ln);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Uy(e.daemon.publicHost,Ln);return{host:t,port:s,isFallback:!1}}return zC(e.daemon.host)?{host:KC(),port:e.daemon.port,isFallback:!1}:Lr(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function zC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function KC(){let n=jy.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Uy(n,e){if(n.startsWith("[")){let s=n.indexOf("]");if(s>0){let r=n.slice(1,s),i=n.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 t=n.lastIndexOf(":");if(t>0&&n.indexOf(":")===t){let s=n.slice(0,t),r=Number(n.slice(t+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:n,port:e}}Ff();Nc();Pf();Ge();be();Ea();lr();var PR={extension:{singular:"extension",plural:"extensions",logFile:n=>O.extensionLogFile(n)},transformer:{singular:"transformer",plural:"transformers",logFile:n=>O.transformerLogFile(n)}};function Wc(n){if(n&&typeof n=="object"&&"error"in n){let e=n.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function wo(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function zc(n){let e=PR[n],t=`/v1/${e.plural}`;async function s(){let u=(await Oe(t,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
406
406
  `);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?lo(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:wo(p.name,f.map(y=>y.name)),status:wo(p.status,f.map(y=>y.status)),version:wo(p.version,f.map(y=>y.version)),pid:wo(p.pid,f.map(y=>y.pid)),restarts:wo(p.restarts,f.map(y=>y.restarts)),started:wo(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)+`
407
407
  `);for(let y of f)process.stdout.write(m(y)+`
408
408
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
409
409
  `)}async function r(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
410
410
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(d)){process.stderr.write(`Invalid ${e.singular} name '${d}': must match [A-Za-z0-9._-]+
411
- `),process.exit(2);return}await Ie();let u=await uo(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${uw(e.singular)} '${d}' already exists in config.
411
+ `),process.exit(2);return}await Ie();let u=await uo(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${fw(e.singular)} '${d}' already exists in config.
412
412
  `),process.exit(1);return}let h=$c(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await yf(u),process.stdout.write(`Added ${e.singular} '${d}' to ${O.config()}
413
413
  `);let w={name:d,...y};try{let b=await Oe(t,{method:"POST",body:w,rethrowNetworkError:!0});if(b.ok){let S=b.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
414
414
  `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${b.status}${Wc(b.body)}). Restart the daemon to apply.
415
415
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
416
- `),process.exit(2);return}await Ie();let l=await uo(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${uw(e.singular)} '${d}' not found in config.
416
+ `),process.exit(2);return}await Ie();let l=await uo(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${fw(e.singular)} '${d}' not found in config.
417
417
  `),process.exit(1);return}delete f[d],u[e.plural]=f,await yf(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${O.config()}
418
418
  `);try{let p=await Oe(`${t}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
419
419
  `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Wc(p.body)}).
@@ -426,48 +426,48 @@ history entries: ${t.history.length}`+(t.promptHistory?`, prompt history: ${t.pr
426
426
  `),h+=1;continue}let w=y.body,b=w.pid!=null?` pid=${w.pid}`:"";process.stdout.write(`${m.name}: ${w.status}${b}
427
427
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
428
428
  `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Mc(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
429
- `),process.exit(2);return}let f=e.logFile(l);await oo(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 uw(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Xr=zc("extension"),fw=Xr.list,pw=Xr.add,hw=Xr.remove,mw=Xr.start,gw=Xr.stop,yw=Xr.restart,ww=Xr.logs;var Zr=zc("transformer"),bw=Zr.list,vw=Zr.add,Sw=Zr.remove,kw=Zr.start,Iw=Zr.stop,xw=Zr.restart,Aw=Zr.logs;Gc();Pa();no();jr();Ge();Dr();Yr();_t();cn();Td();Yf();import WR from"os";import{spawn as zR}from"child_process";async function KR({conn:n,agentId:e,authMethods:t,method:s,spawn:r}){let i;try{let c=await n.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 JR(c,s),u=await Jf(l,{authenticate:f=>n.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
429
+ `),process.exit(2);return}let f=e.logFile(l);await oo(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 fw(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Xr=zc("extension"),pw=Xr.list,hw=Xr.add,mw=Xr.remove,gw=Xr.start,yw=Xr.stop,ww=Xr.restart,bw=Xr.logs;var Zr=zc("transformer"),vw=Zr.list,Sw=Zr.add,kw=Zr.remove,Iw=Zr.start,xw=Zr.stop,Aw=Zr.restart,Cw=Zr.logs;Gc();Pa();no();jr();Ge();Dr();Yr();_t();cn();Td();Yf();import JR from"os";import{spawn as YR}from"child_process";async function VR({conn:n,agentId:e,authMethods:t,method:s,spawn:r}){let i;try{let c=await n.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 QR(c,s),u=await Jf(l,{authenticate:f=>n.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
430
430
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
431
431
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
432
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await n.request("session/new",{cwd:WR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
433
- `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===q.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??t,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function JR(n,e){if(e!==void 0){let s=n.find(i=>i.id===e);if(s)return s;let r=n.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
432
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await n.request("session/new",{cwd:JR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
433
+ `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===q.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??t,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function QR(n,e){if(e!==void 0){let s=n.find(i=>i.id===e);if(s)return s;let r=n.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
434
434
  `),process.exit(2)}if(n.length===1)return n[0];if(process.stdin.isTTY===!0){let s=n.map((c,d)=>`${d+1}) ${c.id} \u2014 ${c.name??c.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
435
435
  ${s.join(`
436
436
  `)}
437
437
  `);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>n.length)&&(process.stderr.write(`invalid selection "${o}" \u2014 enter a number between 1 and ${n.length}
438
438
  `),process.exit(2)),n[a-1]}let t=n.map(s=>s.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${t})
439
- `),process.exit(2)}async function Yw(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
440
- `),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(Gc(),Pw)),s=await t(n,"hydra agent auth"),r=await Ie(),i=await Bt(r);await cr(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Vr(i.wsUrl,o),c=cs(a),d=new zt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:ve}})}catch{}let l;try{l=await KR({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:zR})}finally{a.close()}process.exit(l.exitCode)}Ea();Kl();lr();async function Vw(n){let e=ki(n,"force");if(await bc()&&!e){let r=await Ti("Current password: ");await vc(r)||(process.stderr.write(`Wrong password.
439
+ `),process.exit(2)}async function Vw(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
440
+ `),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(Gc(),Mw)),s=await t(n,"hydra agent auth"),r=await Ie(),i=await Bt(r);await cr(r,i);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Vr(i.wsUrl,o),c=ls(a),d=new zt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:ve}})}catch{}let l;try{l=await VR({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:YR})}finally{a.close()}process.exit(l.exitCode)}Ea();Kl();lr();async function Qw(n){let e=ki(n,"force");if(await bc()&&!e){let r=await Ti("Current password: ");await vc(r)||(process.stderr.write(`Wrong password.
441
441
  `),process.exit(1))}let t=await Ti("New password: ");t.length===0&&(process.stderr.write(`Password must not be empty.
442
442
  `),process.exit(2));let s=await Ti("Confirm new password: ");t!==s&&(process.stderr.write(`Passwords did not match.
443
443
  `),process.exit(1)),await ny(t),process.stdout.write(`Password set.
444
- `)}async function Qw(){let e=(await Oe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
444
+ `)}async function Gw(){let e=(await Oe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
445
445
  `);return}let t={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:nl(t.id,s.map(o=>o.id)),label:nl(t.label,s.map(o=>o.label)),createdAt:nl(t.createdAt,s.map(o=>o.createdAt)),expiresAt:nl(t.expiresAt,s.map(o=>o.expiresAt))},i=o=>[o.id.padEnd(r.id),o.label.padEnd(r.label),o.createdAt.padEnd(r.createdAt),o.expiresAt.padEnd(r.expiresAt),o.lastUsedAt].join(" ");process.stdout.write(i(t)+`
446
446
  `);for(let o of s)process.stdout.write(i(o)+`
447
- `)}async function Gw(n){n||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
447
+ `)}async function Xw(n){n||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
448
448
  `),process.exit(2));let e=await Oe(`/v1/auth/sessions/${n}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${n}
449
449
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${n}
450
450
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
451
- `),process.exit(1)}function nl(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as mr from"fs";Ge();Dr();Yr();Vf();_t();var sl=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Gf(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(Qf(e)){if(e.method==="session/new"){let t=e.params??{},s=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"",r=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!Qf(e)&&!Gf(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(Qf(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(!Gf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let t=this.pending.get(e.id);if(!t)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=an(i),a=o.upstreamSessionId,c=o.agentId,d="";(t.kind==="new"||t.kind==="load")&&(d=t.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 t=this.pendingPermissions.get(e);return t&&this.deletePendingPermission(t),t}takePendingPermissionByToolCall(e){let t=this.pendingPermissionsByToolCall.get(e);if(!t||t.length===0)return;let s=t[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let t=this.pendingPermissionsByToolCall.get(e.toolCallId);if(t){let s=t.indexOf(e.requestId);s>=0&&t.splice(s,1),t.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Qf(n){return"method"in n&&"id"in n&&n.id!==void 0}function Gf(n){return!("method"in n)&&"id"in n}il();cn();be();na();import{writeFileSync as ZR}from"fs";var e0=n=>{ZR("/proc/self/comm",n)};function Ao(n,e={}){if(process.title=n,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??e0;try{s(e.commName??ns())}catch{}}function Co(n,e=ns()){return n.length===0?e:`${e} ${n.join(" ")}`}async function al(n){Ao(Co(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ie(),t=n.target??await Bt(e);t.isLocal&&!n.target&&await cr(e);let s=new sl,r=$d(process.stdin,process.stdout),i=t.isLocal?async()=>(await Bt(await Ie())).wsUrl:t.wsUrl,o=["acp.v1",`hydra-acp-token.${t.token}`],a=new xo({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await o0(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
452
- `);for(let l of d)await a0(a,l,s.lastMessageId(l.sessionId))}}});t0({opts:n,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
453
- `),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 t0({opts:n,upstream:e,downstream:t,tracker:s}){e.onMessage(i=>{if(rb("daemon\u2192client",i),s.observeFromServer(i),n.dangerouslySkipPermissions===!0&&u0(i)){e.send({jsonrpc:"2.0",id:i.id,result:ii(i.params)});return}n0(i,s,t),t.send(i)});let r={name:n.name,used:!1};t.onMessage(i=>{if(rb("client\u2192daemon",i),s.observeFromClient(i),c0(i)){e.send(l0(i));return}if(d0(i)){if(n.sessionId){e.send(f0(i,n.sessionId));return}let o=i;n.agentId&&(o=ol(o,{agentId:n.agentId})),n.agentArgs&&n.agentArgs.length>0&&(o=ol(o,{agentArgs:n.agentArgs})),r.name&&!r.used&&(o=ol(o,{title:r.name}),r.used=!0),n.model&&(o=ol(o,{model:n.model})),e.send(o);return}e.send(i)})}function n0(n,e,t){let s=s0(n);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=i0(s);t.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function s0(n){if(!r0(n))return;let t=(n.params??{}).update;if(!(!t||typeof t!="object"||t.sessionUpdate!=="permission_resolved"))return t}function r0(n){return"method"in n&&n.method==="session/update"&&!("id"in n&&n.id!==void 0)}function i0(n){if(n.outcome&&typeof n.outcome=="object")return n.outcome;if(typeof n.chosenOptionId=="string")return{kind:"selected",optionId:n.chosenOptionId}}async function o0(n,e){let t=n.takePendingPermissions();if(t.length!==0){process.stderr.write(`hydra-acp: cancelling ${t.length} pending permission request(s)
454
- `);for(let s of t){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 a0(n,e,t){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}}};t?(r.historyPolicy="after_message",r.afterMessageId=t):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await n.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
451
+ `),process.exit(1)}function nl(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as mr from"fs";Ge();Dr();Yr();Vf();_t();var sl=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Gf(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(Qf(e)){if(e.method==="session/new"){let t=e.params??{},s=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"",r=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!Qf(e)&&!Gf(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(Qf(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(!Gf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let t=this.pending.get(e.id);if(!t)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=an(i),a=o.upstreamSessionId,c=o.agentId,d="";(t.kind==="new"||t.kind==="load")&&(d=t.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 t=this.pendingPermissions.get(e);return t&&this.deletePendingPermission(t),t}takePendingPermissionByToolCall(e){let t=this.pendingPermissionsByToolCall.get(e);if(!t||t.length===0)return;let s=t[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let t=this.pendingPermissionsByToolCall.get(e.toolCallId);if(t){let s=t.indexOf(e.requestId);s>=0&&t.splice(s,1),t.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Qf(n){return"method"in n&&"id"in n&&n.id!==void 0}function Gf(n){return!("method"in n)&&"id"in n}il();cn();be();na();import{writeFileSync as n0}from"fs";var s0=n=>{n0("/proc/self/comm",n)};function Ao(n,e={}){if(process.title=n,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??s0;try{s(e.commName??ns())}catch{}}function Co(n,e=ns()){return n.length===0?e:`${e} ${n.join(" ")}`}async function al(n){Ao(Co(process.argv.slice(2)),{commName:"hydra-shim"});let e=await Ie(),t=n.target??await Bt(e);t.isLocal&&!n.target&&await cr(e,t);let s=new sl,r=$d(process.stdin,process.stdout),i=t.isLocal?async()=>(await Bt(await Ie())).wsUrl:t.wsUrl,o=["acp.v1",`hydra-acp-token.${t.token}`],a=new xo({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await c0(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
452
+ `);for(let l of d)await l0(a,l,s.lastMessageId(l.sessionId))}}});r0({opts:n,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
453
+ `),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 r0({opts:n,upstream:e,downstream:t,tracker:s}){e.onMessage(i=>{if(ib("daemon\u2192client",i),s.observeFromServer(i),n.dangerouslySkipPermissions===!0&&h0(i)){e.send({jsonrpc:"2.0",id:i.id,result:ii(i.params)});return}i0(i,s,t),t.send(i)});let r={name:n.name,used:!1};t.onMessage(i=>{if(ib("client\u2192daemon",i),s.observeFromClient(i),f0(i)){e.send(p0(i));return}if(u0(i)){if(n.sessionId){e.send(m0(i,n.sessionId));return}let o=i;n.agentId&&(o=ol(o,{agentId:n.agentId})),n.agentArgs&&n.agentArgs.length>0&&(o=ol(o,{agentArgs:n.agentArgs})),r.name&&!r.used&&(o=ol(o,{title:r.name}),r.used=!0),n.model&&(o=ol(o,{model:n.model})),e.send(o);return}e.send(i)})}function i0(n,e,t){let s=o0(n);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=d0(s);t.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function o0(n){if(!a0(n))return;let t=(n.params??{}).update;if(!(!t||typeof t!="object"||t.sessionUpdate!=="permission_resolved"))return t}function a0(n){return"method"in n&&n.method==="session/update"&&!("id"in n&&n.id!==void 0)}function d0(n){if(n.outcome&&typeof n.outcome=="object")return n.outcome;if(typeof n.chosenOptionId=="string")return{kind:"selected",optionId:n.chosenOptionId}}async function c0(n,e){let t=n.takePendingPermissions();if(t.length!==0){process.stderr.write(`hydra-acp: cancelling ${t.length} pending permission request(s)
454
+ `);for(let s of t){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 l0(n,e,t){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}}};t?(r.historyPolicy="after_message",r.afterMessageId=t):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await n.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
455
455
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
456
- `)}}function d0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function c0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function l0(n){let e=n.params??{},t=e.clientInfo,s=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?n:{...n,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:ve}}}}function u0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function f0(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var p0=25*1024*1024,sb=!1,oi=null;function rb(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!sb){sb=!0;try{oi=O.shimWireLogFile(),mr.mkdirSync(O.home(),{recursive:!0});let t=mr.statSync(oi,{throwIfNoEntry:!1});t&&t.size>p0&&mr.renameSync(oi,`${oi}.1`)}catch{oi=null}}if(oi)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
457
- `;mr.appendFile(oi,t,()=>{})}catch{}}}function ol(n,e){let t=n.params??{},s=t._meta??{},r=s["hydra-acp"]??{};return{...n,params:{...t,_meta:{...s,"hydra-acp":{...r,...e}}}}}jr();no();Pa();Ge();Dr();Yr();or();_t();cn();il();import{mkdtempSync as x0,rmSync as A0}from"fs";import{tmpdir as C0}from"os";import{join as R0}from"path";function ib(n){let e="",t=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",n.onChunk(a)},o=()=>{s||(s=!0,t=!1,n.scheduleFlushCheck(()=>{if(s=!1,t){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?t=!0:o())},eof(){r||(r=!0,i())}}}yo();import h0 from"chalk";import m0 from"strip-ansi";var dl=new h0.Instance({level:3});function ob(n,e){if(n.length===0)return"";let t=hr(n);if(t.length===0)return"";let s=[];for(let i of t)s.push(g0(i,e));let r=s.join(`
456
+ `)}}function u0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function f0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function p0(n){let e=n.params??{},t=e.clientInfo,s=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?n:{...n,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:ve}}}}function h0(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function m0(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var g0=25*1024*1024,rb=!1,oi=null;function ib(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!rb){rb=!0;try{oi=O.shimWireLogFile(),mr.mkdirSync(O.home(),{recursive:!0});let t=mr.statSync(oi,{throwIfNoEntry:!1});t&&t.size>g0&&mr.renameSync(oi,`${oi}.1`)}catch{oi=null}}if(oi)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
457
+ `;mr.appendFile(oi,t,()=>{})}catch{}}}function ol(n,e){let t=n.params??{},s=t._meta??{},r=s["hydra-acp"]??{};return{...n,params:{...t,_meta:{...s,"hydra-acp":{...r,...e}}}}}jr();no();Pa();Ge();Dr();Yr();or();_t();cn();il();import{mkdtempSync as R0,rmSync as T0}from"fs";import{tmpdir as E0}from"os";import{join as P0}from"path";function ob(n){let e="",t=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",n.onChunk(a)},o=()=>{s||(s=!0,t=!1,n.scheduleFlushCheck(()=>{if(s=!1,t){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?t=!0:o())},eof(){r||(r=!0,i())}}}yo();import y0 from"chalk";import w0 from"strip-ansi";var dl=new y0.Instance({level:3});function ab(n,e){if(n.length===0)return"";let t=hr(n);if(t.length===0)return"";let s=[];for(let i of t)s.push(b0(i,e));let r=s.join(`
458
458
  `);return r.endsWith(`
459
459
  `)||(r+=`
460
- `),r}function g0(n,e){let t=k0(n.body,e);return e==="ansi"?t=I0(t,n.bodyStyle):t=m0(t),t}var y0="\x1B[1m",w0="\x1B[96m",b0="\x1B[93m",v0="\x1B[0m",S0="\0";function k0(n,e){let t=n.replace(/\^\^/g,S0);return e==="ansi"&&(t=t.replace(/\^\+/g,y0).replace(/\^C/g,w0).replace(/\^Y/g,b0).replace(/\^:/g,v0)),t=t.replace(/\^[+\-:CcKY]/g,""),t=t.replace(/\x00/g,"^"),t}function I0(n,e){if(n.length===0||e===void 0)return n;switch(e){case"heading-1":return dl.bold.yellowBright(n);case"heading-2":return dl.bold.cyanBright(n);case"heading-3":return dl.bold(n);case"dim":return dl.dim(n);default:return n}}var T0=1*1024*1024,ab="mcp__hydra-acp-stdin__";function db(n,e){return{sessionId:n,prompt:e,_meta:{[Mt]:{ancillary:!0}}}}function E0(n){if(n)for(let e of n.split(/\r?\n/)){let t=e.trim();if(t)return t.length>80?`${t.slice(0,80)}\u2026`:t}}function P0(n){if(!n||typeof n!="object")return!1;let e=n.toolCall;if(!e||typeof e!="object")return!1;let t=e.title;if(typeof t=="string"&&t.startsWith(ab))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(ab))}async function cb(n){if(Ao(Co(process.argv.slice(2))),process.stdin.isTTY&&!n.prompt&&!n.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.
461
- `),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let c=x0(R0(C0(),"hydra-cat-"));n.cwd=c,n.detach||process.once("exit",()=>{try{A0(c,{recursive:!0,force:!0})}catch{}})}let e=await Ie(),t=n.target??await Bt(e);t.isLocal&&!n.target&&await cr(e);let s=["acp.v1",`hydra-acp-token.${t.token}`],r=await Vr(t.wsUrl,s),i=cs(r),o=new zt(i),a=await _0({conn:o,opts:n,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:M0(t.baseUrl,t.token)});process.exit(a.exitCode)}function M0(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${n}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:t,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:t,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function _0(n){let{conn:e,opts:t,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=n,c=i?"ansi":"plain",d=t.raw===!0,l=!r&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async V=>t.dangerouslySkipPermissions?ii(V):P0(V)?ii(V):eb(V));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:qr,version:ve}})}catch{}let u=await O0(e,t,l),f=!1,p=!0,h="",m=0,y=V=>{V.length!==0&&(o(V),p=V.charCodeAt(V.length-1)===10,f=!0)},w=()=>{if(d||h.length===0)return;let V=ob(h,c);if(h="",V.length===0)return;let ye=m>0?`
460
+ `),r}function b0(n,e){let t=A0(n.body,e);return e==="ansi"?t=C0(t,n.bodyStyle):t=w0(t),t}var v0="\x1B[1m",S0="\x1B[96m",k0="\x1B[93m",I0="\x1B[0m",x0="\0";function A0(n,e){let t=n.replace(/\^\^/g,x0);return e==="ansi"&&(t=t.replace(/\^\+/g,v0).replace(/\^C/g,S0).replace(/\^Y/g,k0).replace(/\^:/g,I0)),t=t.replace(/\^[+\-:CcKY]/g,""),t=t.replace(/\x00/g,"^"),t}function C0(n,e){if(n.length===0||e===void 0)return n;switch(e){case"heading-1":return dl.bold.yellowBright(n);case"heading-2":return dl.bold.cyanBright(n);case"heading-3":return dl.bold(n);case"dim":return dl.dim(n);default:return n}}var M0=1*1024*1024,db="mcp__hydra-acp-stdin__";function cb(n,e){return{sessionId:n,prompt:e,_meta:{[Mt]:{ancillary:!0}}}}function _0(n){if(n)for(let e of n.split(/\r?\n/)){let t=e.trim();if(t)return t.length>80?`${t.slice(0,80)}\u2026`:t}}function $0(n){if(!n||typeof n!="object")return!1;let e=n.toolCall;if(!e||typeof e!="object")return!1;let t=e.title;if(typeof t=="string"&&t.startsWith(db))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(db))}async function lb(n){if(Ao(Co(process.argv.slice(2))),process.stdin.isTTY&&!n.prompt&&!n.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.
461
+ `),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let c=R0(P0(E0(),"hydra-cat-"));n.cwd=c,n.detach||process.once("exit",()=>{try{T0(c,{recursive:!0,force:!0})}catch{}})}let e=await Ie(),t=n.target??await Bt(e);t.isLocal&&!n.target&&await cr(e,t);let s=["acp.v1",`hydra-acp-token.${t.token}`],r=await Vr(t.wsUrl,s),i=ls(r),o=new zt(i),a=await O0({conn:o,opts:n,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:F0(t.baseUrl,t.token)});process.exit(a.exitCode)}function F0(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${n}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:t,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:t,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function O0(n){let{conn:e,opts:t,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=n,c=i?"ansi":"plain",d=t.raw===!0,l=!r&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async V=>t.dangerouslySkipPermissions?ii(V):$0(V)?ii(V):tb(V));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:qr,version:ve}})}catch{}let u=await N0(e,t,l),f=!1,p=!0,h="",m=0,y=V=>{V.length!==0&&(o(V),p=V.charCodeAt(V.length-1)===10,f=!0)},w=()=>{if(d||h.length===0)return;let V=ab(h,c);if(h="",V.length===0)return;let ye=m>0?`
462
462
  `:"";y(ye+V),m+=1},b=()=>{w(),f&&!p&&y(`
463
- `),f=!1};e.onNotification("session/update",V=>{let ye=V?.update,Be=ds(ye,{cwd:t.cwd});if(Be){if(Be.kind==="agent-text"){d?y(Be.text):h+=Be.text;return}if(Be.kind==="turn-complete"){b();return}switch(Be.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":w();return;default:return}}});let S=!1,k=async V=>{let ye=[];if(t.prompt&&!S&&ye.push({type:"text",text:t.prompt}),V.length>0&&ye.push({type:"text",text:V}),ye.length!==0){try{await e.request("session/prompt",db(u,ye)),S=!0}catch(Be){a(`hydra-acp cat: prompt failed: ${Be.message}
463
+ `),f=!1};e.onNotification("session/update",V=>{let ye=V?.update,Be=cs(ye,{cwd:t.cwd});if(Be){if(Be.kind==="agent-text"){d?y(Be.text):h+=Be.text;return}if(Be.kind==="turn-complete"){b();return}switch(Be.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":w();return;default:return}}});let S=!1,k=async V=>{let ye=[];if(t.prompt&&!S&&ye.push({type:"text",text:t.prompt}),V.length>0&&ye.push({type:"text",text:V}),ye.length!==0){try{await e.request("session/prompt",cb(u,ye)),S=!0}catch(Be){a(`hydra-acp cat: prompt failed: ${Be.message}
464
464
  `);return}b()}},A=0,E,P=new Promise(V=>{E=V}),H=!1,_=async V=>{H||(H=!0,b(),t.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Be=>setTimeout(Be,500))]),await e.close().catch(()=>{}),E({exitCode:V}))};e.onClose(V=>{V&&(a(`hydra-acp cat: ${V.message}
465
- `),A=1),H||(H=!0,b(),E({exitCode:A}))});let F=[],B=!1,N=!1,j=async()=>{if(!B){B=!0;try{for(;F.length>0;){let V=F.shift();if(V===void 0)break;await k(V)}}finally{B=!1,N&&F.length===0&&await _(A)}}};if(r&&!t.sessionId)return t.prompt&&await k(""),await _(0),P;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),$0({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!B&&F.length===0&&_(A)},onError:V=>{a(`hydra-acp cat: stdin error: ${V.message}
465
+ `),A=1),H||(H=!0,b(),E({exitCode:A}))});let F=[],B=!1,N=!1,j=async()=>{if(!B){B=!0;try{for(;F.length>0;){let V=F.shift();if(V===void 0)break;await k(V)}}finally{B=!1,N&&F.length===0&&await _(A)}}};if(r&&!t.sessionId)return t.prompt&&await k(""),await _(0),P;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),L0({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!B&&F.length===0&&_(A)},onError:V=>{a(`hydra-acp cat: stdin error: ${V.message}
466
466
  `),A=1,N=!0,!B&&F.length===0&&_(A)},onPromptFailed:V=>{a(`hydra-acp cat: ${V.message}
467
- `),A=1,N=!0,!B&&F.length===0&&_(A)}}),P;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),t.follow===!0||r&&!!t.sessionId){let V=ib({scheduleFlushCheck:ye=>{let Be=setImmediate(ye);return()=>clearImmediate(Be)},onChunk:ye=>{F.push(ye),j()}});return s.on("data",ye=>{V.feed(typeof ye=="string"?ye:ye.toString("utf8"))}),s.on("end",()=>{V.eof(),N=!0,!B&&F.length===0&&_(A)}),s.on("error",ye=>{a(`hydra-acp cat: stdin error: ${ye.message}
467
+ `),A=1,N=!0,!B&&F.length===0&&_(A)}}),P;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),t.follow===!0||r&&!!t.sessionId){let V=ob({scheduleFlushCheck:ye=>{let Be=setImmediate(ye);return()=>clearImmediate(Be)},onChunk:ye=>{F.push(ye),j()}});return s.on("data",ye=>{V.feed(typeof ye=="string"?ye:ye.toString("utf8"))}),s.on("end",()=>{V.eof(),N=!0,!B&&F.length===0&&_(A)}),s.on("error",ye=>{a(`hydra-acp cat: stdin error: ${ye.message}
468
468
  `),A=1,N=!0,!B&&F.length===0&&_(A)}),P}let X="";return s.on("data",V=>{X+=typeof V=="string"?V:V.toString("utf8")}),s.on("end",()=>{N=!0,X.length>0&&F.push(X),j()}),s.on("error",V=>{a(`hydra-acp cat: stdin error: ${V.message}
469
- `),A=1,N=!0,!B&&F.length===0&&_(A)}),P}function $0(n){let{conn:e,streamClient:t,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=n,c=r.streamThreshold??T0,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let k=b.toString("base64");h=h.then(()=>t.write(s,k,S)).catch(A=>{o(`hydra-acp cat: stdin write failed: ${A.message}
470
- `)})},y=async()=>{d="inline";let b=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(b)}catch(S){n.onPromptFailed(S);return}n.onEof()},w=async()=>{d="pivoting";let b;try{let A={mode:"memory"};r.streamBufferBytes!==void 0&&(A.capacityBytes=r.streamBufferBytes),b=await t.open(s,A)}catch(A){n.onPromptFailed(new Error(`stdin/open failed: ${A.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=F0(r.prompt,b.capacityBytes);e.request("session/prompt",db(s,[{type:"text",text:S}])).catch(A=>{n.onPromptFailed(new Error(`prompt failed: ${A.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),n.onEof()})};i.on("data",b=>{let S=typeof b=="string"?Buffer.from(b,"utf8"):b;if(d==="undecided"){u.push(S),f+=S.length,f>c&&w();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",n.onError)}function F0(n,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
469
+ `),A=1,N=!0,!B&&F.length===0&&_(A)}),P}function L0(n){let{conn:e,streamClient:t,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=n,c=r.streamThreshold??M0,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let k=b.toString("base64");h=h.then(()=>t.write(s,k,S)).catch(A=>{o(`hydra-acp cat: stdin write failed: ${A.message}
470
+ `)})},y=async()=>{d="inline";let b=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(b)}catch(S){n.onPromptFailed(S);return}n.onEof()},w=async()=>{d="pivoting";let b;try{let A={mode:"memory"};r.streamBufferBytes!==void 0&&(A.capacityBytes=r.streamBufferBytes),b=await t.open(s,A)}catch(A){n.onPromptFailed(new Error(`stdin/open failed: ${A.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=B0(r.prompt,b.capacityBytes);e.request("session/prompt",cb(s,[{type:"text",text:S}])).catch(A=>{n.onPromptFailed(new Error(`prompt failed: ${A.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),n.onEof()})};i.on("data",b=>{let S=typeof b=="string"?Buffer.from(b,"utf8"):b;if(d==="undecided"){u.push(S),f+=S.length,f>c&&w();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",n.onError)}function B0(n,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:
471
471
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
472
472
  - \`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.
473
473
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -482,50 +482,50 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
482
482
  User's question:
483
483
  ${n}`:`${s}
484
484
 
485
- 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 O0(n,e,t){if(e.sessionId)return(await n.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:qr,version:ve}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=E0(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),t&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[Mt]:s});let o=await n.request("session/new",i);return an(o._meta),o.sessionId}Ge();be();function cl(n){let e=n.split(".").filter(t=>t.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function lb(n,e){let t=n;for(let s of e){if(t===null||typeof t!="object"||Array.isArray(t))return;t=t[s]}return t}function L0(n){try{return JSON.parse(n)}catch{return n}}function ub(n){return n===void 0?"":typeof n=="string"?n:JSON.stringify(n,null,2)}async function fb(n){n||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
486
- `),process.exit(2));let e=cl(n),t=await Ie(),s=lb(t,e);s===void 0&&(process.stderr.write(`config: key '${n}' is unset
487
- `),process.exit(1)),process.stdout.write(`${ub(s)}
488
- `)}async function pb(n,e){(!n||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
489
- `),process.exit(2));let t=cl(n),s=L0(e);try{await Ps(r=>{let i=r;for(let o=0;o<t.length-1;o++){let a=t[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 '${t.slice(0,o+1).join(".")}' (not an object)`);i=c}i[t[t.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
490
- `),process.exit(1)}process.stdout.write(`set ${n} = ${ub(s)}
491
- `)}async function hb(n){n||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
492
- `),process.exit(2));let e=cl(n);try{await Ps(t=>{let s=t;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(t){process.stderr.write(`${t.message}
485
+ 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 N0(n,e,t){if(e.sessionId)return(await n.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:qr,version:ve}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=_0(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),t&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[Mt]:s});let o=await n.request("session/new",i);return an(o._meta),o.sessionId}Ge();be();function cl(n){let e=n.split(".").filter(t=>t.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function ub(n,e){let t=n;for(let s of e){if(t===null||typeof t!="object"||Array.isArray(t))return;t=t[s]}return t}function D0(n){try{return JSON.parse(n)}catch{return n}}function fb(n){return n===void 0?"":typeof n=="string"?n:JSON.stringify(n,null,2)}async function pb(n){n||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
486
+ `),process.exit(2));let e=cl(n),t=await Ie(),s=ub(t,e);s===void 0&&(process.stderr.write(`config: key '${n}' is unset
487
+ `),process.exit(1)),process.stdout.write(`${fb(s)}
488
+ `)}async function hb(n,e){(!n||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
489
+ `),process.exit(2));let t=cl(n),s=D0(e);try{await Ms(r=>{let i=r;for(let o=0;o<t.length-1;o++){let a=t[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 '${t.slice(0,o+1).join(".")}' (not an object)`);i=c}i[t[t.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
490
+ `),process.exit(1)}process.stdout.write(`set ${n} = ${fb(s)}
491
+ `)}async function mb(n){n||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
492
+ `),process.exit(2));let e=cl(n);try{await Ms(t=>{let s=t;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(t){process.stderr.write(`${t.message}
493
493
  `),process.exit(1)}process.stdout.write(`unset ${n}
494
- `)}async function mb(n){let e=await Ie(),t=n?lb(e,cl(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
494
+ `)}async function gb(n){let e=await Ie(),t=n?ub(e,cl(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
495
495
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(t,null,2)}
496
- `)}function gb(){process.stdout.write(`${O.config()}
497
- `)}Ge();Es();Yr();cn();lr();async function bb(n={}){let{report:e,configLoaded:t}=await B0();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
496
+ `)}function yb(){process.stdout.write(`${O.config()}
497
+ `)}Ge();Ps();Yr();cn();lr();async function vb(n={}){let{report:e,configLoaded:t}=await H0();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
498
498
  `);return}process.stdout.write(`CLI: ${e.cli}
499
499
  `),t&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
500
- `),e.daemonReachable&&(yb("Extensions",e.extensions),yb("Transformers",e.transformers)))}function yb(n,e){if(process.stdout.write(`
500
+ `),e.daemonReachable&&(wb("Extensions",e.extensions),wb("Transformers",e.transformers)))}function wb(n,e){if(process.stdout.write(`
501
501
  ${n}:
502
502
  `),e.length===0){process.stdout.write(` (none)
503
503
  `);return}let t=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(t)} ${i.padEnd(s)} ${r.status}
504
- `)}}async function B0(){let n={cli:ve,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ie()}catch{return{report:n,configLoaded:!1}}let t=await Jr(e);if(t!==void 0&&(n.daemonReachable=!0,n.daemon=t.version??null),!n.daemonReachable)return{report:n,configLoaded:!0};let s;try{s=await Fr()}catch{return{report:n,configLoaded:!0}}let r=await co(),i={Authorization:`Bearer ${s}`};return n.extensions=await wb(`${r}/v1/extensions`,i,"extensions"),n.transformers=await wb(`${r}/v1/transformers`,i,"transformers"),{report:n,configLoaded:!0}}async function wb(n,e,t){try{let s=await fetch(n,{headers:e});if(!s.ok)return[];let i=(await s.json())[t];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as N0}from"child_process";import{accessSync as D0,constants as H0,statSync as U0}from"fs";import{delimiter as j0,join as q0}from"path";var W0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function z0(n){return W0.has(n)}function K0(n){for(let e of n)if(e!==void 0&&!e.startsWith("-"))return e}function J0(n){let e=[],t=!1;for(let s of n){if(!t&&s!==void 0&&!s.startsWith("-")){t=!0;continue}s!==void 0&&e.push(s)}return e}function Y0(n){try{if(!U0(n).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return D0(n,H0.X_OK),!0}catch{return!1}}function V0(n,e=process.env){let t=e.PATH??e.Path??"";if(t.length===0)return;let s=t.split(j0).filter(o=>o.length>0),r=`hydra-acp-${n}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=q0(o,r+a);if(Y0(c))return c}}function Q0(n,e){let t=N0(n,e,{stdio:"inherit",env:process.env});t.error&&(process.stderr.write(`hydra-acp: failed to exec ${n}: ${t.error.message}
505
- `),process.exit(1)),typeof t.status=="number"&&process.exit(t.status),t.signal&&process.kill(process.pid,t.signal),process.exit(1)}function vb(n){let e=K0(n);if(e===void 0||z0(e))return!1;let t=V0(e);if(t===void 0)return!1;Q0(t,J0(n))}Xf();var br=!1,zv=!1;function Kv(n){!n||zv||(zv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
506
- `))}async function oP(){let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(ia(),hh));n();let e=process.argv.slice(2),t=e.indexOf("launch");if(t!==-1){let w=e.slice(0,t),b=e.slice(t+1),S=b[0],k=b.slice(1),{flags:A}=Bl(w);if(Yv(A),A.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
504
+ `)}}async function H0(){let n={cli:ve,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await Ie()}catch{return{report:n,configLoaded:!1}}let t=await Jr(e);if(t!==void 0&&(n.daemonReachable=!0,n.daemon=t.version??null),!n.daemonReachable)return{report:n,configLoaded:!0};let s;try{s=await Fr()}catch{return{report:n,configLoaded:!0}}let r=await co(),i={Authorization:`Bearer ${s}`};return n.extensions=await bb(`${r}/v1/extensions`,i,"extensions"),n.transformers=await bb(`${r}/v1/transformers`,i,"transformers"),{report:n,configLoaded:!0}}async function bb(n,e,t){try{let s=await fetch(n,{headers:e});if(!s.ok)return[];let i=(await s.json())[t];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as U0}from"child_process";import{accessSync as j0,constants as q0,statSync as W0}from"fs";import{delimiter as z0,join as K0}from"path";var J0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function Y0(n){return J0.has(n)}function V0(n){for(let e of n)if(e!==void 0&&!e.startsWith("-"))return e}function Q0(n){let e=[],t=!1;for(let s of n){if(!t&&s!==void 0&&!s.startsWith("-")){t=!0;continue}s!==void 0&&e.push(s)}return e}function G0(n){try{if(!W0(n).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return j0(n,q0.X_OK),!0}catch{return!1}}function X0(n,e=process.env){let t=e.PATH??e.Path??"";if(t.length===0)return;let s=t.split(z0).filter(o=>o.length>0),r=`hydra-acp-${n}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=K0(o,r+a);if(G0(c))return c}}function Z0(n,e){let t=U0(n,e,{stdio:"inherit",env:process.env});t.error&&(process.stderr.write(`hydra-acp: failed to exec ${n}: ${t.error.message}
505
+ `),process.exit(1)),typeof t.status=="number"&&process.exit(t.status),t.signal&&process.kill(process.pid,t.signal),process.exit(1)}function Sb(n){let e=V0(n);if(e===void 0||Y0(e))return!1;let t=X0(e);if(t===void 0)return!1;Z0(t,Q0(n))}Xf();var br=!1,Kv=!1;function Jv(n){!n||Kv||(Kv=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
506
+ `))}async function cP(){let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(ia(),hh));n();let e=process.argv.slice(2),t=e.indexOf("launch");if(t!==-1){let w=e.slice(0,t),b=e.slice(t+1),S=b[0],k=b.slice(1),{flags:A}=Bl(w);if(Vv(A),A.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
507
507
  `),process.exit(2);return}let E=S??kt(A,"agent");if(!E){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
508
- `),process.exit(2);return}let P=await Vv(eu(A),{allowPrompt:!1}),H=kt(A,"name"),_=kt(A,"model");br=!0;let F=A["dangerously-skip-permissions"]===!0;Kv(F);let B={agentId:E,agentArgs:k,name:H,model:_,dangerouslySkipPermissions:F};P?.sessionId!==void 0&&(B.sessionId=P.sessionId),P?.target!==void 0&&P.fromUrl&&(B.target=P.target),await al(B);return}Dp(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&vb(e);let{positional:s,flags:r}=Bl(e);if(Yv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${aP()}
509
- `);return}if(r.help===!0){qp(s[0]);return}let i=Dp(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;Kv(u);let f=eu(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Vv(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.
510
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){br=!0,await Jv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}br=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await al(w);return}switch(a){case"acp":case"shim":{br=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await al(w);return}case"cat":{let w=Dp(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=w??b,k=kt(r,"cwd"),A={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};k!==void 0&&(A.cwd=k),y!==void 0&&(A.target=y);let E=jp(r,"stream-threshold");E!==void 0&&(A.streamThreshold=E);let P=jp(r,"stream-bytes");P!==void 0&&(A.streamBufferBytes=P),d!==void 0&&await Jc(d),br=!0,await cb(A);return}case"version":{br=!0,await bb({json:r.json===!0});return}case"init":await Ah(r);return;case"daemon":{let w=e.indexOf("daemon"),b=e.slice(w+1),S=b[0];if(S===void 0||S==="status"){await Ty();return}if(S==="start"){await xy(r);return}if(S==="stop"){await Ay();return}if(S==="restart"){await Cy();return}if(S==="log"||S==="logs"){await Ry(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
511
- `),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=kt(r,"columns"),S;if(b!==void 0)try{S=Dy(b)}catch(k){process.stderr.write(`${k.message}
512
- `),process.exit(2);return}await jy({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(w==="info"){await lw(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(w==="diff"){await cw(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(w==="kill"){await qy(s[2]);return}if(w==="remove"){await Wy(s[2]);return}if(w==="collect"){let b=kt(r,"max-age-days"),S=kt(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(b!==void 0){let A=Number(b);if(!Number.isFinite(A)||A<0){process.stderr.write(`--max-age-days must be a non-negative number
508
+ `),process.exit(2);return}let P=await Qv(eu(A),{allowPrompt:!1}),H=kt(A,"name"),_=kt(A,"model");br=!0;let F=A["dangerously-skip-permissions"]===!0;Jv(F);let B={agentId:E,agentArgs:k,name:H,model:_,dangerouslySkipPermissions:F};P?.sessionId!==void 0&&(B.sessionId=P.sessionId),P?.target!==void 0&&P.fromUrl&&(B.target=P.target),await al(B);return}Dp(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&Sb(e);let{positional:s,flags:r}=Bl(e);if(Vv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${lP()}
509
+ `);return}if(r.help===!0){qp(s[0]);return}let i=Dp(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;Jv(u);let f=eu(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Qv(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.
510
+ `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){br=!0,await Yv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}br=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await al(w);return}switch(a){case"acp":case"shim":{br=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await al(w);return}case"cat":{let w=Dp(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=w??b,k=kt(r,"cwd"),A={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};k!==void 0&&(A.cwd=k),y!==void 0&&(A.target=y);let E=jp(r,"stream-threshold");E!==void 0&&(A.streamThreshold=E);let P=jp(r,"stream-bytes");P!==void 0&&(A.streamBufferBytes=P),d!==void 0&&await Jc(d),br=!0,await lb(A);return}case"version":{br=!0,await vb({json:r.json===!0});return}case"init":await Ah(r);return;case"daemon":{let w=e.indexOf("daemon"),b=e.slice(w+1),S=b[0];if(S===void 0||S==="status"){await Ey();return}if(S==="start"){await Ay(r);return}if(S==="stop"){await Cy();return}if(S==="restart"){await Ry();return}if(S==="log"||S==="logs"){await Ty(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
511
+ `),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=kt(r,"columns"),S;if(b!==void 0)try{S=Hy(b)}catch(k){process.stderr.write(`${k.message}
512
+ `),process.exit(2);return}await qy({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(w==="info"){await uw(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(w==="diff"){await lw(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(w==="kill"){await Wy(s[2]);return}if(w==="remove"){await zy(s[2]);return}if(w==="collect"){let b=kt(r,"max-age-days"),S=kt(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(b!==void 0){let A=Number(b);if(!Number.isFinite(A)||A<0){process.stderr.write(`--max-age-days must be a non-negative number
513
513
  `),process.exit(2);return}k.maxAgeDays=A}if(S!==void 0){let A=Number(S);if(!Number.isFinite(A)||A<=0){process.stderr.write(`--limit must be a positive number
514
- `),process.exit(2);return}k.limit=A}await zy(k);return}if(w==="export"){let b=kt(r,"out"),S=kt(r,"tools");await Ky(s[2],b,S);return}if(w==="transcript"){let b=kt(r,"out"),S=r.tools===!0;await Jy(s[2],b,{includeTools:S});return}if(w==="import"){let b=kt(r,"cwd");await Yy(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(w==="share"){let b=kt(r,"host"),S=kt(r,"cwd");await Vy(s[2],{...b!==void 0?{host:b}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
515
- `),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await fw();return}if(S==="add"){await pw(k,A);return}if(S==="remove"){await hw(k);return}if(S==="start"){await mw(k);return}if(S==="stop"){await gw(k);return}if(S==="restart"){await yw(k);return}if(S==="log"||S==="logs"){await ww(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
516
- `),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await bw();return}if(S==="add"){await vw(k,A);return}if(S==="remove"){await Sw(k);return}if(S==="start"){await kw(k);return}if(S==="stop"){await Iw(k);return}if(S==="restart"){await xw(k);return}if(S==="log"||S==="logs"){await Aw(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
517
- `),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await Lf();return}if(w==="refresh"){await Vc();return}if(w==="install"){await Bf(s[2]);return}if(w==="sync"){await Nf(s[2]);return}if(w==="set"){await Hf(s[2],s[3]);return}if(w==="pin"){await Uf(s[2],s[3]);return}if(w==="add"){let b=e.indexOf(a),S=e.slice(b+1);await jf(S[1],S.slice(2));return}if(w==="remove"){await qf(s[2]);return}if(w==="uninstall"){await Wf(s[2]);return}if(w==="log"||w==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:k,rest:A}=Mc(S);await Df(k,A);return}if(w==="auth"){await Yw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
514
+ `),process.exit(2);return}k.limit=A}await Ky(k);return}if(w==="export"){let b=kt(r,"out"),S=kt(r,"tools");await Jy(s[2],b,S);return}if(w==="transcript"){let b=kt(r,"out"),S=r.tools===!0;await Yy(s[2],b,{includeTools:S});return}if(w==="import"){let b=kt(r,"cwd");await Vy(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(w==="share"){let b=kt(r,"host"),S=kt(r,"cwd");await Qy(s[2],{...b!==void 0?{host:b}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
515
+ `),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await pw();return}if(S==="add"){await hw(k,A);return}if(S==="remove"){await mw(k);return}if(S==="start"){await gw(k);return}if(S==="stop"){await yw(k);return}if(S==="restart"){await ww(k);return}if(S==="log"||S==="logs"){await bw(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
516
+ `),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),b=e.slice(w+1),S=b[0],k=b[1],A=b.slice(2);if(S===void 0||S==="list"){await vw();return}if(S==="add"){await Sw(k,A);return}if(S==="remove"){await kw(k);return}if(S==="start"){await Iw(k);return}if(S==="stop"){await xw(k);return}if(S==="restart"){await Aw(k);return}if(S==="log"||S==="logs"){await Cw(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
517
+ `),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await Lf();return}if(w==="refresh"){await Vc();return}if(w==="install"){await Bf(s[2]);return}if(w==="sync"){await Nf(s[2]);return}if(w==="set"){await Hf(s[2],s[3]);return}if(w==="pin"){await Uf(s[2],s[3]);return}if(w==="add"){let b=e.indexOf(a),S=e.slice(b+1);await jf(S[1],S.slice(2));return}if(w==="remove"){await qf(s[2]);return}if(w==="uninstall"){await Wf(s[2]);return}if(w==="log"||w==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:k,rest:A}=Mc(S);await Df(k,A);return}if(w==="auth"){await Vw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
518
518
  `),process.exit(2);return}case"registry":{let w=s[1];if(w==="refresh"){await Vc();return}if(w==="pin"){await Qc(!0);return}if(w==="unpin"){await Qc(!1);return}process.stderr.write(`Unknown registry subcommand: ${w}
519
- `),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let b=s[2];if(b===void 0||b==="set"){await Vw(r);return}process.stderr.write(`Unknown auth password action: ${b}
520
- `),process.exit(2);return}if(w===void 0||w==="list"){await Qw();return}if(w==="revoke"){await Gw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
521
- `),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await mb(s[2]);return}if(w==="get"){await fb(s[2]);return}if(w==="set"){await pb(s[2],s[3]);return}if(w==="unset"){await hb(s[2]);return}if(w==="path"){gb();return}process.stderr.write(`Unknown config subcommand: ${w}
522
- `),process.exit(2);return}case"tui":br=!0,await Jv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
523
- `),qp(),process.exit(2)}}async function Jv(n,e){let t=kt(n,"cwd"),s=n.reattach===!0,r=n.new===!0,i=n.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 Jc(e.agentId),Ao(Co(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Wv(),qv)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),t!==void 0&&(a.cwd=t),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),n.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
524
- `),process.exit(2)),a.drip=!0;let c=jp(n,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function jp(n,e){let t=n[e];if(t!==void 0){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s}}}function Yv(n){let e=Yp(n);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
519
+ `),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let b=s[2];if(b===void 0||b==="set"){await Qw(r);return}process.stderr.write(`Unknown auth password action: ${b}
520
+ `),process.exit(2);return}if(w===void 0||w==="list"){await Gw();return}if(w==="revoke"){await Xw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
521
+ `),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await gb(s[2]);return}if(w==="get"){await pb(s[2]);return}if(w==="set"){await hb(s[2],s[3]);return}if(w==="unset"){await mb(s[2]);return}if(w==="path"){yb();return}process.stderr.write(`Unknown config subcommand: ${w}
522
+ `),process.exit(2);return}case"tui":br=!0,await Yv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
523
+ `),qp(),process.exit(2)}}async function Yv(n,e){let t=kt(n,"cwd"),s=n.reattach===!0,r=n.new===!0,i=n.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 Jc(e.agentId),Ao(Co(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(zv(),Wv)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),t!==void 0&&(a.cwd=t),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),n.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
524
+ `),process.exit(2)),a.drip=!0;let c=jp(n,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function jp(n,e){let t=n[e];if(t!==void 0){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s}}}function Vv(n){let e=Yp(n);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
525
525
 
526
- `),qp(),process.exit(2))}function Dp(n){for(let e=0;e<n.length;e+=1){let t=n[e];if(t!==void 0){if(t==="-p")return n[e+1];if(t.startsWith("-p")&&!t.startsWith("--"))return t.slice(2)}}}async function Vv(n,e){try{return await Sh(n,e)}catch(t){ie({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`${t.message}
527
- `),process.exit(1)}}function aP(){try{let n=rP(sP(import.meta.url));return JSON.parse(nP(iP(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Hp=["tui"],Qv=["shim","acp"],xt=["cat"],Ml=["launch"],dP=["init"],_l=["daemon"],cP=["version"],ht=["session","sessions"],td=["extension","extensions"],nd=["transformer","transformers"],qn=["agent","agents"],lP=["registry"],sd=["config"],Up=["auth"];function qp(n){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."},[Hp," hydra-acp tui [same flags] Force TUI explicitly."],[Qv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Qv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[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."],[Ml," hydra-acp launch <agent> [agent-args...]"],[Ml," Shim mode, force daemon to spawn <agent>"],[Ml," from the registry. Args after <agent>"],[Ml," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[dP," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[_l," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[_l," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[_l," hydra-acp daemon stop|restart"],[_l," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[cP," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ht," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ht," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ht," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."],[ht," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ht," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."],[ht," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ht," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."],[ht," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ht," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."],[ht," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ht," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ht," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ht," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."],[ht," hydra-acp session export <id> [--out <file>|.]"],[ht," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ht," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ht," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"],[ht," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ht," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."],[td," hydra-acp extension list List configured extensions and live state"],[td," hydra-acp extension add <name> [opts] Add an extension to config"],[td," hydra-acp extension remove <name> Remove an extension from config"],[td," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[td," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[nd," hydra-acp transformer list List configured transformers and live state"],[nd," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[nd," hydra-acp transformer remove <name> Remove a transformer from config"],[nd," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[nd," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[qn," hydra-acp agent [list] List agents in the cached registry"],[qn," hydra-acp agent refresh Force a registry re-fetch"],[qn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[qn," 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>])."],[qn," 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."],[qn," 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)."],[qn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[qn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[lP," 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."],[qn," 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`"],[qn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[qn," hydra-acp agent auth <id> Run the auth flow for <id>"],[sd," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[sd," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[sd," 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."],[sd," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[sd," 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"],[Hp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Hp," 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"},""],t=[];for(let s of e){if(typeof s=="string"){t.push(s);continue}if("globalOnly"in s){n===void 0&&t.push(s.globalOnly);continue}let[r,i]=s;(n===void 0||r.includes(n))&&t.push(i)}process.stdout.write(t.join(`
526
+ `),qp(),process.exit(2))}function Dp(n){for(let e=0;e<n.length;e+=1){let t=n[e];if(t!==void 0){if(t==="-p")return n[e+1];if(t.startsWith("-p")&&!t.startsWith("--"))return t.slice(2)}}}async function Qv(n,e){try{return await Sh(n,e)}catch(t){ie({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`${t.message}
527
+ `),process.exit(1)}}function lP(){try{let n=aP(oP(import.meta.url));return JSON.parse(iP(dP(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Hp=["tui"],Gv=["shim","acp"],xt=["cat"],Ml=["launch"],uP=["init"],_l=["daemon"],fP=["version"],ht=["session","sessions"],td=["extension","extensions"],nd=["transformer","transformers"],qn=["agent","agents"],pP=["registry"],sd=["config"],Up=["auth"];function qp(n){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."},[Hp," hydra-acp tui [same flags] Force TUI explicitly."],[Gv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Gv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[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."],[Ml," hydra-acp launch <agent> [agent-args...]"],[Ml," Shim mode, force daemon to spawn <agent>"],[Ml," from the registry. Args after <agent>"],[Ml," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[uP," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[_l," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[_l," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[_l," hydra-acp daemon stop|restart"],[_l," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[fP," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[ht," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[ht," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[ht," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."],[ht," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[ht," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."],[ht," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[ht," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."],[ht," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[ht," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."],[ht," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[ht," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[ht," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[ht," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."],[ht," hydra-acp session export <id> [--out <file>|.]"],[ht," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[ht," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"],[ht," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[ht," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"],[ht," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[ht," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."],[td," hydra-acp extension list List configured extensions and live state"],[td," hydra-acp extension add <name> [opts] Add an extension to config"],[td," hydra-acp extension remove <name> Remove an extension from config"],[td," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[td," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[nd," hydra-acp transformer list List configured transformers and live state"],[nd," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[nd," hydra-acp transformer remove <name> Remove a transformer from config"],[nd," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[nd," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[qn," hydra-acp agent [list] List agents in the cached registry"],[qn," hydra-acp agent refresh Force a registry re-fetch"],[qn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[qn," 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>])."],[qn," 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."],[qn," 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)."],[qn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[qn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[pP," 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."],[qn," 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`"],[qn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[qn," hydra-acp agent auth <id> Run the auth flow for <id>"],[sd," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[sd," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[sd," 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."],[sd," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[sd," 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"],[Hp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Hp," 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"},""],t=[];for(let s of e){if(typeof s=="string"){t.push(s);continue}if("globalOnly"in s){n===void 0&&t.push(s.globalOnly);continue}let[r,i]=s;(n===void 0||r.includes(n))&&t.push(i)}process.stdout.write(t.join(`
528
528
  `)+`
529
- `)}async function Gv(){if(!br)try{let n=await ja();n&&process.stderr.write(`\u2728 ${qa(n)}
530
- `)}catch{}}oP().then(Gv).catch(async n=>{ie({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`hydra-acp: ${n.message}
531
- `),await Gv(),process.exit(1)});
529
+ `)}async function Xv(){if(!br)try{let n=await ja();n&&process.stderr.write(`\u2728 ${qa(n)}
530
+ `)}catch{}}cP().then(Xv).catch(async n=>{ie({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n),cause:Zv(n.cause)});let e=hP(n.cause),t=e?` (${e})`:"";process.stderr.write(`hydra-acp: ${n.message}${t}
531
+ `),await Xv(),process.exit(1)});function Zv(n){if(n!=null){if(n instanceof Error){let e=n;return{message:e.message,code:e.code,errno:e.errno,syscall:e.syscall,address:e.address,port:e.port,stack:e.stack,cause:Zv(e.cause)}}return String(n)}}function hP(n){if(!(n instanceof Error))return"";let e=n,t=[];return e.code&&t.push(e.code),(e.address!==void 0||e.port!==void 0)&&t.push(`${e.address??""}:${e.port??""}`),e.message&&t.length===0&&t.push(e.message),t.join(" ")}