@hydra-acp/cli 0.1.126 → 0.1.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +184 -184
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Vk=Object.defineProperty;var J=(n,e)=>()=>(n&&(e=n(n=0)),e);var lu=(n,e)=>{for(var t in e)Vk(n,t,{get:e[t],enumerable:!0})};import*as ge from"path";import*as fu from"os";function lt(n){let e=fu.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function eI(){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 Se(){let n=process.env[Zk];if(n&&n.length>0)return ge.resolve(n);let e=eI();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(fu.homedir(),".hydra-acp")}var Zk,
|
|
3
|
-
`,{encoding:"utf8",mode:384})}async function ra(){let n=await Bi();if(n)return n;let e=Li();return await Ni(e),process.stderr.write(`hydra-acp: initialized ${
|
|
4
|
-
`),e}var
|
|
5
|
-
`;await nI(n,r,t)}async function nI(n,e,t={}){let s=await sI(n),r=rI(s);await Ot.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${iI()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Ot.writeFile(i,e,o),await Ot.rename(i,s)}catch(o){throw await Ot.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Xh.chmodSync(s,t.mode)}catch{}}async function sI(n){let e;try{e=await Ot.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Ot.readlink(n),s=Hn.isAbsolute(t)?t:Hn.resolve(Hn.dirname(n),t);try{let r=await Ot.realpath(Hn.dirname(s));return Hn.join(r,Hn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function Tn(n){let e;try{e=await Ot.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 rI(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function iI(){return tI(4).toString("hex")}var qr=J(()=>{"use strict"});import*as
|
|
6
|
-
`)}async function xe(){return await Pd(),hu.parse(await Ed())}async function ds(n){await Pd();let e=await Ed();n(e),hu.parse(e),await fn(
|
|
2
|
+
var Vk=Object.defineProperty;var J=(n,e)=>()=>(n&&(e=n(n=0)),e);var lu=(n,e)=>{for(var t in e)Vk(n,t,{get:e[t],enumerable:!0})};import*as ge from"path";import*as fu from"os";function lt(n){let e=fu.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function eI(){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 Se(){let n=process.env[Zk];if(n&&n.length>0)return ge.resolve(n);let e=eI();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(fu.homedir(),".hydra-acp")}var Zk,L,we=J(()=>{"use strict";Zk="HYDRA_ACP_HOME";L={home:Se,config:()=>ge.join(Se(),"config.json"),authToken:()=>ge.join(Se(),"auth-token"),remotes:()=>ge.join(Se(),"remotes.json"),pidFile:()=>ge.join(Se(),"daemon.pid"),logFile:()=>ge.join(Se(),"daemon.log"),currentLogFile:()=>ge.join(Se(),"current.log"),registryCache:()=>ge.join(Se(),"registry.json"),ttySessionDir:()=>ge.join(Se(),"tty"),ttySessionFile:n=>ge.join(Se(),"tty",n),agentsDir:()=>ge.join(Se(),"agents"),agentLogFile:n=>ge.join(Se(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>ge.join(Se(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>ge.join(Se(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>ge.join(Se(),"sessions"),sessionDir:n=>ge.join(Se(),"sessions",n),sessionFile:n=>ge.join(Se(),"sessions",n,"meta.json"),historyFile:n=>ge.join(Se(),"sessions",n,"history.jsonl"),historyArchiveFile:(n,e)=>ge.join(Se(),"sessions",n,`history.jsonl.${e}`),toolsDir:n=>ge.join(Se(),"sessions",n,"tools"),toolBlobFile:(n,e)=>ge.join(Se(),"sessions",n,"tools",e),queueFile:n=>ge.join(Se(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>ge.join(Se(),"sessions",".tombstones"),tombstoneAgentDir:n=>ge.join(Se(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>ge.join(Se(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>ge.join(Se(),"extensions"),extensionLogDir:n=>ge.join(Se(),"extensions",n),extensionLogFile:n=>ge.join(Se(),"extensions",n,"current.log"),extensionPidFile:n=>ge.join(Se(),"extensions",n,"extension.pid"),transformersDir:()=>ge.join(Se(),"transformers"),transformerLogDir:n=>ge.join(Se(),"transformers",n),transformerLogFile:n=>ge.join(Se(),"transformers",n,"current.log"),transformerPidFile:n=>ge.join(Se(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>ge.join(Se(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>ge.join(Se(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>ge.join(Se(),"prompt-history"),tuiLogFile:()=>ge.join(Se(),"tui.log"),shimWireLogFile:()=>ge.join(Se(),"shim-wire.log")}});import*as Oi from"fs/promises";function Li(){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 Bi(){try{let e=(await Oi.readFile(L.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function jr(){let n=await Bi();if(!n)throw new Error(`No service token found at ${L.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Ni(n){await Oi.mkdir(L.home(),{recursive:!0}),await Oi.writeFile(L.authToken(),n+`
|
|
3
|
+
`,{encoding:"utf8",mode:384})}async function ra(){let n=await Bi();if(n)return n;let e=Li();return await Ni(e),process.stderr.write(`hydra-acp: initialized ${L.authToken()} with a fresh service token.
|
|
4
|
+
`),e}var Ms=J(()=>{"use strict";we()});import*as Ot from"fs/promises";import*as Xh from"fs";import*as Hn from"path";import{randomBytes as tI}from"crypto";async function fn(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
5
|
+
`;await nI(n,r,t)}async function nI(n,e,t={}){let s=await sI(n),r=rI(s);await Ot.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${iI()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Ot.writeFile(i,e,o),await Ot.rename(i,s)}catch(o){throw await Ot.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Xh.chmodSync(s,t.mode)}catch{}}async function sI(n){let e;try{e=await Ot.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Ot.readlink(n),s=Hn.isAbsolute(t)?t:Hn.resolve(Hn.dirname(n),t);try{let r=await Ot.realpath(Hn.dirname(s));return Hn.join(r,Hn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function Tn(n){let e;try{e=await Ot.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 rI(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function iI(){return tI(4).toString("hex")}var qr=J(()=>{"use strict"});import*as sr from"fs/promises";import{homedir as pu}from"os";import{z as q}from"zod";function tm(n){return n.tui.inAppSelection??n.tui.mouse}function nm(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function sm(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Ed(){return await mI(),await Tn(L.config())??{}}async function mI(){let n;try{n=await sr.lstat(L.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await sr.stat(L.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await sr.readlink(L.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${L.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 Pd(){let n=await Ed(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await sr.access(L.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${L.authToken()} and ${L.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ni(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await fn(L.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${L.config()} to ${L.authToken()}.
|
|
6
|
+
`)}async function xe(){return await Pd(),hu.parse(await Ed())}async function ds(n){await Pd();let e=await Ed();n(e),hu.parse(e),await fn(L.config(),e,{mode:384})}async function ia(n,e){await ds(t=>{let s=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};s[n]=e,t.tui=s})}async function rm(n){await ds(e=>{let t=e.tui&&typeof e.tui=="object"&&!Array.isArray(e.tui)?e.tui:{},s=t.sidebar&&typeof t.sidebar=="object"&&!Array.isArray(t.sidebar)?t.sidebar:{};s.enabled=n,t.sidebar=s,e.tui=t})}async function Di(n){await ds(e=>{e.defaultAgent=n})}async function im(n,e){await ds(t=>{let s=t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{};s[n]=e,t.defaultModels=s})}async function om(n,e){await ds(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 mu(n,e){await ds(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 am(n){await ds(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function dm(){let n=await Ed();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function st(n){return n==="~"||n==="$HOME"?pu():n.startsWith("~/")?pu()+n.slice(1):n.startsWith("$HOME/")?pu()+n.slice(5):n}var em,oI,Un,aI,dI,cI,lI,uI,fI,Zh,pI,hI,hu,et=J(()=>{"use strict";we();Ms();qr();em="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",oI=q.object({cert:q.string(),key:q.string()}),Un=55514,aI=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Un),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:oI.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:q.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:q.number().int().positive().default(10),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),dI=q.object({url:q.string().url().default(em),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),cI=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),lI=q.object({packageSpec:q.string().optional()}),uI=q.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),fI=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),sidebar:q.object({enabled:q.boolean().default(!1),width:q.number().int().positive().optional(),border:q.enum(["none","rule","frame"]).default("frame"),gadgets:q.array(q.string()).default(["activity","context","queue","todo","files","git","resources","session","tools"])}).default({enabled:!1,border:"frame",gadgets:["activity","context","queue","todo","files","git","resources","session","tools"]}),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:q.record(uI,q.object({command:q.union([q.string(),q.array(q.string())])})).default({})}),Zh=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),pI=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),hI=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),hu=q.object({daemon:aI.default({}),registry:dI.default({url:em,ttlHours:24,pinned:!1}),agents:q.record(q.string(),cI).default({}),agentOverrides:q.record(q.string(),lI).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(Zh,pI).default({}),transformers:q.record(Zh,hI).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:fI.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",sidebar:{enabled:!1,border:"frame",gadgets:["activity","context","queue","todo","files","git","resources","session","tools"]}})})});function Wr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function gu(n){return{httpScheme:"https",wsScheme:"wss"}}function yu(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 ${Md(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Md(n)}`);let t=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(t){let c=Number(t[1]);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${t[1]}`)}let s=gI(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Md(n)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Md(n)}`);let i=Wr(r),o;if(s.port){let c=Number(s.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=c}else o=Un;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function cm(n){let e=n.port!==void 0&&n.port!==Un?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function gI(n){try{return new URL(n)}catch{return null}}function Md(n){return n.length>80?`${n.slice(0,77)}...`:n}var oa=J(()=>{"use strict";et()});function zr(n,e){return`${n}:${e}`}function lm(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function yI(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 wI(){let n=await Tn(L.remotes());return n===void 0?{version:1,entries:{}}:bI(n)}function bI(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 wu(n){await fn(L.remotes(),n,{mode:384})}var _d,bu=J(()=>{"use strict";we();qr();_d=class n{data;constructor(e){this.data=e}static async load(){let e=await wI(),t=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(lm(a,t)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await wu(i),new n(i)}get(e,t){let s=this.data.entries[zr(e,t)];if(s&&!lm(s,Date.now()))return s}async set(e,t,s){this.data.entries[zr(e,t)]=s,await wu(this.data)}async delete(e,t){let s=zr(e,t);return s in this.data.entries?(delete this.data.entries[s],await wu(this.data),!0):!1}list(){let e=[];for(let[t,s]of Object.entries(this.data.entries)){let r=yI(t);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Hi(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",d),r||s.setRawMode(!1),s.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
|
|
7
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)}},d=c=>{o(),t(c)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",d)}):vI()}function vI(){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 vu=J(()=>{"use strict"});import*as um from"path";function cs(){let n=process.argv[1];if(!n)return"hydra-acp";let e=um.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var aa=J(()=>{"use strict"});import*as $d from"fs/promises";async function ls(){try{let n=await $d.readFile(
|
|
9
|
-
`,{encoding:"utf8",mode:384})}function En(n){try{return process.kill(n,0),!0}catch{return!1}}var Ui=J(()=>{"use strict";we()});var wm={};lu(wm,{_resetForTests:()=>EI,clearPin:()=>RI,fetchPeerFingerprint:()=>xu,formatFingerprint:()=>Fd,getPin:()=>ku,installGlobalTlsTrust:()=>Cu,loadPinsFromStore:()=>Iu,setPin:()=>da,sha256Hex:()=>Au,wsTlsOptions:()=>ca});import{createHash as SI}from"crypto";import*as pm from"tls";import{Agent as kI,Dispatcher as II,buildConnector as xI,getGlobalDispatcher as AI,setGlobalDispatcher as CI}from"undici";function da(n,e,t){Kr.set(zr(n,e),hm(t))}function RI(n,e){Kr.delete(zr(n,e))}function ku(n,e){return Kr.get(zr(n,e))}function Iu(n){Kr.clear();for(let e of n.list())e.entry.pinnedFingerprint&&da(e.host,e.port,e.entry.pinnedFingerprint)}async function xu(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=pm.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(l,
|
|
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 vu=J(()=>{"use strict"});import*as um from"path";function cs(){let n=process.argv[1];if(!n)return"hydra-acp";let e=um.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var aa=J(()=>{"use strict"});import*as $d from"fs/promises";async function ls(){try{let n=await $d.readFile(L.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 fm(n){await $d.writeFile(L.pidFile(),JSON.stringify(n)+`
|
|
9
|
+
`,{encoding:"utf8",mode:384})}function En(n){try{return process.kill(n,0),!0}catch{return!1}}var Ui=J(()=>{"use strict";we()});var wm={};lu(wm,{_resetForTests:()=>EI,clearPin:()=>RI,fetchPeerFingerprint:()=>xu,formatFingerprint:()=>Fd,getPin:()=>ku,installGlobalTlsTrust:()=>Cu,loadPinsFromStore:()=>Iu,setPin:()=>da,sha256Hex:()=>Au,wsTlsOptions:()=>ca});import{createHash as SI}from"crypto";import*as pm from"tls";import{Agent as kI,Dispatcher as II,buildConnector as xI,getGlobalDispatcher as AI,setGlobalDispatcher as CI}from"undici";function da(n,e,t){Kr.set(zr(n,e),hm(t))}function RI(n,e){Kr.delete(zr(n,e))}function ku(n,e){return Kr.get(zr(n,e))}function Iu(n){Kr.clear();for(let e of n.list())e.entry.pinnedFingerprint&&da(e.host,e.port,e.entry.pinnedFingerprint)}async function xu(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=pm.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(l,u)=>{if(!a){a=!0,clearTimeout(c);try{o.destroy()}catch{}l?i(l):u&&r(u)}},c=setTimeout(()=>{d(new Error(`TLS connect to ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){d(new Error(`${n}:${e} did not present a TLS certificate`));return}d(null,Au(l.raw))}),o.once("error",l=>d(l))})}function Au(n){return SI("sha256").update(n).digest("hex")}function Fd(n){let e=hm(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function hm(n){return n.replace(/:/g,"").toLowerCase()}function Cu(){if(Su)return;Su=!0;let n=AI(),e=new kI({connect:xI({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>gm(s,r)})}),t=new II;t.dispatch=(s,r)=>{let i=TI(s.origin);return(i&&mm(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(()=>{})),CI(t)}function TI(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function mm(n){for(let e of Kr.keys())if(ym(e)?.host===n)return!0;return!1}function gm(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Au(e.raw);for(let[s,r]of Kr.entries()){let i=ym(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${Fd(t)})`)}function ym(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 ca(n){return mm(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>gm(e,t)}:{autoSelectFamily:!0}}function EI(){Kr.clear(),Su=!1}var Kr,Su,la=J(()=>{"use strict";bu();Kr=new Map,Su=!1});import*as km from"os";async function Wt(n){let e=await ra(),t=await ls();if(t&&En(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:Wr(r)}}function bm(n,e){let{httpScheme:t,wsScheme:s}=gu(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${s}://${n.host}:${n.port}/acp`,token:e,display:xm(n),isLocal:n.isLoopback}}async function Im(n,e={}){let t=e.fetchImpl??fetch,s=e.promptImpl??Hi,r=e.confirmImpl??$I,i=e.tlsHandshakeImpl??PI,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&o){let w=await Bi();if(w)return _I(n,w)}let d=e.store??await _d.load();Iu(d),Cu();let c=d.get(n.host,n.port);if(c)return c.pinnedFingerprint&&da(n.host,n.port,c.pinnedFingerprint),bm(n,c.token);if(!a)throw new Ru(n.host,n.port);let l=xm(n),{httpScheme:u}=gu(n.host),f;if(u==="https"&&ku(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: ${Fd(w.fingerprint)}${b}
|
|
13
|
-
`),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);da(n.host,n.port,w.fingerprint),
|
|
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 Sm(){try{let n=km.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function xm(n){return n.port===Un?n.host:`${n.host}:${n.port}`}var Ru,Jr=J(()=>{"use strict";et();
|
|
15
|
-
`)}catch{}}function BI(n){try{if(LI(n).size<Cm)return;OI(n,`${n}.0`)}catch{}}var Cm,Vr=J(()=>{"use strict";we();Cm=5*1024*1024});import*as Hm from"fs";import*as
|
|
16
|
-
`))}async function jm(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${Pn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=Pn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=
|
|
17
|
-
`)}});var W,Dd=J(()=>{"use strict";W={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as He}from"zod";var Ym,lx,Qm,Xm,Zm,Hu=J(()=>{"use strict";Ym=He.object({protocolVersion:He.number().optional(),clientCapabilities:He.record(He.unknown()).optional(),clientInfo:He.object({name:He.string(),version:He.string().optional()}).optional()}),lx=He.enum(["full","pending_only","none","after_message"]),Qm=He.object({cwd:He.string(),mcpServers:He.array(He.unknown()).optional(),_meta:He.record(He.unknown()).optional()}),Xm=He.object({upstreamSessionId:He.string(),agentId:He.string(),cwd:He.string(),title:He.string().optional(),agentArgs:He.array(He.string()).optional()}),Zm=He.object({sessionId:He.string(),historyPolicy:lx.default("full"),afterMessageId:He.string().optional(),clientId:He.string().optional(),clientInfo:He.object({name:He.string(),version:He.string().optional()}).optional(),_meta:He.record(He.unknown()).optional()})});import{z as fe}from"zod";function Hd(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 ng(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:fa(n._meta,Hd(n))};return n.title!==void 0&&(e.title=n.title),e}var eg,tg,Uu,yF,ux,wF,ju=J(()=>{"use strict";Ud();eg=fe.object({sessionId:fe.string()}),tg=fe.object({cwd:fe.string().optional(),cursor:fe.string().optional()}),Uu=fe.object({used:fe.number().optional(),size:fe.number().optional(),costAmount:fe.number().optional(),costCurrency:fe.string().optional()}),yF=fe.object({sessionId:fe.string(),upstreamSessionId:fe.string().optional(),cwd:fe.string(),title:fe.string().optional(),agentId:fe.string().optional(),currentModel:fe.string().optional(),currentUsage:Uu.optional(),importedFromMachine:fe.string().optional(),importedFromUpstreamSessionId:fe.string().optional(),parentSessionId:fe.string().optional(),forkedFromSessionId:fe.string().optional(),forkedFromMessageId:fe.string().optional(),originatingClient:fe.object({name:fe.string(),version:fe.string().optional()}).optional(),interactive:fe.boolean().optional(),priority:fe.number().int().nonnegative().optional(),updatedAt:fe.string(),attachedClients:fe.number().int().nonnegative(),status:fe.enum(["warm","cold"]).default("warm"),busy:fe.boolean().default(!1),awaitingInput:fe.boolean().default(!1),compactionState:fe.any().optional(),agentPid:fe.number().int().positive().optional(),forkSynthesisState:fe.enum(["running","failed"]).optional(),_meta:fe.record(fe.unknown()).optional()}),ux=fe.object({sessionId:fe.string(),cwd:fe.string(),title:fe.string().optional(),updatedAt:fe.string().optional(),_meta:fe.record(fe.unknown()).optional()}),wF=fe.object({sessions:fe.array(ux),nextCursor:fe.string().optional()})});function fx(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 hn(n){if(!n)return{};let e=n[Bt];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=Xm.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=Uu.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="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=fx(t.env);r!==void 0&&(s.env=r)}return s}function fa(n,e){return{...n??{},[Bt]:e}}var Bt,Ud=J(()=>{"use strict";Hu();ju();Bt="hydra-acp"});import{z as te}from"zod";var sg,jd,rg,xF,AF,CF,ig,RF,og,TF,ag,EF,PF,dg=J(()=>{"use strict";sg=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),jd=te.object({sessionId:te.string()}),rg=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),xF=te.object({sessionId:te.string(),messageId:te.string(),originator:rg,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),AF=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),CF=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),ig=te.object({sessionId:te.string(),messageId:te.string()}),RF=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),og=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),TF=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),ag=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),EF=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),PF=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:rg,amendedAt:te.number()})});import{z as rr}from"zod";var cg,qd,Ji,lg=J(()=>{"use strict";cg=rr.object({agentId:rr.string(),version:rr.string(),source:rr.enum(["binary","npm"]),phase:rr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:rr.number().optional(),totalBytes:rr.number().optional(),packageSpec:rr.string().optional()}),qd="hydra-acp/agents/install_progress",Ji={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Nt=J(()=>{"use strict";Dd();Hu();Ud();ju();dg();lg()});import{nanoid as px}from"nanoid";var qu,Zt,Yr=J(()=>{"use strict";Nt();qu=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 qu;let s=px(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:W.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??W.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 fg from"os";function or(){return fg.hostname()}function Wu(){let n=new Set;n.add(or());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 pa=J(()=>{"use strict"});async function Vi(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Gi(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 zu=J(()=>{"use strict"});function pg(n){return n!==void 0&&wx.has(n)}function Ku(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let s=t.path;typeof s=="string"&&s.length>0&&e.push(s)}return e}function Jd(n){return Ku(n)[0]}var wx,hg,Kd,ha=J(()=>{"use strict";wx=new Set(["edit","delete","move"]);hg="edit",Kd=class{kinds=new Map;note(e,t){t!==void 0&&t.length>0&&!this.kinds.has(e)&&this.kinds.set(e,t)}get(e){return this.kinds.get(e)}effective(e,t){return t!==void 0&&t.length>0?t:this.kinds.get(e)}clear(){this.kinds.clear()}get size(){return this.kinds.size}}});import*as gg from"fs/promises";function Cx(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var bx,vx,Yi,Sx,kx,Ix,xx,Ax,mg,Vd,yg=J(()=>{"use strict";bx=64*1024*1024,vx=1*1024*1024,Yi=64*1024,Sx=6e4,kx=100,Ix=1e3,xx=64*1024,Ax=256*1024,mg=20;Vd=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??bx,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(vx,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,Yi));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Yi)),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,Yi)),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,Sx));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Cx(e.pattern),d),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??kx,Ix)),u=Math.max(1,Math.min(e.maxBytes??xx,Ax)),p=Math.max(0,Math.min(e.contextBefore??0,mg)),h=Math.max(0,Math.min(e.contextAfter??0,mg)),m=[],y=[],w=[],b=0,v=!1,k=0,A=0,E=(_,F)=>{for(let Q of w)Q.remaining>0&&(Q.match.after===void 0&&(Q.match.after=[]),Q.match.after.push({cursor:_,line:F}),Q.remaining--,b+=F.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test(F)!==l&&m.length<f){let Q={cursor:_,line:F};if(p>0&&y.length>0){Q.before=y.slice();for(let X of Q.before)b+=X.line.length}b+=F.length,m.push(Q),h>0&&w.push({match:Q,remaining:h})}if(p>0)for(y.push({cursor:_,line:F});y.length>p;)y.shift();let N=m.length>=f&&w.length===0,q=b>=u;return N||q};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)){v=!0;break}}if(!v&&k<o.length&&this.closed){let _=o.subarray(k).toString("utf8"),F=r+k;E(F,_)&&(v=!0),A=o.length}let P=Math.min(r+A,this.writeCursor),H={matches:m,truncated:v,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(()=>gg.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Qi,tO,wg=J(()=>{"use strict";Qi=[{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."}],tO=new Map(Qi.map(n=>[n.verb,n]))});function bg(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Xi(n,e){return Ju(n,e.map(t=>t.modelId))}function Ju(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=bg(n),s=e.filter(i=>bg(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 Gd=J(()=>{"use strict"});function Sg(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=Vu(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0){e.set(l,a);for(let f of Px){if(!vg(c[f]))continue;let u=s.get(l);u===void 0?s.set(l,new Map([[f,c[f]]])):u.set(f,c[f])}if(Array.isArray(c.content)&&c.content.length>0){let f=t.get(l);f?f.push(...c.content):t.set(l,[...c.content])}}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=Vu(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Tx(r,i.outIndex,Rx(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&t.has(f)?Ex(d,t.get(f)??[]):d,p=f===void 0?void 0:s.get(f);if(p!==void 0)for(let[h,m]of p)vg(Vu(u)?.[h])||(u=Mx(u,h,m));r.push(u);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function Vu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Rx(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Tx(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 Ex(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function vg(n){return n==null||typeof n!="object"?!1:Array.isArray(n)?n.length>0:Object.keys(n).length>0}function Mx(n,e,t){let s=n.params??{},r=s.update??{};return{...n,params:{...s,update:{...r,[e]:t}}}}var Px,kg=J(()=>{"use strict";Px=["rawInput","locations"]});function Zi(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received"){i();let l=Yu(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=Qu(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(i(),s.push(Gu(d))):c==="turn_complete"&&i()}return i(),Lx(s.join(`
|
|
13
|
+
`),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);da(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:Sm()})});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 d.set(n.host,n.port,{token:y.session_token,expiresAt:y.expires_at,label:Sm(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),bm(n,y.session_token)}async function PI(n,e){let t=await MI(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await xu(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function MI(n,e,t=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=c=>{if(!i){i=!0,clearTimeout(d);try{a.destroy()}catch{}r(c)}},a=s.connect({host:n,port:e,servername:n,autoSelectFamily:!0}),d=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",c=>{let l=c.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?vm(p.subject):void 0,issuer:p?.issuer?vm(p.issuer):void 0});return}let f=[l,c.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 vm(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 _I(n,e){let t=await ls(),r=t&&En(t.pid)?t.loopbackPort:n.port,i=n.port===Un?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 $I(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 Sm(){try{let n=km.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function xm(n){return n.port===Un?n.host:`${n.host}:${n.port}`}var Ru,Jr=J(()=>{"use strict";et();Ms();oa();bu();vu();aa();Ui();la();oa();Ru=class extends Error{host;port;constructor(e,t){let s=t===Un?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${cs()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as FI,renameSync as OI,statSync as LI}from"fs";function Rm(n){Cm=n}function re(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?L.tuiLogFile():e;if(t.length!==0)try{BI(t);let s=JSON.stringify({t:new Date().toISOString(),...n});FI(t,`${s}
|
|
15
|
+
`)}catch{}}function BI(n){try{if(LI(n).size<Cm)return;OI(n,`${n}.0`)}catch{}}var Cm,Vr=J(()=>{"use strict";we();Cm=5*1024*1024});import*as Hm from"fs";import*as zt from"fs/promises";import*as rr from"path";import{spawn as Um}from"child_process";import{Readable as qI}from"stream";function Pn(){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 $u(n,e=Pn()){if(e)return n[e]}function Fu(n){ji=n??(e=>process.stderr.write(e+`
|
|
16
|
+
`))}async function jm(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${Pn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=Pn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentInstallDir(n.agentId,e,n.version),s=rr.resolve(t,n.target.cmd);if(await _u(s))return s;if(await WI({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await _u(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await zt.chmod(s,493).catch(()=>{}),s}async function WI(n){await zt.mkdir(rr.dirname(n.installDir),{recursive:!0});let e=await zt.mkdtemp(`${n.installDir}.partial-`);try{ji(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await zI({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});ji(`hydra-acp: extracting ${n.agentId}`),qi(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await JI(t,e),await zt.unlink(t).catch(()=>{});try{await zt.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await _u(n.installDir)){await zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),qi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}ji(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),qi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function qi(n,e){if(n)try{n(e)}catch{}}async function zI(n){let e=KI(n.url),t=rr.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=Hm.createWriteStream(t),o=qI.fromWeb(s.body);qi(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),c=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-c>=u&&(c=p,qi(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=l&&(d=p,ji(Dm(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),ji(Dm(n.agentId,a,r,!0)),qi(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Dm(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 KI(n){let e=new URL(n);return rr.posix.basename(e.pathname)||"archive"}async function JI(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await Mu("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await VI("unzip")){await Mu("unzip",["-q",n,"-d",e]);return}await Mu("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function Mu(n,e){return new Promise((t,s)=>{let r=Um(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 VI(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Um(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function _u(n){try{return await zt.access(n),!0}catch{return!1}}var ji,Wi=J(()=>{"use strict";we();ji=n=>{process.stderr.write(n+`
|
|
17
|
+
`)}});var W,Dd=J(()=>{"use strict";W={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as He}from"zod";var Ym,lx,Qm,Xm,Zm,Hu=J(()=>{"use strict";Ym=He.object({protocolVersion:He.number().optional(),clientCapabilities:He.record(He.unknown()).optional(),clientInfo:He.object({name:He.string(),version:He.string().optional()}).optional()}),lx=He.enum(["full","pending_only","none","after_message"]),Qm=He.object({cwd:He.string(),mcpServers:He.array(He.unknown()).optional(),_meta:He.record(He.unknown()).optional()}),Xm=He.object({upstreamSessionId:He.string(),agentId:He.string(),cwd:He.string(),title:He.string().optional(),agentArgs:He.array(He.string()).optional()}),Zm=He.object({sessionId:He.string(),historyPolicy:lx.default("full"),afterMessageId:He.string().optional(),clientId:He.string().optional(),clientInfo:He.object({name:He.string(),version:He.string().optional()}).optional(),_meta:He.record(He.unknown()).optional()})});import{z as fe}from"zod";function Hd(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 ng(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:fa(n._meta,Hd(n))};return n.title!==void 0&&(e.title=n.title),e}var eg,tg,Uu,wF,ux,bF,ju=J(()=>{"use strict";Ud();eg=fe.object({sessionId:fe.string()}),tg=fe.object({cwd:fe.string().optional(),cursor:fe.string().optional()}),Uu=fe.object({used:fe.number().optional(),size:fe.number().optional(),costAmount:fe.number().optional(),costCurrency:fe.string().optional()}),wF=fe.object({sessionId:fe.string(),upstreamSessionId:fe.string().optional(),cwd:fe.string(),title:fe.string().optional(),agentId:fe.string().optional(),currentModel:fe.string().optional(),currentUsage:Uu.optional(),importedFromMachine:fe.string().optional(),importedFromUpstreamSessionId:fe.string().optional(),parentSessionId:fe.string().optional(),forkedFromSessionId:fe.string().optional(),forkedFromMessageId:fe.string().optional(),originatingClient:fe.object({name:fe.string(),version:fe.string().optional()}).optional(),interactive:fe.boolean().optional(),priority:fe.number().int().nonnegative().optional(),updatedAt:fe.string(),attachedClients:fe.number().int().nonnegative(),status:fe.enum(["warm","cold"]).default("warm"),busy:fe.boolean().default(!1),awaitingInput:fe.boolean().default(!1),compactionState:fe.any().optional(),agentPid:fe.number().int().positive().optional(),forkSynthesisState:fe.enum(["running","failed"]).optional(),_meta:fe.record(fe.unknown()).optional()}),ux=fe.object({sessionId:fe.string(),cwd:fe.string(),title:fe.string().optional(),updatedAt:fe.string().optional(),_meta:fe.record(fe.unknown()).optional()}),bF=fe.object({sessions:fe.array(ux),nextCursor:fe.string().optional()})});function fx(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 hn(n){if(!n)return{};let e=n[Bt];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=Xm.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=Uu.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="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=fx(t.env);r!==void 0&&(s.env=r)}return s}function fa(n,e){return{...n??{},[Bt]:e}}var Bt,Ud=J(()=>{"use strict";Hu();ju();Bt="hydra-acp"});import{z as te}from"zod";var sg,jd,rg,AF,CF,RF,ig,TF,og,EF,ag,PF,MF,dg=J(()=>{"use strict";sg=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),jd=te.object({sessionId:te.string()}),rg=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),AF=te.object({sessionId:te.string(),messageId:te.string(),originator:rg,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),CF=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),RF=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),ig=te.object({sessionId:te.string(),messageId:te.string()}),TF=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),og=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),EF=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),ag=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),PF=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),MF=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:rg,amendedAt:te.number()})});import{z as ir}from"zod";var cg,qd,Ji,lg=J(()=>{"use strict";cg=ir.object({agentId:ir.string(),version:ir.string(),source:ir.enum(["binary","npm"]),phase:ir.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ir.number().optional(),totalBytes:ir.number().optional(),packageSpec:ir.string().optional()}),qd="hydra-acp/agents/install_progress",Ji={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Nt=J(()=>{"use strict";Dd();Hu();Ud();ju();dg();lg()});import{nanoid as px}from"nanoid";var qu,Zt,Yr=J(()=>{"use strict";Nt();qu=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 qu;let s=px(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:W.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??W.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 fg from"os";function ar(){return fg.hostname()}function Wu(){let n=new Set;n.add(ar());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 pa=J(()=>{"use strict"});async function Vi(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Gi(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 zu=J(()=>{"use strict"});function pg(n){return n!==void 0&&wx.has(n)}function Ku(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let s=t.path;typeof s=="string"&&s.length>0&&e.push(s)}return e}function Jd(n){return Ku(n)[0]}var wx,hg,Kd,ha=J(()=>{"use strict";wx=new Set(["edit","delete","move"]);hg="edit",Kd=class{kinds=new Map;note(e,t){t!==void 0&&t.length>0&&!this.kinds.has(e)&&this.kinds.set(e,t)}get(e){return this.kinds.get(e)}effective(e,t){return t!==void 0&&t.length>0?t:this.kinds.get(e)}clear(){this.kinds.clear()}get size(){return this.kinds.size}}});import*as gg from"fs/promises";function Cx(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var bx,vx,Yi,Sx,kx,Ix,xx,Ax,mg,Vd,yg=J(()=>{"use strict";bx=64*1024*1024,vx=1*1024*1024,Yi=64*1024,Sx=6e4,kx=100,Ix=1e3,xx=64*1024,Ax=256*1024,mg=20;Vd=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??bx,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(vx,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,Yi));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Yi)),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,Yi)),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,Sx));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Cx(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??kx,Ix)),f=Math.max(1,Math.min(e.maxBytes??xx,Ax)),p=Math.max(0,Math.min(e.contextBefore??0,mg)),h=Math.max(0,Math.min(e.contextAfter??0,mg)),m=[],y=[],w=[],b=0,v=!1,k=0,A=0,E=(P,$)=>{for(let G of w)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:P,line:$}),G.remaining--,b+=$.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test($)!==l&&m.length<u){let G={cursor:P,line:$};if(p>0&&y.length>0){G.before=y.slice();for(let X of G.before)b+=X.line.length}b+=$.length,m.push(G),h>0&&w.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:P,line:$});y.length>p;)y.shift();let N=m.length>=u&&w.length===0,U=b>=f;return N||U};for(let P=0;P<o.length;P++){if(o[P]!==10)continue;let $=o.subarray(k,P).toString("utf8"),B=r+k;if(k=P+1,A=k,E(B,$)){v=!0;break}}if(!v&&k<o.length&&this.closed){let P=o.subarray(k).toString("utf8"),$=r+k;E($,P)&&(v=!0),A=o.length}let _=Math.min(r+A,this.writeCursor),H={matches:m,truncated:v,nextCursor:_,scannedBytes:A};return i>0&&(H.gap=i),this.closed&&_>=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(()=>gg.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Qi,nO,wg=J(()=>{"use strict";Qi=[{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."}],nO=new Map(Qi.map(n=>[n.verb,n]))});function bg(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Xi(n,e){return Ju(n,e.map(t=>t.modelId))}function Ju(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=bg(n),s=e.filter(i=>bg(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 Gd=J(()=>{"use strict"});function Sg(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=Vu(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0){e.set(l,a);for(let u of Px){if(!vg(c[u]))continue;let f=s.get(l);f===void 0?s.set(l,new Map([[u,c[u]]])):f.set(u,c[u])}if(Array.isArray(c.content)&&c.content.length>0){let u=t.get(l);u?u.push(...c.content):t.set(l,[...c.content])}}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=Vu(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Tx(r,i.outIndex,Rx(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&t.has(u)?Ex(d,t.get(u)??[]):d,p=u===void 0?void 0:s.get(u);if(p!==void 0)for(let[h,m]of p)vg(Vu(f)?.[h])||(f=Mx(f,h,m));r.push(f);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function Vu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Rx(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Tx(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 Ex(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function vg(n){return n==null||typeof n!="object"?!1:Array.isArray(n)?n.length>0:Object.keys(n).length>0}function Mx(n,e,t){let s=n.params??{},r=s.update??{};return{...n,params:{...s,update:{...r,[e]:t}}}}var Px,kg=J(()=>{"use strict";Px=["rawInput","locations"]});function Zi(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received"){i();let l=Yu(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=Qu(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(i(),s.push(Gu(d))):c==="turn_complete"&&i()}return i(),Lx(s.join(`
|
|
18
18
|
`),t)}function Gu(n){let e=$x(n),t=Fx(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function $x(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Fx(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of _x){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Ox(r,200)}`)}return t}function Yu(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 Qu(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Ox(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Lx(n,e){if(n.length<=e)return n;let t=n.split(`
|
|
19
19
|
`);for(;t.length>0;){let s=Ig+t.join(`
|
|
20
20
|
`);if(s.length<=e)return s;t.shift()}return Ig}var Ig,_x,Yd=J(()=>{"use strict";Ig=`[older history truncated]
|
|
21
|
-
`,_x=["file_path","filePath","path","command","pattern","query"]});function Xu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??xg}`),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=ma("Open threads",t.open_threads);o.length>0&&e.push(o);let a=ma("Decisions",t.decisions);a.length>0&&e.push(a);let d=ma("File edit intentions",t.file_edit_intentions);d.length>0&&e.push(d);let c=ma("Unresolved errors",t.unresolved_errors);c.length>0&&e.push(c);let l=ma("Tool state",t.tool_state);l.length>0&&e.push(l);let
|
|
21
|
+
`,_x=["file_path","filePath","path","command","pattern","query"]});function Xu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??xg}`),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=ma("Open threads",t.open_threads);o.length>0&&e.push(o);let a=ma("Decisions",t.decisions);a.length>0&&e.push(a);let d=ma("File edit intentions",t.file_edit_intentions);d.length>0&&e.push(d);let c=ma("Unresolved errors",t.unresolved_errors);c.length>0&&e.push(c);let l=ma("Tool state",t.tool_state);l.length>0&&e.push(l);let u=Ag(t.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=Ag(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??xg}`);let{closedText:s,openText:r,keptCount:i}=Bx(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 ma(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 Ag(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 Bx(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Nx(n),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=t).length,
|
|
24
|
-
`)}function Nx(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 d=a.sessionUpdate;if(d==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Yu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(d==="agent_message_chunk"&&t!==null){let c=Qu(a.content);c.length>0&&(t.agent+=c)}else d==="tool_call"&&t!==null?t.tools.push(Gu(a)):d==="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 xg,Rg=J(()=>{"use strict";Yd();xg="(untitled)"});import*as fs from"fs/promises";async function ga(n,e){let t=
|
|
23
|
+
`)}`}function Ag(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 Bx(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Nx(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 d=a.length>0?Cg(a):"",c=i?Cg([i]):"";return{closedText:d,openText:c,keptCount:o}}function Cg(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 Nx(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 d=a.sessionUpdate;if(d==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Yu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(d==="agent_message_chunk"&&t!==null){let c=Qu(a.content);c.length>0&&(t.agent+=c)}else d==="tool_call"&&t!==null?t.tools.push(Gu(a)):d==="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 xg,Rg=J(()=>{"use strict";Yd();xg="(untitled)"});import*as fs from"fs/promises";async function ga(n,e){let t=L.queueFile(n);if(e.length===0){await fs.unlink(t).catch(()=>{});return}await fs.mkdir(L.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
25
25
|
`)+`
|
|
26
|
-
`;await fs.writeFile(t,s,"utf8")}async function Tg(n){let e=
|
|
27
|
-
`))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Eg(n){let e=
|
|
26
|
+
`;await fs.writeFile(t,s,"utf8")}async function Tg(n){let e=L.queueFile(n),t;try{t=await fs.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 Eg(n){let e=L.queueFile(n);await fs.unlink(e).catch(()=>{})}var Zu=J(()=>{"use strict";we()});import{customAlphabet as $g}from"nanoid";import*as Lg from"fs/promises";function dr(){return`m_${Og()}`}function ut(n){return n.startsWith(Kt)?n.slice(Kt.length):n}function mn(n,e){return n.code=e,n}function Pg(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Wx.has(s)}function zx(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 Kx(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 Jx(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 to(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 ya(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 Vx(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 Gx(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 Yx(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 Qx(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:dr()}}}function Xd(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 Mg(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 Xx(n){let e=Zx(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=eA(n.resolver),t}function Zx(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 eA(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 eo(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function tf(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function tA(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function _g(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 nf(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 Fg,Og,ef,Dx,Hx,Ux,zt,jx,Qd,qx,no,Wx,ps=J(()=>{"use strict";zu();ha();yg();wg();Gd();kg();Rg();Zu();Nt();Fg="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Og=$g(Fg,16),ef=$g(Fg,16),Dx=20,Hx=20,Ux=5,zt="hydra_session_";jx=1e3,Qd=300*1e3,qx=64,no=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 Kd;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??`${zt}${Og()}`,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??jx,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){Gx(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=Mg(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 f=this.transformChain[l];if(t.has(f.name)||!f.intercepts.has(a))continue;let u=`t_${ef()}`,p;try{p=await f.connection.request("hydra-acp/transformer/message",{token:u,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,w=new Set(t),b=r;await new Promise(v=>{let k=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:f.name}),this.runResponseChain(y,new Set([...w,f.name]),m+1,b).then(()=>v()).catch(()=>v()))},Qd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(u,{resolve:()=>v(),timer:k,transformerName:f.name,method:b,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),t.add(f.name)}if(r!=="session/update")return;let d=Yx(o);if(d!==null){this.setAgentAdvertisedCommands(d);return}let c=Vx(o);if(c!==null){this.setAgentAdvertisedModes(c);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 agentPid(){return this.agent.pid}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,d=this.forwardedEnv,c=this.currentModel,l=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let u=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await f({agentId:r,cwd:o,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:u});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Gi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger}),await Vi({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=Xu({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 v=i?`
|
|
29
|
+
`)}`}function nf(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 Fg,Og,ef,Dx,Hx,Ux,Kt,jx,Qd,qx,no,Wx,ps=J(()=>{"use strict";zu();ha();yg();wg();Gd();kg();Rg();Zu();Nt();Fg="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Og=$g(Fg,16),ef=$g(Fg,16),Dx=20,Hx=20,Ux=5,Kt="hydra_session_";jx=1e3,Qd=300*1e3,qx=64,no=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 Kd;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??`${Kt}${Og()}`,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??jx,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){Gx(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=Mg(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_${ef()}`,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(v=>{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(()=>v()).catch(()=>v()))},Qd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>v(),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 d=Yx(o);if(d!==null){this.setAgentAdvertisedCommands(d);return}let c=Vx(o);if(c!==null){this.setAgentAdvertisedModes(c);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 agentPid(){return this.agent.pid}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,d=this.forwardedEnv,c=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,...d?{forwardedEnv:d}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Gi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger}),await Vi({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=Xu({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 v=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:v},_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,d=this.currentModel,c=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 Gi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:d,agentReportedModel:l.initialModel,logger:this.logger}),await Vi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Dx){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 d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate,l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l){if(c==="tool_call")r.add(l);else if(c==="tool_call_update"){let f=d.status;(f==="completed"||f==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}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 mn(new Error("session is closed"),W.SessionNotFound);if(this.clients.has(e.clientId))throw mn(new Error(`client ${e.clientId} is already attached`),W.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:Sg(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Pg(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Xd(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 mn(new Error("client not attached"),W.SessionNotFound);if(this.closing)throw mn(new Error("session is closing; new prompts cannot be accepted"),W.SessionClosing);let r=ar();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(hn((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=eo(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:ar()};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>qx;){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 mn(new Error("client not attached"),W.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=ar(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=ar(),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 mn(new Error("client not attached"),W.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${ef()}`,f;try{f=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??tf(e);if(u==="continue"){f?.payload&&typeof f.payload=="object"&&(o=f.payload),s.add(d.name);continue}if(u==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.forwardRequest(e,h,new Set([...m,d.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:tf(e))))},Qd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:d.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}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 d=this.transformChain[a];if(s.has(d.name)||!d.intercepts.has(o))continue;let c=`t_${ef()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(u){this.logger?.warn(`transformer ${d.name} error on ${o}: ${u.message}`);continue}let f=l?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:l?.payload??tA(e)};if(f==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(d.name);continue}if(f==="processing"){let u=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(m,p,new Set([...h,d.name]),u+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},Qd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:d.name,method:m,envelope:p,chainIdx:u,originatedBy:h,side:"agent-request"})})}s.add(d.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):Qd,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:tf(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(c=>c.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=ar(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((c,l)=>{let f={kind:"user",messageId:o,originator:d,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:c,reject:l},u=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{position:u}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let 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=eo((e??{}).prompt),r=nf(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=to(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=to(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(o.id==="mode"){let a=ya(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=to(o.options);if(d.length>0){let c=ya(o.options),l=c.length>0?c.map(y=>({value:y.id,name:y.name??y.id})):d.map(y=>({value:y.modelId,name:y.name??y.modelId})),f=o.name,u=typeof f=="string"&&f.trim()?f.trim():a,p=o.currentValue,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:h,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let 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(zx(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Kx(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(",")}]`),Jx(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 Qi){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 d=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&d.length>0){let c=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,f={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(f.description=r.description),e.push(f)}if(d.length>0&&t.get(d)===s){let c=r.verb?`${d} ${r.verb}`:d,f={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(f.description=r.description),e.push(f)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,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 Qi)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 d=r.get(a);d===void 0?r.set(a,o):d!==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(Qi.some(f=>f.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(o,t):this.runForkCommand(o);default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=W.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=Qi.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(c.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=W.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 d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(h=>{c=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>c({stopReason:"cancelled",reason:h})});let f,u=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let p=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,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:v},_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,d=this.currentModel,c=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 Gi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:d,agentReportedModel:l.initialModel,logger:this.logger}),await Vi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,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=Dx){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 d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate,l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l){if(c==="tool_call")r.add(l);else if(c==="tool_call_update"){let u=d.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 mn(new Error("session is closed"),W.SessionNotFound);if(this.clients.has(e.clientId))throw mn(new Error(`client ${e.clientId} is already attached`),W.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:Sg(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Pg(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Xd(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 mn(new Error("client not attached"),W.SessionNotFound);if(this.closing)throw mn(new Error("session is closing; new prompts cannot be accepted"),W.SessionClosing);let r=dr();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(hn((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=eo(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:dr()};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>qx;){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 mn(new Error("client not attached"),W.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=dr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=dr(),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 mn(new Error("client not attached"),W.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${ef()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??tf(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(d.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:d.name}),this.forwardRequest(e,h,new Set([...m,d.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:tf(e))))},Qd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:d.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}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 d=this.transformChain[a];if(s.has(d.name)||!d.intercepts.has(o))continue;let c=`t_${ef()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${d.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??tA(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(d.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(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(m,p,new Set([...h,d.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},Qd);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:w,transformerName:d.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(d.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):Qd,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:tf(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(c=>c.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=dr(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((c,l)=>{let u={kind:"user",messageId:o,originator:d,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:c,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=eo((e??{}).prompt),r=nf(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=to(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=to(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(o.id==="mode"){let a=ya(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=to(o.options);if(d.length>0){let c=ya(o.options),l=c.length>0?c.map(y=>({value:y.id,name:y.name??y.id})):d.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,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(zx(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Kx(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(",")}]`),Jx(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 Qi){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 d=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&d.length>0){let c=r.verb?`hydra ${d} ${r.verb}`:`hydra ${d}`,u={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(u.description=r.description),e.push(u)}if(d.length>0&&t.get(d)===s){let c=r.verb?`${d} ${r.verb}`:d,u={name:r.argsHint?`${c} ${r.argsHint}`:c};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 Qi)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 d=r.get(a);d===void 0?r.set(a,o):d!==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(Qi.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=W.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=Qi.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(c.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=W.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 d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(h=>{c=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>c({stopReason:"cancelled",reason:h})});let u,f=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",d),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":"",d=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${d}`});e=`Sessions (${t.length}):
|
|
36
36
|
${s.join(`
|
|
@@ -40,39 +40,39 @@ ${e}
|
|
|
40
40
|
${t.join(`
|
|
41
41
|
`)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
42
42
|
${s}
|
|
43
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let d=o?i.some(l=>l.modelId===o):!0,c=i.map(l=>{let
|
|
43
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let d=o?i.some(l=>l.modelId===o):!0,c=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!d&&o&&c.unshift(`\u25B6 ${o}`),a=c.join(`
|
|
44
44
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
45
45
|
${a}
|
|
46
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Xi(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(
|
|
46
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Xi(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),d=a.length>0?a:i,c=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
47
47
|
${c}.
|
|
48
48
|
${l}:
|
|
49
49
|
${d.join(`
|
|
50
50
|
`)}
|
|
51
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let l=c.id===i?"\u25B6 ":" ",
|
|
51
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let l=c.id===i?"\u25B6 ":" ",u=c.name&&c.name!==c.id?` ${c.name}`:"";return`${l}${c.id}${u}`});!a&&i&&d.unshift(`\u25B6 ${i}`),o=d.join(`
|
|
52
52
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
53
53
|
${o}
|
|
54
54
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(i=>i.id).join(", ");throw mn(new Error(`unknown mode: ${t} (known: ${r})`),W.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
55
55
|
_(no config options advertised yet)_
|
|
56
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let
|
|
57
|
-
${
|
|
56
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>_g(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
57
|
+
${u.join(`
|
|
58
58
|
|
|
59
59
|
`)}
|
|
60
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(l=>l.id===s);if(!o){let l=i.map(
|
|
60
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(l=>l.id===s);if(!o){let l=i.map(u=>u.id).join(`
|
|
61
61
|
`);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
62
62
|
"${s}" is not a known config option.
|
|
63
63
|
Available options:
|
|
64
64
|
${l}
|
|
65
65
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
66
66
|
${_g(o)}
|
|
67
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),d=Ju(r,a),c=r;if(d.kind==="resolved")c=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let l=r.toLowerCase(),
|
|
67
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),d=Ju(r,a),c=r;if(d.kind==="resolved")c=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let l=r.toLowerCase(),u=d.kind==="ambiguous"?d.candidates:a.filter(m=>m.toLowerCase().includes(l)),f=u.length>0?u:a,p=d.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${d.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=d.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
68
68
|
${p}.
|
|
69
69
|
${h}:
|
|
70
|
-
${
|
|
70
|
+
${f.join(`
|
|
71
71
|
`)}
|
|
72
72
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(c!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:c}),this.applyModelChange(c),{stopReason:"end_turn"}):s==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):s==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:c}),{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 mn(new Error("/hydra agent requires an agent id"),W.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw mn(new Error(`already on agent ${r}`),W.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw mn(new Error("agent restart not configured for this session"),W.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),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
|
-
`)),{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 d=await this.findMessageIdBefore(t).catch(()=>{});d&&(i.forkAt=d)}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 mn(new Error("session is closing"),W.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let
|
|
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=Xu({synopsis:e,title:t,tail:s,tailK:Hx,tailFloor:Ux,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 Vd(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??Yi,Yi)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=W.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Eg(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(()=>Lg.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;this.toolCallKind.note(i,o);let a=this.toolCallKind.effective(i,o);if(a===hg&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let f=l.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let u=l.line,p={path:f,toolCallId:i};typeof u=="number"&&(p.line=u),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let d=typeof s.status=="string"?s.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,d);let c={toolCallId:i,status:d};a&&(c.kind=a),s.content!==void 0&&(c.content=s.content),Array.isArray(s.locations)&&(c.locations=s.locations),this.notifyChain("tool.completed",c)}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=!Pg(e,r),o=i?Qx(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.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 mn(new Error("no clients attached to handle permission request"),W.PermissionDenied);let s=this.rewriteForClient(e),r=Mg(s),i=ar(),{toolCall:o,options:a}=s??{};return new Promise((d,c)=>{let l=!1,f=[],u=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===W.MethodNotFound;function w(b){if(l)return;let v=b.connection.request("session/request_permission",s);f.push({client:b}),u++,v.then(k=>{u--,m(()=>{let A=Xx({toolCallId:r,result:k,resolver:b});for(let E of f)E.client.clientId!==b.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:A}).catch(()=>{});d(k)})}).catch(k=>{if(u--,y(k)||(p=k),u===0&&!l){let A=p??mn(new Error("no client handled permission request"),W.PermissionDenied);m(()=>c(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:ar(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{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(()=>ga(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=eo(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 d=t.slice(s.length).trim(),c=d?`/hydra ${r} ${d}`:`/hydra ${r}`;a=await this.handleSlashCommand(c,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)}};Wx=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 so}from"zod";var nA,Bg,Ng=J(()=>{"use strict";nA=so.object({source:so.string(),reason:so.string(),raisedAt:so.number(),payload:so.unknown()}),Bg=so.array(nA)});import{z as Ue}from"zod";function Ug(n){let e=n.trim();if(e.length===0)return;let t=ro(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=ro(e.slice(i,o+1)))}if(t===void 0){let i=qg(e);i!==void 0&&(t=ro(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,Hg))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=wa.safeParse(s.synopsis);i.success&&sA(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function jg(n){let e=n.trim();if(e.length===0)return;let t=ro(e);if(t===void 0){let c=e.indexOf("{"),l=e.lastIndexOf("}");c>=0&&l>c&&(t=ro(e.slice(c,l+1)))}if(t===void 0){let c=qg(e);c!==void 0&&(t=ro(c))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let c=s.title.trim();c.length>0&&(r.title=c.slice(0,Hg))}let i={},o=!1,a=["goal","outcome"];for(let c of a)if(typeof s[c]=="string"){let l=s[c].trim();l.length>0&&(i[c]=l,o=!0)}let d=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let c of d)if(Array.isArray(s[c])){let l=s[c],
|
|
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 d=await this.findMessageIdBefore(t).catch(()=>{});d&&(i.forkAt=d)}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 mn(new Error("session is closing"),W.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=eo(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 c of s)o&&o.speaker===c.speaker?o.text+=c.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:c.speaker,text:c.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
|
|
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=Xu({synopsis:e,title:t,tail:s,tailK:Hx,tailFloor:Ux,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 Vd(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??Yi,Yi)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=W.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Eg(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(()=>Lg.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;this.toolCallKind.note(i,o);let a=this.toolCallKind.effective(i,o);if(a===hg&&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 d=typeof s.status=="string"?s.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,d);let c={toolCallId:i,status:d};a&&(c.kind=a),s.content!==void 0&&(c.content=s.content),Array.isArray(s.locations)&&(c.locations=s.locations),this.notifyChain("tool.completed",c)}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=!Pg(e,r),o=i?Qx(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.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 mn(new Error("no clients attached to handle permission request"),W.PermissionDenied);let s=this.rewriteForClient(e),r=Mg(s),i=dr(),{toolCall:o,options:a}=s??{};return new Promise((d,c)=>{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===W.MethodNotFound;function w(b){if(l)return;let v=b.connection.request("session/request_permission",s);u.push({client:b}),f++,v.then(k=>{f--,m(()=>{let A=Xx({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(()=>{});d(k)})}).catch(k=>{if(f--,y(k)||(p=k),f===0&&!l){let A=p??mn(new Error("no client handled permission request"),W.PermissionDenied);m(()=>c(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:dr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{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(()=>ga(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=eo(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 d=t.slice(s.length).trim(),c=d?`/hydra ${r} ${d}`:`/hydra ${r}`;a=await this.handleSlashCommand(c,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)}};Wx=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 so}from"zod";var nA,Bg,Ng=J(()=>{"use strict";nA=so.object({source:so.string(),reason:so.string(),raisedAt:so.number(),payload:so.unknown()}),Bg=so.array(nA)});import{z as Ue}from"zod";function Ug(n){let e=n.trim();if(e.length===0)return;let t=ro(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=ro(e.slice(i,o+1)))}if(t===void 0){let i=qg(e);i!==void 0&&(t=ro(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,Hg))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=wa.safeParse(s.synopsis);i.success&&sA(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function jg(n){let e=n.trim();if(e.length===0)return;let t=ro(e);if(t===void 0){let c=e.indexOf("{"),l=e.lastIndexOf("}");c>=0&&l>c&&(t=ro(e.slice(c,l+1)))}if(t===void 0){let c=qg(e);c!==void 0&&(t=ro(c))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let c=s.title.trim();c.length>0&&(r.title=c.slice(0,Hg))}let i={},o=!1,a=["goal","outcome"];for(let c of a)if(typeof s[c]=="string"){let l=s[c].trim();l.length>0&&(i[c]=l,o=!0)}let d=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let c of d)if(Array.isArray(s[c])){let l=s[c],u=Ue.array(Ue.string()).safeParse(l);u.success&&l.length>0&&(i[c]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function ro(n){try{return JSON.parse(n)}catch{return}}function qg(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 sA(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 Dg,wa,Hg,sf,rf,Zd=J(()=>{"use strict";Dg=Ue.object({status:Ue.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Ue.number(),iter:Ue.number().int().nonnegative().optional(),attempts:Ue.number().int().nonnegative().optional(),lastError:Ue.string().optional(),worker:Ue.object({upstreamSessionId:Ue.string(),pid:Ue.number().int().nonnegative()}).optional()}),wa=Ue.object({goal:Ue.string().optional(),outcome:Ue.string().optional(),files_touched:Ue.array(Ue.string()).optional(),tools_used:Ue.array(Ue.string()).optional(),rejected_approaches:Ue.array(Ue.string()).optional(),open_threads:Ue.array(Ue.string()).optional(),decisions:Ue.array(Ue.string()).optional(),file_edit_intentions:Ue.array(Ue.string()).optional(),unresolved_errors:Ue.array(Ue.string()).optional(),tool_state:Ue.array(Ue.string()).optional()}),Hg=200,sf=`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,48 +94,48 @@ Use empty arrays/strings where a field doesn't apply.`;rf=`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 io from"fs/promises";import*as
|
|
97
|
+
Use empty arrays/strings where a field doesn't apply.`});import*as io from"fs/promises";import*as CO from"path";import{customAlphabet as rA}from"nanoid";import{z as ne}from"zod";function ba(){return`${aA}${oA()}`}function uA(n){if(!of.test(n))throw new Error(`unsafe session id: ${n}`)}function uf(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 iA,oA,aA,af,df,dA,cf,lf,cA,lA,of,ec,ff=J(()=>{"use strict";we();qr();Ng();Zd();iA="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",oA=rA(iA,16),aA="hydra_lineage_";af=ne.object({name:ne.string(),description:ne.string().optional()}),df=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),dA=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),cf=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),lf=ne.object({name:ne.string(),version:ne.string().optional()}),cA=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),lA=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:wa.optional(),compactionState:Dg.optional(),rollbackBreadcrumb:cA.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:cf.optional(),agentCommands:ne.array(af).optional(),agentModes:ne.array(df).optional(),agentModels:ne.array(dA).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:lf.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Bg.default([]).optional(),extensionState:ne.record(ne.string(),ne.record(ne.string(),ne.unknown())).default({}).optional(),createdAt:ne.string(),updatedAt:ne.string()}),of=/^[A-Za-z0-9_-]+$/;ec=class{async write(e){uA(e.sessionId);let t={version:1,...e};await fn(L.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!of.test(e))return;let t=await Tn(L.sessionFile(e));if(t!==void 0)try{return lA.parse(t)}catch{return}}async delete(e){if(of.test(e)){try{await io.unlink(L.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await io.rmdir(L.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 io.readdir(L.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 pA}from"url";import*as va from"path";import*as nc from"fs";function hA(){try{let n=va.dirname(pA(import.meta.url));for(let e=0;e<8;e+=1){let t=va.join(n,"package.json");if(nc.existsSync(t)){let r=JSON.parse(nc.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=va.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var be,Qr,gn=J(()=>{"use strict";be=hA(),Qr="hydra-acp-cat"});function pf(n){let e=new Map;for(let t of Zg(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 Yg(n){return pf(n).map(e=>e.name)}function hf(n){let e=new Map;for(let t of Zg(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 Qg(n){return hf(n).map(e=>e.path)}function Xg(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Zg(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:Vg(i),paths:new Set},e.set(d,c)):c.toolName=Vg(i);for(let l of Gg(i.rawInput,i.locations))c.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of Gg(i.rawInput,i.locations))a.paths.add(d)}return e}function Vg(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Gg(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)}}}for(let s of Ku(e))t.add(s);return t}var mf=J(()=>{"use strict";ha()});import{promises as Sa}from"fs";import*as kf from"path";async function ka(n){let e;try{e=await Sa.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return FA(e)}function FA(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 Ia(n,e,t=ly){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 Xr(n,e){await Sa.mkdir(kf.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await Sa.writeFile(n,t.length>0?t.join(`
|
|
99
99
|
`)+`
|
|
100
100
|
`:"")}async function uy(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await Sa.mkdir(kf.dirname(n),{recursive:!0}),await Sa.appendFile(n,JSON.stringify(t)+`
|
|
101
|
-
`,{encoding:"utf8"}))}function oc(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function If(n,e,t=ly){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=Ia(r,o,t)))}return r}var ly,ac=J(()=>{"use strict";ly=500});import{z as _e}from"zod";function xa(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 qn(n){return BA.parse(n)}var OA,LA,BA,Zr=J(()=>{"use strict";ff();Zd();OA=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),LA=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:wa.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:cf.optional(),agentCommands:_e.array(af).optional(),agentModes:_e.array(df).optional(),interactive:_e.boolean().optional(),originatingClient:lf.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),BA=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:LA,history:_e.array(OA),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as XA}from"crypto";function $f(n){if(Array.isArray(n))return n.map($f);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=$f(n[t]);return e}return n}function cr(n){let{tui:e,...t}=n,s=JSON.stringify($f(t));return XA("sha256").update(s).digest("hex").slice(0,16)}var Ma=J(()=>{"use strict";et()});function Ff(n){return Math.floor(n/4)}function Py(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=Ff(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 My(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Of=J(()=>{"use strict"});function _a(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var _y=J(()=>{"use strict"});import{posix as l0}from"path";import u0 from"strip-ansi";function St(n){return u0(n).replace(f0,"")}function Te(n){return St(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function gs(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 w0(t);case"agent_thought_chunk":case"agent_thought":return b0(t);case"user_message_chunk":return v0(t);case"prompt_received":return S0(t);case"tool_call":return k0(t,e);case"tool_call_update":return R0(t,e);case"plan":return P0(t);case"current_mode_update":return M0(t);case"current_model_update":return _0(t);case"turn_complete":return $0(t);case"usage_update":return y0(t);case"available_commands_update":return m0(t);case"available_modes_update":return g0(t);case"session_info_update":return h0(t);case"config_option_update":return p0(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function p0(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 h0(n){let e=ft(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 d=a.agentId;if(typeof d=="string"&&(r=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?i=c:c===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 xc(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 m0(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:xc(e)}:null}function g0(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 y0(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 w0(n){let e=$a(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:_a(n)}}function b0(n){let e=typeof n.text=="string"?St(n.text):$a(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:_a(n)}}function v0(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=$a(n.content);return t===null?null:{kind:"user-text",text:t}}function S0(n){let e=F0(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Oy(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function $y(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 Ac(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=$y(r.oldText),o=$y(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 Ly(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:St(t)}function k0(n,e={}){let t=ft(n,"toolCallId")??ft(n,"id");if(!t)return null;let s=ft(n,"title")??ft(n,"name")??ft(n,"label")??"tool call",r=ft(n,"name")??ft(n,"title");if(Oy(r)){let h=Ly(n);if(h!==null){let m=ft(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=Dy(Te(s),n,e),o=ft(n,"status"),a=ft(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Ac(n);c!==null&&(d.editDiff=c);let l=Ny(n);l!==void 0&&(d.detail=l);let f=Lf(n);f!==void 0&&(d.detailFull=f);let u=By(n);u!==void 0&&(d.locations=u);let p=_a(n);return p!==void 0&&(d.workerTaskId=p),d}function By(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 Ny(n){let e=Lf(n);if(e===void 0)return;let t=Te(e),s=n.rawInput;return s&&typeof s.command=="string"?A0(t,Fy):C0(t,Fy)}function Lf(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 St(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 lt(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 lt(Te(s))}}}function x0(n){for(let e of I0)if(n.startsWith(e))return!0;return!1}function Dy(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return lt(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 lt(o)}return x0(n)?lt(`/${n}`):t.cwd&&t.cwd.length>0?lt(l0.resolve(t.cwd,n)):n}function A0(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function C0(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 R0(n,e={}){let t=ft(n,"toolCallId")??ft(n,"id");if(!t)return null;let s=ft(n,"title"),r=s!==void 0?Dy(Te(s),n,e):void 0,i=ft(n,"status"),o=Ac(n),a=Ny(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=ft(n,"name")??s;if(Oy(c)){let h={kind:"exit-plan-mode",toolCallId:t},m=Ly(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 f=Lf(n);f!==void 0&&(l.detailFull=f);let u=By(n);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=T0(n);h!==null&&(l.errorText=h),E0(n,h)&&(l.upstreamInterrupted=!0)}let p=_a(n);return p!==void 0&&(l.workerTaskId=p),l}function T0(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=$a(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 St(s)}return null}function E0(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 P0(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 M0(n){let e=ft(n,"currentModeId")??ft(n,"currentMode")??ft(n,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function _0(n){let e=ft(n,"currentModel")??ft(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 $0(n){let e=ft(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 $a(n){if(typeof n=="string")return St(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?St(e.text):null}function F0(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=$a(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function ft(n,e){let t=n[e];return typeof t=="string"?t:void 0}var f0,Fy,I0,lr=J(()=>{"use strict";we();_y();f0=/[\x00-\x08\x0b-\x1f\x7f]/g;Fy=64;I0=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function co(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=L0(o);if(c.length===0)continue;let l=c;if(d!==void 0){let f=e.get(d)??[],u=[];for(let p of c)f.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(d,[...f,...u]),l=u}for(let f of l)O0(t,f)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function lo(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 O0(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 L0(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,f=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||f===void 0||e.push({path:o,oldText:l,newText:f})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Ac(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Cc=J(()=>{"use strict";lr()});function ys(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var ho=J(()=>{"use strict";Nt()});import{spawn as sR}from"child_process";import{dirname as rR,resolve as iR}from"path";import{fileURLToPath as oR}from"url";import{setTimeout as Tw}from"timers/promises";async function Ew(){let n=await ls();if(n&&En(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function aR(n){let e=await ti(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===cr(n)?"match":"mismatch":"missing"}async function pr(n,e){let t=await aR(n);if(t==="mismatch"){let s=cs();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...
|
|
101
|
+
`,{encoding:"utf8"}))}function oc(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function If(n,e,t=ly){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=Ia(r,o,t)))}return r}var ly,ac=J(()=>{"use strict";ly=500});import{z as _e}from"zod";function xa(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 qn(n){return BA.parse(n)}var OA,LA,BA,Zr=J(()=>{"use strict";ff();Zd();OA=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),LA=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:wa.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:cf.optional(),agentCommands:_e.array(af).optional(),agentModes:_e.array(df).optional(),interactive:_e.boolean().optional(),originatingClient:lf.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),BA=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:LA,history:_e.array(OA),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as XA}from"crypto";function $f(n){if(Array.isArray(n))return n.map($f);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=$f(n[t]);return e}return n}function lr(n){let{tui:e,...t}=n,s=JSON.stringify($f(t));return XA("sha256").update(s).digest("hex").slice(0,16)}var Ma=J(()=>{"use strict";et()});function Ff(n){return Math.floor(n/4)}function Py(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=Ff(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 My(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Of=J(()=>{"use strict"});function _a(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var _y=J(()=>{"use strict"});import{posix as l0}from"path";import u0 from"strip-ansi";function St(n){return u0(n).replace(f0,"")}function Te(n){return St(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function gs(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 w0(t);case"agent_thought_chunk":case"agent_thought":return b0(t);case"user_message_chunk":return v0(t);case"prompt_received":return S0(t);case"tool_call":return k0(t,e);case"tool_call_update":return R0(t,e);case"plan":return P0(t);case"current_mode_update":return M0(t);case"current_model_update":return _0(t);case"turn_complete":return $0(t);case"usage_update":return y0(t);case"available_commands_update":return m0(t);case"available_modes_update":return g0(t);case"session_info_update":return h0(t);case"config_option_update":return p0(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function p0(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 h0(n){let e=pt(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 d=a.agentId;if(typeof d=="string"&&(r=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?i=c:c===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 xc(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 m0(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:xc(e)}:null}function g0(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 y0(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 w0(n){let e=$a(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:_a(n)}}function b0(n){let e=typeof n.text=="string"?St(n.text):$a(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:_a(n)}}function v0(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=$a(n.content);return t===null?null:{kind:"user-text",text:t}}function S0(n){let e=F0(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Oy(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function $y(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 Ac(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=$y(r.oldText),o=$y(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 Ly(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:St(t)}function k0(n,e={}){let t=pt(n,"toolCallId")??pt(n,"id");if(!t)return null;let s=pt(n,"title")??pt(n,"name")??pt(n,"label")??"tool call",r=pt(n,"name")??pt(n,"title");if(Oy(r)){let h=Ly(n);if(h!==null){let m=pt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=Dy(Te(s),n,e),o=pt(n,"status"),a=pt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Ac(n);c!==null&&(d.editDiff=c);let l=Ny(n);l!==void 0&&(d.detail=l);let u=Lf(n);u!==void 0&&(d.detailFull=u);let f=By(n);f!==void 0&&(d.locations=f);let p=_a(n);return p!==void 0&&(d.workerTaskId=p),d}function By(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 Ny(n){let e=Lf(n);if(e===void 0)return;let t=Te(e),s=n.rawInput;return s&&typeof s.command=="string"?A0(t,Fy):C0(t,Fy)}function Lf(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 St(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 lt(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 lt(Te(s))}}}function x0(n){for(let e of I0)if(n.startsWith(e))return!0;return!1}function Dy(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return lt(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 lt(o)}return x0(n)?lt(`/${n}`):t.cwd&&t.cwd.length>0?lt(l0.resolve(t.cwd,n)):n}function A0(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function C0(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 R0(n,e={}){let t=pt(n,"toolCallId")??pt(n,"id");if(!t)return null;let s=pt(n,"title"),r=s!==void 0?Dy(Te(s),n,e):void 0,i=pt(n,"status"),o=Ac(n),a=Ny(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=pt(n,"name")??s;if(Oy(c)){let h={kind:"exit-plan-mode",toolCallId:t},m=Ly(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=Lf(n);u!==void 0&&(l.detailFull=u);let f=By(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=T0(n);h!==null&&(l.errorText=h),E0(n,h)&&(l.upstreamInterrupted=!0)}let p=_a(n);return p!==void 0&&(l.workerTaskId=p),l}function T0(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=$a(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 St(s)}return null}function E0(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 P0(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 M0(n){let e=pt(n,"currentModeId")??pt(n,"currentMode")??pt(n,"mode");return e?{kind:"mode-changed",mode:Te(e)}:null}function _0(n){let e=pt(n,"currentModel")??pt(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 $0(n){let e=pt(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 $a(n){if(typeof n=="string")return St(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?St(e.text):null}function F0(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=$a(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function pt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var f0,Fy,I0,ur=J(()=>{"use strict";we();_y();f0=/[\x00-\x08\x0b-\x1f\x7f]/g;Fy=64;I0=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function co(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=L0(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)O0(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function lo(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 O0(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 L0(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Ac(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Cc=J(()=>{"use strict";ur()});function ys(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var ho=J(()=>{"use strict";Nt()});import{spawn as sR}from"child_process";import{dirname as rR,resolve as iR}from"path";import{fileURLToPath as oR}from"url";import{setTimeout as Tw}from"timers/promises";async function Ew(){let n=await ls();if(n&&En(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function aR(n){let e=await ti(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===lr(n)?"match":"mismatch":"missing"}async function hr(n,e){let t=await aR(n);if(t==="mismatch"){let s=cs();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
102
|
`),Uc(),await jc(n)),e!==void 0){let s=await ls();if(s&&En(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 cR(`${e.baseUrl}/v1/health`)}}async function Hc(n){let e=await Ew();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function ti(n,e=1e3){let t=await Ew();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 Uc(){let n=rR(oR(import.meta.url)),e=iR(n,"./daemon.js");sR(process.execPath,[e],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function dR(n,e=500){try{return(await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}})).ok}catch{return!1}}async function cR(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await dR(n))return;await Tw(150)}throw new Error(`hydra-acp daemon did not answer ${n} within ${e}ms`)}async function jc(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Hc(n))return;await Tw(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var ni=J(()=>{"use strict";aa();Ma();Ui()});import*as Pw from"fs";import*as yo from"fs/promises";async function wo(n,e,t){let s=uR(e),r;try{r=await yo.stat(n)}catch(d){if(d.code==="ENOENT"){process.stderr.write(`${t} (${n})
|
|
103
103
|
`),process.exit(1);return}throw d}let i=await lR(n,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${n} --
|
|
104
|
-
`);let o=!1,a=Pw.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let d=await yo.stat(n);if(d.size<=i){d.size<i&&(i=d.size);return}let c=await yo.open(n,"r");try{let l=Buffer.alloc(d.size-i);await c.read(l,0,l.length,i),process.stdout.write(l),i=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function lR(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await yo.open(n,"r");try{let i=e,o="",a=0;for(;i>0&&a<=t;){let l=Math.min(s,i);i-=l;let
|
|
104
|
+
`);let o=!1,a=Pw.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let d=await yo.stat(n);if(d.size<=i){d.size<i&&(i=d.size);return}let c=await yo.open(n,"r");try{let l=Buffer.alloc(d.size-i);await c.read(l,0,l.length,i),process.stdout.write(l),i=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function lR(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await yo.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 c=o.split(`
|
|
105
105
|
`).slice(-t-1);process.stdout.write(c.join(`
|
|
106
106
|
`)),o.endsWith(`
|
|
107
107
|
`)||process.stdout.write(`
|
|
108
108
|
`)}finally{await r.close()}return e}function qc(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 uR(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 La=J(()=>{"use strict"});import{WebSocket as hR}from"ws";async function si(n,e,t=mR){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=ca(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 hR(n,e,s),a=Date.now(),d=setTimeout(()=>{o.off("open",c),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new zf(n,Date.now()-a))},t),c=()=>{clearTimeout(d),o.off("error",l),r(o)},l=
|
|
111
|
-
`),process.exit(1)}let d=null;if(a.status!==204)try{d=await a.json()}catch{d=null}let c=e.expectStatus,l=c===void 0?a.ok:Array.isArray(c)?c.includes(a.status):c===a.status;if(c!==void 0&&!l){let
|
|
110
|
+
`),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var La=J(()=>{"use strict"});import{WebSocket as hR}from"ws";async function si(n,e,t=mR){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=ca(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 hR(n,e,s),a=Date.now(),d=setTimeout(()=>{o.off("open",c),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new zf(n,Date.now()-a))},t),c=()=>{clearTimeout(d),o.off("error",l),r(o)},l=u=>{clearTimeout(d),o.off("open",c),i(u)};o.once("open",c),o.once("error",l)})}var mR,zf,Ba=J(()=>{"use strict";la();mR=1e4,zf=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 Wc from"fs/promises";function gR(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function vo(){let n=await ls();if(n&&En(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await xe();return Bw(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Bw(n,e,t){return`${t?"https":"http"}://${gR(n)}:${e}`}async function Le(n,e={}){let t=await jr(),s=await vo(),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
|
+
`),process.exit(1)}let d=null;if(a.status!==204)try{d=await a.json()}catch{d=null}let c=e.expectStatus,l=c===void 0?a.ok:Array.isArray(c)?c.includes(a.status):c===a.status;if(c!==void 0&&!l){let u=`HTTP ${a.status}`;if(d&&typeof d=="object"&&"error"in d){let p=d.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:d}}function So(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 zc(n,e){let t=e!=="agent",s=t?[]:void 0,r=[],i={},o=!0,a=0;for(;a<n.length;){let d=n[a];if(d==="--command"){let c=n[a+1];c===void 0&&(process.stderr.write(`--command requires a value
|
|
113
113
|
`),process.exit(2)),s=t?yR(c):c,a+=2;continue}if(d==="--args"){let c=n[a+1];c===void 0&&(process.stderr.write(`--args requires a value
|
|
114
114
|
`),process.exit(2)),r=c.split(",").filter(l=>l.length>0),a+=2;continue}if(d==="--env"){let c=n[a+1];c===void 0&&(process.stderr.write(`--env requires KEY=VALUE
|
|
115
115
|
`),process.exit(2));let l=c.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${c}': expected KEY=VALUE
|
|
116
116
|
`),process.exit(2)),i[c.slice(0,l)]=c.slice(l+1),a+=2;continue}if(d==="--disabled"&&e!=="agent"){o=!1,a+=1;continue}process.stderr.write(`Unknown flag: ${d}
|
|
117
|
-
`),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function yR(n){return n.split(/\s+/).filter(e=>e.length>0)}async function ko(){let n=await Wc.readFile(
|
|
118
|
-
`,{encoding:"utf8",mode:384})}var
|
|
119
|
-
`)});let d=new LR({write(l,f
|
|
120
|
-
`)});let c=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:d,flush:async()=>{a.writable&&await new Promise(l=>{d.end(()=>l())}),await c}}}function BR(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 Xf=J(()=>{"use strict"});import NR from"chalk";import{highlight as DR,supportsLanguage as Xc}from"cli-highlight";import el from"string-width";function ep(n){let e=n.indexOf("#"),t=e===-1?n:n.slice(0,e),s=e===-1?"":n.slice(e),r=t.split("/").map(i=>encodeURIComponent(i)).join("/");return`file://${HR}${r}${s}`}function
|
|
121
|
-
`&&!/[A-Za-z0-9]/.test(h)){let w=-1;for(let b=
|
|
122
|
-
`)break;if(v!=="*"||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>
|
|
123
|
-
`&&m!=="_"&&!/[A-Za-z0-9_]/.test(h)){let w=-1;for(let b=
|
|
124
|
-
`)break;if(v!=="_")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>
|
|
125
|
-
`),l=!1,
|
|
117
|
+
`),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function yR(n){return n.split(/\s+/).filter(e=>e.length>0)}async function ko(){let n=await Wc.readFile(L.config(),"utf8");return JSON.parse(n)}async function Kf(n){await Wc.writeFile(L.config(),JSON.stringify(n,null,2)+`
|
|
118
|
+
`,{encoding:"utf8",mode:384})}var mr=J(()=>{"use strict";et();Ms();we();Ui();Ba()});async function wn(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(d){throw o?new Jf(n,t):d}finally{clearTimeout(a)}}async function Wn(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 wn(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 Nw(n,e=fetch){let t=await wn(`${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(d=>d.installed==="yes"):[],i=0,o=0,a=0;for(let d of r)try{let c=await wn(`${n.baseUrl}/v1/agents/${d.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},3e4,e);if(!c.ok)continue;let l=await c.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function ri(n,e=fetch){let t=await wn(`${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 Kc(n,e,t={},s=fetch){let r=await wn(`${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 bs(n,e,t=fetch){let s=await wn(`${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 Dw(n,e,t,s=fetch){let r=await wn(`${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 Hw(n,e,t,s=fetch){let r=await wn(`${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 Uw(n,e,t=fetch){let s=await wn(`${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 jw(n,e,t={},s=fetch){let r={q:e};t.sessionIds&&t.sessionIds.length>0&&(r.sessionIds=t.sessionIds);let i=await wn(`${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 qw(n,e,t=fetch){let s=await wn(`${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 Jc(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 Jf,Na=J(()=>{"use strict";Jf=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 Vf(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function Ww(n,e){let t=n??"?",s=Vf(e);return s?`${t}${wR}${s}`:t}function zw(n){return n??"?"}function Kw(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:Gf(e,t)}function Gf(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var wR,Yf=J(()=>{"use strict";wR="\u2022"});function Jw(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(!Gc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Gc.join(", ")})`);if(t.has(r))throw new Error(`--columns: duplicate column "${r}"`);t.add(r),s.push(r)}return s}function Ao(n,e=Date.now()){return{session:ut(n.sessionId),upstream:SR(n.upstreamSessionId,n.importedFromMachine),host:n.importedFromMachine??"-",state:kR(n.status,n.busy,n.awaitingInput,vR(n.compactionState),n.forkSynthesisState),agent:zw(n.agentId),model:Vf(n.currentModel)??"-",age:IR(n.updatedAt,e),title:n.title??"-",cwd:lt(n.cwd),cost:Kw(n.currentUsage)}}function vR(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 SR(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function kR(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 Co(n,e={}){let t=e.columns??Io,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]=xR(xo[r],n.map(i=>i[r]));return s}function IR(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 d=Math.floor(a/7);if(d<9)return`${d}w`;let c=Math.floor(a/30);return c<12?`${c}mo`:`${Math.floor(a/365)}y`}function xR(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function gr(n,e,t,s={}){let r=s.columns??Io,i=s.cwdMaxWidth??bR,o=b=>b==="age"?n[b].padStart(e[b]):n[b].padEnd(e[b]);if(t===void 0)return r.map((v,k)=>k===r.length-1?n[v]:o(v)).join(Vc);let a=r.map((b,v)=>({col:b,i:v})).filter(({col:b})=>Qf.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=r.map(o).join(Vc);return b.length>t?b.slice(0,t):b}let c=r.filter(b=>!Qf.has(b)).reduce((b,v)=>b+e[v],0),l=Math.max(0,r.length-1),u=t-c-l*Vc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:v}of a){if(v===d)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],A=Math.min(k,Math.max(0,p-1));f.set(v,A),p=Math.max(0,p-A)}f.set(d,Math.max(0,p));let h=r.length-1,m=(b,v,k)=>{if(b==="cwd")return Da(n[b],v).padEnd(v);let A=AR(n[b],v);return k?A:A.padEnd(v)},w=r.map((b,v)=>Qf.has(b)?m(b,f.get(v)??0,v===h):o(b)).join(Vc);return w.length>t?w.slice(0,t):w}function AR(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function Da(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 Gc,Io,Qf,xo,Vc,bR,Yc=J(()=>{"use strict";Yf();we();ps();Gc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Io=["session","state","age","cwd","title","agent","cost"],Qf=new Set(["cwd","title"]),xo={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Vc=" ",bR=32});import{spawn as OR}from"child_process";import{Writable as LR}from"stream";function Qc(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=BR(t);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=n.spawn??OR,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 d=new LR({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()}});d.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
|
|
120
|
+
`)});let c=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:d,flush:async()=>{a.writable&&await new Promise(l=>{d.end(()=>l())}),await c}}}function BR(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 Xf=J(()=>{"use strict"});import NR from"chalk";import{highlight as DR,supportsLanguage as Xc}from"cli-highlight";import el from"string-width";function ep(n){let e=n.indexOf("#"),t=e===-1?n:n.slice(0,e),s=e===-1?"":n.slice(e),r=t.split("/").map(i=>encodeURIComponent(i)).join("/");return`file://${HR}${r}${s}`}function wr(n,e={}){switch(n.kind){case"user-text":{let t=Zf(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 Zf(n.text," ","agent");case"agent-thought":return Zf(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return dT(n,e.maxPlanItems??oT);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 tp(n,e){return yr(n,e).styled}function yr(n,e){let t=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.italicReset??"^:",o=e?.linkOpen??"^C^_",a=e?.linkReset??"^:",d="",c=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==="\\"){d+=h,c+=1,f+=2;continue}}if(p==="^"){d+="^^",c+=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=yr(m,e),w=c;d+=`^+${y.styled}${r}`;for(let b of y.links)u.push({start:w+b.start,end:w+b.end,url:b.url});c+=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
|
+
`&&!/[A-Za-z0-9]/.test(h)){let w=-1;for(let b=f+1;b<n.length;b++){let v=n[b];if(v===`
|
|
122
|
+
`)break;if(v!=="*"||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),v=yr(b,e),k=c;d+=`^_${v.styled}${i}`;for(let A of v.links)u.push({start:k+A.start,end:k+A.end,url:A.url});c+=v.cleanLength,v.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
|
+
`&&m!=="_"&&!/[A-Za-z0-9_]/.test(h)){let w=-1;for(let b=f+1;b<n.length;b++){let v=n[b];if(v===`
|
|
124
|
+
`)break;if(v!=="_")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),v=yr(b,e),k=c;d+=`^_${v.styled}${i}`;for(let A of v.links)u.push({start:k+A.start,end:k+A.end,url:A.url});c+=v.cleanLength,v.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,"^^");d+=`${t}${y}${s}`,c+=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=yr(y,e),v=c;d+=`${o}${b.styled}${a}`;for(let k of b.links)u.push({start:v+k.start,end:v+k.end,url:k.url});c+=b.cleanLength,u.push({start:v,end:c,url:w}),f=m+1;continue}}}d+=p,c+=1,f+=1}return{styled:d,links:u,cleanLength:c,ansi:l}}function UR(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 ob(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 ab(n,e){let{proseStyle:t,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,d=[],c=n.replace(/^\s+/,"").split(`
|
|
125
|
+
`),l=!1,u="",f=[],p=i!==" ",h=(w,b,v=" ",k,A,E)=>{let _={prefix:v,body:w,bodyStyle:b};r!==void 0&&(_.prefixStyle=r),k&&k.length>0&&(_.links=k),A&&(_.ansi=!0),E!==void 0&&E>0&&(_.hangingIndent=E),d.push(_)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let w=cb(u,f);for(let b of w){let v={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(v.prefixStyle=r),b.ansi&&(v.ansi=!0),d.push(v)}}else for(let w of f)h(w.replace(/\^/g,"^^"),t);f=[],u=""}};for(let w=0;w<c.length;w++){let b=c[w],v=b.match(/^\s*```\s*(\w*)\s*$/);if(v){l?(y(),l=!1):(l=!0,u=v[1]??"");continue}if(l){f.push(b);continue}let k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let $=k[1].length,B=k[2]??"",N=s?$===1?"heading-1":$===2?"heading-2":"heading-3":t,U=s?ob(N):o;h(tp(B,U),N,m());continue}let A=c[w+1];if(b.includes("|")&&A!==void 0&&jR(A)&&Ha(b).length===Ha(A).length){let $=Ha(b),B=[],N=w+2;for(;N<c.length&&c[N].includes("|");)B.push(Ha(c[N])),N++;let U=GR($,B,a);for(let G of U)r!==void 0&&(G.prefixStyle=r),d.push(G);w=N-1;continue}let E=b.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let $=E[1]??"",B=E[2]??"",N=yr(B,o),U=$.length+2,G=N.links.map(X=>({start:X.start+U,end:X.end+U,url:X.url}));h(`${$}\u2022 ${N.styled}`,t,m(),G,N.ansi,$.length+2);continue}let _=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(_){let $=_[1]??"",B=_[2]??"",N=_[3]??"",U=yr(N,o),G=$.length+B.length+2,X=U.links.map(Y=>({start:Y.start+G,end:Y.end+G,url:Y.url}));h(`${$}${B}. ${U.styled}`,t,m(),X,U.ansi,$.length+B.length+2);continue}let H=b.trim()==="",P=yr(b,o);h(P.styled,t,H?" ":m(),P.links,P.ansi)}for(l&&y();d.length>0&&d[d.length-1].body==="";)d.pop();return d}function br(n,e){return ab(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Ro(n){return ab(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Ha(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 jR(n){if(!n.includes("|"))return!1;let e=Ha(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Zc(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 el(e)}function zR(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:el(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]:"",d=n[i+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="*"&&!/[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]:"",d=n[i+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="_"&&!/[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:Zc(r)}),t=i}return e}function KR(n,e){let t=[],s="",r=0;for(let i of n){let o=el(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 JR(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 d=KR(o.text,e);for(let l=0;l<d.length-1;l++)t.push(d[l]);let c=d[d.length-1]??"";s=c,r=el(c)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||t.length===0)&&i(),t}function VR(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,db)),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),d=a.reduce((l,u)=>l+u.slack,0);if(d===0)return r;for(let l of a){let u=Math.floor(o*l.slack/d);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let c=e-i;for(;c>0;){let l=-1,u=0;for(let f=0;f<t;f++){let p=n[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,c--}return r}function GR(n,e,t){let s=n.length,r=new Array(s).fill(0);for(let c=0;c<s;c++)r[c]=Zc(n[c]??"");for(let c of e)for(let l=0;l<s;l++){let u=c[l]??"",f=Zc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(t!==void 0){let c=Math.max(s*db,t-qR-(s-1)*WR);i=VR(r,c)}let o=(c,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=c[m]??"",w=i[m],b=JR(zR(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]??"",v=i[w],k=Zc(b),A=tp(b,u);y.push(A+" ".repeat(Math.max(0,v-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(n,"heading-3",ob("heading-3")));let d=[];for(let c=0;c<s;c++)d.push("\u2500".repeat(i[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let c of e)a.push(...o(c,"agent"));return a}function cb(n,e){if(n.length===0||!Xc(n))return e.map(a=>({body:a,ansi:!1}));let t=e.join(`
|
|
126
126
|
`),s=`${n}\0${t}`,r=ii.get(s),i;if(r!==void 0)ii.delete(s),ii.set(s,r),i=r;else{let a;try{a=DR(t,{language:n,theme:YR,ignoreIllegals:!0})}catch{return e.map(d=>({body:d,ansi:!1}))}if(i=a.replace(/\x1b\[39m/g,"\x1B[37m"),ii.size>=QR){let d=ii.keys().next().value;d!==void 0&&ii.delete(d)}ii.set(s,i)}let o=i.split(`
|
|
127
127
|
`);return o.length!==e.length?e.map(a=>({body:a,ansi:!1})):o.map((a,d)=>({body:a,ansi:a!==e[d]}))}function ZR(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Xc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Xc("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let s=e.slice(t),r=XR[s];return r&&Xc(r)?r:""}function Zf(n,e,t,s,r,i){let o=n.replace(/^\s+/,"").split(`
|
|
128
128
|
`),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let d of o){let c={prefix:e,prefixStyle:s??t,body:d,bodyStyle:t};i&&(c.fillRow=!0),a.push(c)}return a}function eT(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function vs(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 lb(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 Ua(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=[],d=null;if(n.detail){let
|
|
131
|
+
`),r=!0),{text:s,truncated:r}}function Ua(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=[],d=null;if(n.detail){let f=n.detail,p=o.toLowerCase(),h=f.toLowerCase();(h.startsWith(`${p} `)||h.startsWith(`${p} `))&&(f=f.slice(o.length).trimStart());let m=o.includes(f)||n.detailFull!==void 0&&o.includes(n.detailFull);f.length>0&&!m&&(o=`${o} \xB7 ${f}`,d=f)}if(n.startedAt!==void 0){let f=n.endedAt??e;o=`${o} \xB7 ${vs(f-n.startedAt)}`}let c=n.locations?.[0]?.path??n.detailFull;if(c!==void 0&&c.length>0&&(c.startsWith("/")||c.startsWith("~")||n.locations?.[0]!==void 0)){let p=d!==null&&(d.startsWith("\u2026")||d.startsWith("/")||d.startsWith("~")),h=[n.detailFull,c,lt(c),p?d:null].filter(y=>y!=null&&y.length>0).sort((y,w)=>w.length-y.length),m=(y,w)=>{let b=y===0?"":o[y-1],v=o[y+w]??"";return!rb.test(b)&&!rb.test(v)};for(let y of h){let w=o.indexOf(y);for(;w!==-1&&!m(w,y.length);)w=o.indexOf(y,w+1);if(w!==-1){let b=n.locations?.[0]?.line;a.push({start:w,end:w+y.length,url:b===void 0?c:`${c}#L${b}`});break}}}let l={prefix:` ${sT(n.status)} `,prefixStyle:rT(n.status),body:o,bodyStyle:cT(n.status)};a.length>0&&(l.links=a);let u=[l];return n.status==="failed"&&n.errorText&&u.push({prefix:" ",body:Te(n.errorText),bodyStyle:"tool-status-fail"}),u}function ub(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=ZR(r);if(i.length>0){let o=cb(i,s.map(a=>Te(a)));for(let a of o){let d={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(d.ansi=!0),e.push(d)}}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 pb(n){fb=n>=0?n:0}function np(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let c=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${eT(c)})`}else{let c=sp(n),l=[];c.added>0&&l.push(`+${c.added}`),c.removed>0&&l.push(`-${c.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=c=>{let l=Te(lt(n.path)),
|
|
133
|
+
`),r=n.locations?.[0]?.path??n.detailFull??n.detail,i=ZR(r);if(i.length>0){let o=cb(i,s.map(a=>Te(a)));for(let a of o){let d={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(d.ansi=!0),e.push(d)}}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 pb(n){fb=n>=0?n:0}function np(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let c=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${eT(c)})`}else{let c=sp(n),l=[];c.added>0&&l.push(`+${c.added}`),c.removed>0&&l.push(`-${c.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=c=>{let l=Te(lt(n.path)),f=`${c?"\u25BE":"\u25B8"} Edited `,p={prefix:" ",body:`${f}${l}${i}`,bodyStyle:"dim"};return n.path!==void 0&&(p.links=[{start:f.length,end:f.length+l.length,url:n.path}]),p};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=rp(n,{maxLines:1/0});if(a.length===0)return n.path&&s.push(o(!1)),s;n.path&&s.push(o(!0));let d="```diff\n"+a+"\n```";return s.push(...br(d)),s.length>0&&s.unshift({body:""}),s}function hb(n){let e=St(n.oldText).split(`
|
|
134
134
|
`),t=St(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 sp(n){let{oldLines:e,newLines:t}=hb(n),s=0,r=0;for(let i of mb(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function ib(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function rp(n,e={}){let t=e.maxLines??tT,s=e.contextLines??fb,{oldLines:r,newLines:i}=hb(n),o=mb(r,i),a=[];if(Number.isFinite(s)){if(!o.some(
|
|
136
|
-
`)}function mb(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(...nT(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 nT(n,e){let t=n.length,s=e.length;if(t===0||s===0){let d=[];for(let c of n)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let d=t-1;d>=0;d--)for(let c=s-1;c>=0;c--)n[d]===e[c]?r[d][c]=r[d+1][c+1]+1:r[d][c]=Math.max(r[d+1][c],r[d][c+1]);let i=[],o=0,a=0;for(;o<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 ip(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function sT(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 rT(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 gb(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...
|
|
137
|
-
`),process.exit(2));let t=e.fold===!0?"?fold=true":"",s=await Le(`/v1/sessions/${encodeURIComponent(n)}/diff${t}`),r;if(s.ok)r=s.body;else if(s.status===404){let c=(await Le(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,l;try{l=qn(c)}catch(
|
|
138
|
-
`),process.exit(1)}let
|
|
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 sp(n){let{oldLines:e,newLines:t}=hb(n),s=0,r=0;for(let i of mb(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function ib(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function rp(n,e={}){let t=e.maxLines??tT,s=e.contextLines??fb,{oldLines:r,newLines:i}=hb(n),o=mb(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(ib(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let c of o)a.push(ib(c));let d=[];for(let c=0;c<a.length;c++){if(d.length>=t-1&&c<a.length-1){let u=a.length-c;d.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}d.push(a[c])}return d.join(`
|
|
136
|
+
`)}function mb(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(...nT(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 nT(n,e){let t=n.length,s=e.length;if(t===0||s===0){let d=[];for(let c of n)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let d=t-1;d>=0;d--)for(let c=s-1;c>=0;c--)n[d]===e[c]?r[d][c]=r[d+1][c+1]+1:r[d][c]=Math.max(r[d+1][c],r[d][c+1]);let i=[],o=0,a=0;for(;o<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 ip(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function sT(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 rT(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 gb(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...br(n.plan));let t=n.status;if(t!==void 0){let s=iT(t);s!==null&&e.push(s)}return e}function iT(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 aT(n,e){let t=n.length;if(e<=0||t<=e)return{start:0,end:t};let s=n.findIndex(c=>(c.status??"pending")==="in_progress"),r=n.findIndex(c=>(c.status??"pending")==="pending"),i=s>=0?s:r>=0?r:t-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),d=Math.min(t,a+e);return d-a<e&&(a=Math.max(0,d-e)),{start:a,end:d}}function dT(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:d,end:c}=aT(n.entries,e),l=c-d<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=d;p<c;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*$/,""),v=tp(b,UR(w));f.push({prefix:" ",body:`${y} ${v}`,bodyStyle:w})}return f}function cT(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 rb,HR,db,qR,WR,ht,YR,QR,ii,XR,tT,fb,oT,oi=J(()=>{"use strict";pa();we();ur();rb=/[A-Za-z0-9_./\-~+@]/,HR=ar();db=6,qR=2,WR=3;ht=new NR.Instance({level:3}),YR={keyword:ht.blueBright,built_in:ht.cyan,type:ht.cyanBright,literal:ht.blue,number:ht.greenBright,string:ht.yellow,regexp:ht.red,comment:ht.gray,function:ht.yellow,title:ht.yellow,class:ht.yellowBright,attr:ht.cyan,attribute:ht.cyan,variable:ht.white,params:ht.white,meta:ht.magenta,symbol:ht.magenta,addition:ht.greenBright,deletion:ht.redBright,section:ht.cyan,tag:ht.cyan,name:ht.cyanBright},QR=512,ii=new Map;XR={".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"};tT=40,fb=Number.POSITIVE_INFINITY;oT=5});import{highlight as lT,supportsLanguage as uT}from"cli-highlight";async function wb(n,e={}){n||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
|
|
137
|
+
`),process.exit(2));let t=e.fold===!0?"?fold=true":"",s=await Le(`/v1/sessions/${encodeURIComponent(n)}/diff${t}`),r;if(s.ok)r=s.body;else if(s.status===404){let c=(await Le(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,l;try{l=qn(c)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
|
|
138
|
+
`),process.exit(1)}let u=co(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:lo(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=Qc({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(op(r,a)),await i.flush()}function op(n,e){if(n.length===0)return`No file edits found in this session.
|
|
141
141
|
`;let t=[],s=[...n].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=hT(r,e);i!==null&&t.push(i)}return t.length===0?`No file edits found in this session.
|
|
@@ -144,14 +144,14 @@ Use empty arrays/strings where a field doesn't apply.`});import*as io from"fs/pr
|
|
|
144
144
|
`)+`
|
|
145
145
|
|
|
146
146
|
`;return!e||!uT("diff")?i:lT(i,{language:"diff"})}function yb(n){if(n.length===0)return 0;let e=n.split(`
|
|
147
|
-
`);return e[e.length-1]===""&&e.pop(),e.length}var ap=J(()=>{"use strict";
|
|
148
|
-
`),process.exit(2));let t=await Le(`/v1/sessions/${encodeURIComponent(n)}`,{expectStatus:[200,404]}),s=t.status===200?t.body.status:void 0,i=(await Le(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,o;try{o=qn(i)}catch(
|
|
149
|
-
`),process.exit(1)}let a=lp(o,s??"cold"),d=e.diff===!0,c=null;if(d){let
|
|
150
|
-
`);return}let l=process.stdout.isTTY===!0,
|
|
151
|
-
`),
|
|
147
|
+
`);return e[e.length-1]===""&&e.pop(),e.length}var ap=J(()=>{"use strict";mr();Zr();Cc();oi();Xf()});async function bb(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
|
|
148
|
+
`),process.exit(2));let t=await Le(`/v1/sessions/${encodeURIComponent(n)}`,{expectStatus:[200,404]}),s=t.status===200?t.body.status:void 0,i=(await Le(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,o;try{o=qn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
|
|
149
|
+
`),process.exit(1)}let a=lp(o,s??"cold"),d=e.diff===!0,c=null;if(d){let f=co(o.history);c=e.fold===!0?f.map(p=>({...p,hunks:lo(p.hunks)})):f}if(e.json){let f={...a};c!==null&&(f.diff=c),process.stdout.write(JSON.stringify(f,null,2)+`
|
|
150
|
+
`);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(d){let f=Qc({disabled:e.noPager===!0});f.stream.write(tl(a,e.verbose===!0)),f.stream.write(`
|
|
151
|
+
`),f.stream.write(op(c??[],u)),await f.flush();return}process.stdout.write(tl(a,e.verbose===!0))}function lp(n,e){let t=n.session,s=n.history,r=Xg(s),i=pf(s),o=hf(s),a=t.currentUsage,d=Date.parse(t.createdAt),c=Date.parse(t.updatedAt),l=Number.isFinite(d)&&Number.isFinite(c)?c-d: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 tl(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:")}${gT(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=" ",d=c=>c.padEnd(22);if(n.synopsis.goal&&t.push(`${a}${d("Goal:")}${n.synopsis.goal}`),n.synopsis.outcome&&t.push(`${a}${d("Outcome:")}${n.synopsis.outcome}`),n.synopsis.rejected_approaches&&n.synopsis.rejected_approaches.length>0){t.push(`${a}${d("Rejected approaches:")}`);for(let c of n.synopsis.rejected_approaches)t.push(`${a} - ${c}`)}if(n.synopsis.open_threads&&n.synopsis.open_threads.length>0){t.push(`${a}${d("Open threads:")}`);for(let c of n.synopsis.open_threads)t.push(`${a} - ${c}`)}if(n.synopsis.files_touched&&n.synopsis.files_touched.length>0){t.push(`${a}${d("Files touched:")}`);for(let c of n.synopsis.files_touched)t.push(`${a} - ${c}`)}if(n.synopsis.tools_used&&n.synopsis.tools_used.length>0){t.push(`${a}${d("Tools used:")}`);for(let c of n.synopsis.tools_used)t.push(`${a} - ${c}`)}}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 d=e?n.tools:n.tools.slice(0,dp),c=Math.max(...d.map(l=>l.name.length),4);for(let l of d)t.push(` ${l.name.padEnd(c)} ${l.count}`);!e&&n.tools.length>dp&&t.push(` ... ${n.tools.length-dp} more (use --verbose to see all)`)}let o=e?n.files:n.files.map(a=>{let d=a.byTool.filter(l=>mT.has(l.name)),c=d.reduce((l,u)=>l+u.count,0);return{path:a.path,count:c,byTool:d}}).filter(a=>a.count>0);if(o.length>0){t.push("");let a=e?"Files touched":"Files edited";t.push(`${a} (${o.length}):`);let d=e?o:o.slice(0,cp),c=Math.max(...d.map(l=>l.path.length),4);for(let l of d)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");t.push(` ${l.path.padEnd(c)} ${l.count} (${u})`)}else t.push(` ${l.path.padEnd(c)} ${l.count}`);!e&&o.length>cp&&t.push(` ... ${o.length-cp} more (use --verbose to see all)`)}return t.join(`
|
|
152
152
|
`)+`
|
|
153
|
-
`}function gT(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 dp,cp,mT,up=J(()=>{"use strict";
|
|
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:
|
|
153
|
+
`}function gT(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 dp,cp,mT,up=J(()=>{"use strict";mr();Zr();mf();Cc();Xf();ap();dp=10,cp=15,mT=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Db={};lu(Db,{assertKnownAgent:()=>il,canonicalAgentId:()=>ja,resolveAgentIdOrExit:()=>ol,runAgentsAdd:()=>bp,runAgentsInstall:()=>hp,runAgentsList:()=>pp,runAgentsLogs:()=>gp,runAgentsPin:()=>wp,runAgentsRefresh:()=>al,runAgentsRemove:()=>vp,runAgentsSet:()=>yp,runAgentsSync:()=>mp,runAgentsUninstall:()=>Sp,runRegistryPin:()=>dl});import*as rl from"fs/promises";import*as Bb from"path";async function pp(){let e=(await Le("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
|
|
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 ${So(e.fetchedAt)})`:"";process.stdout.write(`
|
|
157
157
|
Registry version: ${e.version}${o}
|
|
@@ -165,12 +165,12 @@ Registry version: ${e.version}${o}
|
|
|
165
165
|
`),s.command&&process.stdout.write(` \u2192 ${s.command}
|
|
166
166
|
`)}async function mp(n){if(!n){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
|
|
167
167
|
`),process.exit(2);return}let e=await ol(n,"hydra agent sync"),s=(await Le(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${n}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
|
|
168
|
-
`);return}let r=s.synced.map(d=>({id:d.sessionId,upstream:d.upstreamSessionId,cwd:d.cwd,title:d.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:
|
|
168
|
+
`);return}let r=s.synced.map(d=>({id:d.sessionId,upstream:d.upstreamSessionId,cwd:d.cwd,title:d.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:Fs(i.id,r.map(d=>d.id)),upstream:Fs(i.upstream,r.map(d=>d.upstream)),cwd:Fs(i.cwd,r.map(d=>d.cwd))},a=d=>[d.id.padEnd(o.id),d.upstream.padEnd(o.upstream),d.cwd.padEnd(o.cwd),d.title].join(" ");process.stdout.write(a(i)+`
|
|
169
169
|
`);for(let d of r)process.stdout.write(a(d)+`
|
|
170
170
|
`);process.stdout.write(`
|
|
171
171
|
Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
|
|
172
172
|
`)}async function gp(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
|
|
173
|
-
`),process.exit(2);return}let t=
|
|
173
|
+
`),process.exit(2);return}let t=L.agentLogFile(n);await wo(t,e,"No log file (agent never ran?)")}async function yp(n,e){let t=await xe();if(!n){let d=await Lb()??fp(await ko());process.stdout.write(`${Ob(d)}
|
|
174
174
|
`);return}let s;try{let a=await Le("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(c=>c.id))}catch{}if(!(t.agents[n]!==void 0)&&s!==void 0&&!s.includes(n)){let a=n.toLowerCase(),d=a.length>0?s.filter(c=>c.toLowerCase().startsWith(a)):[];if(d.length===1)n=d[0];else if(d.length>1){process.stderr.write(`hydra agent set: '${n}' is ambiguous (matches ${d.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 im(n,e):await Di(n);let i=fp(await ko());e!==void 0&&n!==i.agent&&process.stdout.write(`Default model for ${n} is now ${e}.
|
|
@@ -187,18 +187,18 @@ Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
|
|
|
187
187
|
`),process.exit(2);return}await mu(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 Sp(n){if(!n){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
|
|
189
189
|
`),process.exit(2);return}let e=await ol(n,"hydra agent uninstall"),t=Pn();if(t===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
|
|
190
|
-
`),process.exit(1);return}let s=Bb.join(
|
|
190
|
+
`),process.exit(1);return}let s=Bb.join(L.agentsDir(),t,e),r=!1;try{await rl.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
|
|
191
191
|
`);return}await rl.rm(s,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${t}). Next session using it will re-install.
|
|
192
192
|
`)}async function dl(n){await am(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
|
|
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 cl=J(()=>{"use strict";et();we();Wi();La();mr()});var ll,Os,Eo,qa,Hb,Wa,kp,ul,ci,Ub,li,jb,ui,qb,fi,Po,Mo,Wb,_o,zb,Kb,Jb,Ip,Vb,fl,pl,za,Gb,Yb,Ka=J(()=>{"use strict";ll="\x1B[?2004h",Os="\x1B[?2004l",Eo="\x1B[200~",qa="\x1B[201~",Hb="\x1B[?1049l",Wa="\x1B[?7h",kp="\x1B[?7l",ul="\x1B[?25h",ci="\x1B[?1l",Ub="\x1B[>1u",li="\x1B[<u",jb="\x1B[>4;2m",ui="\x1B[>4;0m",qb="\x1B[>5;1m",fi="\x1B[>5;0m",Po="\x1B[?1000l",Mo="\x1B[?1002l",Wb="\x1B[?1003l",_o="\x1B[?1006l",zb="\x1B[?1015l",Kb="\x1B[?w",Jb="\x1B[=24;1w",Ip="\x1B[=0;0w",Vb="\x1B]22;pointer\x07",fl="\x1B]22;default\x07",pl="\x1B[?1004h",za="\x1B[?1004l",Gb="\x1B[?2026h",Yb="\x1B[?2026l"});function zn(){process.stdout.write(li),process.stdout.write(Os),process.stdout.write(ui),process.stdout.write(fi),process.stdout.write(Po),process.stdout.write(Mo),process.stdout.write(_o),process.stdout.write(ci),process.stdout.write("\x1B>")}function tn(n){return n.width??80}function Ls(n){return n.height??24}function Kn(n,e){let t=tn(n),s=Ls(n),r=e.contentWidth??wT,i=Math.max(10,t-4),o=Math.min(r,i),a=o+2,d=Math.max(1,Math.min(e.contentHeight,s-4)),c=d+2,l=Math.max(1,Math.floor((t-a)/2)+1),u=Math.max(1,Math.floor((s-c)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=Qb.repeat(a-2),p=IT(f,e.title);n.moveTo(l,u),n.dim.noFormat(bT),xT(n,p),n.dim.noFormat(vT);for(let h=1;h<=d;h++)n.moveTo(l,u+h),n.dim.noFormat(Xb),e.overlay&&n.noFormat(" ".repeat(o)),n.moveTo(l+a-1,u+h),n.dim.noFormat(Xb);return n.moveTo(l,u+c-1),n.dim.noFormat(ST+Qb.repeat(a-2)+kT),{x:l,y:u,w:a,h:c,contentX:l+1,contentY:u+1,contentW:o,contentH:d}}function IT(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 xT(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 tt(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function Ja(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function Ss(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 d=!1,c=()=>{d||(r??t)()},l=(h,m,y)=>{d||s(h,m,y,p)},u=(h,m)=>{d||!i||i(h,m,p)},f=()=>{d||(d=!0,e.off("key",l),e.off("resize",c),i&&e.off("mouse",u),e.grabInput(!1),re({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({}),re({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",c)})}var wT,Qb,Xb,bT,vT,ST,kT,pi=J(()=>{"use strict";Vr();Ka();wT=64,Qb="\u2500",Xb="\u2502",bT="\u250C",vT="\u2510",ST="\u2514",kT="\u2518"});function Zb(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 RT(n,e,t){let s={title:`Agent "${n}" needs to be set up`,description:e?.description??AT,footer:CT};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),t&&t.length>0){s.authMethods=t;let r=t.map((d,c)=>({index:c,label:`[${c+1}] ${Zb(d)}`,method:d}));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 TT(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 ET(n){return typeof n!="object"||n===null?!1:n.code===W.AuthRequired}function ev(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[Bt];if(!(typeof s!="object"||s===null))return s}function PT(n){let e=ev(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function MT(n){let e=ev(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,d=r.name,c=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof d=="string"&&(l.name=d),c!==null&&typeof c=="object"&&!Array.isArray(c)&&(l._meta=c),s.push(l)}return s.length>0?s:void 0}async function tv(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!ET(e))throw e;let t=PT(e)??n.fallbackAgentId??"",s=MT(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 _T(n,e,t){n.grabInput(!1),re({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),zn(),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({}),re({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",d=>{o(),i({exitCode:d})}),a.on("error",d=>{o(),process.stdout.write(`
|
|
195
195
|
failed to spawn ${e.command}: ${d.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 $T(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 xp(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($T(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 nv(n,e,t,s,r){zn();let i=RT(e,t,s),o=!1,a,d,c=()=>{let
|
|
199
|
-
`)}}});function dv(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 hi(n){return{outcome:{outcome:"selected",optionId:dv(n,["allow_once","allow_always"])}}}function cv(n){return{outcome:{outcome:"selected",optionId:dv(n,["reject_once","reject_always"])}}}function gl(n){return n&&typeof n=="object"?n:void 0}function Va(n){return typeof n=="string"&&n.length>0?n:void 0}function lv(n){let e=gl(n),t=gl(e?.toolCall),s={paths:[]};if(!t)return s;let r=Va(t.kind);r&&(s.kind=r);let i=new Set,o=c=>{let l=Va(c);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let c of a)o(gl(c)?.path);let d=gl(t.rawInput);if(d){o(d.file_path),o(d.filePath),o(d.path);let c=Va(d.command);c&&(s.command=c);let l=Va(d.url);l&&(s.url=l);let f=Va(d.description);f&&(s.description=f)}return s}function uv(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 yl=J(()=>{"use strict"});function UE(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Pv(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 jE(n,e){let t=Pv(n),s=Pv(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 Ga(){if(vr!==void 0)return vr;if(UE())return vr=null,vr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:Mv,version:be}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&jE(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}vr={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{}vr=null}}catch{vr=null}return vr}function Ya(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${Mv}`}var Mv,vr,Ep=J(()=>{"use strict";gn();Mv="@hydra-acp/cli"});import*as Qa from"fs/promises";import*as Pp from"path";async function Xa(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Pp.resolve(st(e)),s;try{s=await Qa.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 _v(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 Qa.stat(r)).isDirectory())return r}catch{}return null}async function $v(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=Pp.resolve(st(r)),o;try{o=(await Qa.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,basePrefix:s,matches:[]}}let a=s.startsWith("."),d=o.filter(c=>c.name.startsWith(s)).filter(c=>a||!c.name.startsWith(".")).map(c=>c.isDir?`${c.name}/`:c.name).sort();return{prefix:t,basePrefix:s,matches:d}}var Mp=J(()=>{"use strict";et()});var Fv,Ov,Lv,Bv=J(()=>{"use strict";Fv="hydra-acp/question/list",Ov="hydra-acp/question/answer",Lv="hydra-acp/question/dismiss"});import{EventEmitter as qE}from"events";import{WebSocket as WE}from"ws";function zE(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=ca(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 WE(n,e,t),o=()=>{i.off("error",a),s(ys(i))},a=d=>{i.off("open",o),r(d)};i.once("open",o),i.once("error",a)})}function Nv(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??zE,d=["acp.v1",`hydra-acp-token.${n.token}`],c=await a(n.wsUrl,d),l=new Zt(c),f;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)f=s.reuseSessionId;else{let m=t.replace(/\s+/g," ").trim().slice(0,60);f=(await Kc(n,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw c.close().catch(()=>{}),m}let u=new _p(l,c,f,n,o),p=!1,h=m=>{p||(p=!0,u.emit("event",m),c.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&u.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw c.close().catch(()=>{}),bs(n,f,o).catch(()=>{}),m}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:t}],_meta:{[Bt]:{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 _p,Dv=J(()=>{"use strict";la();Na();Yr();ho();Nt();_p=class extends qE{_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(()=>{}),bs(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 $p,kl,Hv=J(()=>{"use strict";oi();lr();$p=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())}},kl=class extends $p{_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=gs(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=Ro(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Ro(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=Ua(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=Ua(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=yr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return wr(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 GE(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Za(n,e,t,s){zn();let r=GE(e,t??KE),i=0,o=null,a=null,d=()=>{let E=Bs(n)-8;return Math.max(1,Math.min(JE,e.length,E))},c=()=>{let E=d(),P=Math.max(0,e.length-E);i>P&&(i=P),i<0&&(i=0)},l=()=>{let E=d();r<i?i=r:r>=i+E&&(i=r-E+1),c()},f=null,u=0,p=(E,P)=>{if(E<i||E>=i+u)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,q=` ${B} ${H.id}`;if(E===r){let Q=`${q} ${N}`;n.brightWhite.bgBlue.noFormat(Ja(tt(Q,_),_))}else{let Q=_-q.length-2,X=Q>1?` ${tt(N,Q)}`:"";n.noFormat(q),X.length>0&&n.dim.noFormat(X);let G=q.length+X.length;G<_&&n.noFormat(" ".repeat(_-G))}},h=(E,P)=>{let H=E.contentY+2+u+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=Ja(tt(F,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{c();let E=d(),P=E+4,H=Math.min(VE,Math.max(40,tn(n)-8)),_=Kn(n,{contentHeight:P,contentWidth:H,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=_,f=_,u=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=f;if(P===null){m();return}let H=d(),_=i;if(l(),i!==_){m();return}u=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)}},v=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=f;if(E===null){m();return}let P=d();c(),u=Math.min(P,e.length-i);let H=Math.min(e.length,i+P);for(let _=i;_<H;_++)p(_,E);for(let _=u;_<P;_++){let F=E.contentY+2+_;n.moveTo(E.contentX,F),n.noFormat(" ".repeat(E.contentW))}h(E,P)},A=E=>{let P=d(),H=Math.max(0,e.length-P);if(H===0)return;let _=Math.max(0,Math.min(H,i+E));_!==i&&(i=_,k())};return Ss({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"){v();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"){v();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 Q=P?.y;if(typeof Q!="number"||o===null)return;let X=Q-o;if(X<0||X>=u)return;let G=i+X;if(G<0||G>=e.length)return;if(G!==r){let pe=r;r=G,w(pe)}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>=u)return;let N=i+B;if(N<0||N>=e.length)return;let q=e[N];q&&H({kind:"select",agentId:q.id,persist:!1})}})}var KE,JE,VE,Fp=J(()=>{"use strict";pi();KE="opencode",JE=20,VE=88});import YE from"path";function ed(n){return Uv[YE.extname(n).toLowerCase()]??null}function QE(n){return ed(n)!==null}function Op(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(!XE.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 ZE(n){return Op(n)!==null}function Fn(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function jv(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(!ZE(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!QE(o))return null;t.push(o)}return t.length>0?t:null}var ks,Uv,XE,Il=J(()=>{"use strict";ks=10*1024*1024,Uv={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};XE=new Set(Object.values(Uv))});import{spawn as eP}from"child_process";import Lp from"fs/promises";import tP from"os";import nP from"path";async function Al(n={}){let e={...Bp,...n};return e.platform==="darwin"?oP(e):e.platform==="linux"?aP(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function zv(n={}){let e={...Bp,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Bo(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Bo(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 td(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Kv(n,e={}){let{target:t="both",...s}=e,r={...Bp,...s},i=await sP(r,n,t);if(i.ok)return i;let o=rP(r,n,t);return o.ok||o.reason!==Jv?o:i}async function sP(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await xl(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 Bo(n,"wl-copy")?Wv(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await Bo(n,"xclip")?Wv(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 Wv(n,e,t,s,r,i,o){let a=t;if(i){try{await xl(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await xl(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await xl(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function rP(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>qv)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${qv} 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??iP)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Jv}}function iP(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 oP(n){let e=nP.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 Vv(n.spawn,"osascript",s);let r=await fP(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Lp.unlink(e).catch(()=>{})}try{let r=await td(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function aP(n){let e=await dP(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await uP(n,e),s=lP(t);if(s)try{let r=await td(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>ks?{ok:!1,reason:`clipboard image is ${Fn(r.length)}, max ${Fn(ks)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await td(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function dP(n){return n.env.WAYLAND_DISPLAY&&await Bo(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Bo(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function lP(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of cP)if(e.has(t))return t;return null}async function uP(n,e){try{return(await td(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
|
|
198
|
+
`),i({exitCode:-1})}})}function $T(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 xp(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($T(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 nv(n,e,t,s,r){zn();let i=RT(e,t,s),o=!1,a,d,c=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,d&&u++;let f=Kn(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(tt(` ${a}`,p)),h++),d&&(n.moveTo(f.contentX,f.contentY+h),n.brightRed.noFormat(tt(` ${d}`,p)),h++),n.moveTo(f.contentX,f.contentY+h),n.brightWhite.bold.noFormat(tt(` ${i.title}`,p)),h+=2,n.moveTo(f.contentX,f.contentY+h),n.noFormat(tt(` ${i.description}`,p)),h++,i.command&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Run: "),n.brightWhite.noFormat(tt(i.command,p-7)),h++),i.url&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Docs: "),n.brightWhite.noFormat(tt(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(tt(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 Ss({term:n,render:()=>{c()},onKey:(u,f,p,h)=>{if(o)return;let m=TT(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,d=void 0,a=`Authenticating with ${Zb(y)}\u2026`,c();let w=r.runTerminalAuth??(b=>_T(n,b));(async()=>{let b=await xp(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"){d=b.message,a=void 0,o=!1,c();return}a=void 0,d=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,c()})()}}}})}var AT,CT,Ap=J(()=>{"use strict";Vr();Dd();Ud();pi();AT="This agent requires authentication before use.",CT="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as av}from"timers/promises";function jT(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var NT,DT,HT,UT,Fo,Cp=J(()=>{"use strict";Ba();ho();NT=200,DT=5e3,HT=2,UT=60,Fo=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current||this.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let 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(()=>{}),av(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=NT;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await si(s,this.opts.subprotocols);this.bindStream(ys(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>=UT)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 av(t),this.destroyed)return;t=Math.min(t*HT,DT)}}bindStream(e){this.current=e,e.onMessage(t=>{if(jT(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 dv(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 hi(n){return{outcome:{outcome:"selected",optionId:dv(n,["allow_once","allow_always"])}}}function cv(n){return{outcome:{outcome:"selected",optionId:dv(n,["reject_once","reject_always"])}}}function gl(n){return n&&typeof n=="object"?n:void 0}function Va(n){return typeof n=="string"&&n.length>0?n:void 0}function lv(n){let e=gl(n),t=gl(e?.toolCall),s={paths:[]};if(!t)return s;let r=Va(t.kind);r&&(s.kind=r);let i=new Set,o=c=>{let l=Va(c);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let c of a)o(gl(c)?.path);let d=gl(t.rawInput);if(d){o(d.file_path),o(d.filePath),o(d.path);let c=Va(d.command);c&&(s.command=c);let l=Va(d.url);l&&(s.url=l);let u=Va(d.description);u&&(s.description=u)}return s}function uv(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 yl=J(()=>{"use strict"});function UE(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Pv(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 jE(n,e){let t=Pv(n),s=Pv(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 Ga(){if(Sr!==void 0)return Sr;if(UE())return Sr=null,Sr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:Mv,version:be}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&jE(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}Sr={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{}Sr=null}}catch{Sr=null}return Sr}function Ya(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${Mv}`}var Mv,Sr,Ep=J(()=>{"use strict";gn();Mv="@hydra-acp/cli"});import*as Qa from"fs/promises";import*as Pp from"path";async function Xa(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Pp.resolve(st(e)),s;try{s=await Qa.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 _v(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 Qa.stat(r)).isDirectory())return r}catch{}return null}async function $v(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=Pp.resolve(st(r)),o;try{o=(await Qa.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,basePrefix:s,matches:[]}}let a=s.startsWith("."),d=o.filter(c=>c.name.startsWith(s)).filter(c=>a||!c.name.startsWith(".")).map(c=>c.isDir?`${c.name}/`:c.name).sort();return{prefix:t,basePrefix:s,matches:d}}var Mp=J(()=>{"use strict";et()});var Fv,Ov,Lv,Bv=J(()=>{"use strict";Fv="hydra-acp/question/list",Ov="hydra-acp/question/answer",Lv="hydra-acp/question/dismiss"});import{EventEmitter as qE}from"events";import{WebSocket as WE}from"ws";function zE(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=ca(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 WE(n,e,t),o=()=>{i.off("error",a),s(ys(i))},a=d=>{i.off("open",o),r(d)};i.once("open",o),i.once("error",a)})}function Nv(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??zE,d=["acp.v1",`hydra-acp-token.${n.token}`],c=await a(n.wsUrl,d),l=new Zt(c),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 Kc(n,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw c.close().catch(()=>{}),m}let f=new _p(l,c,u,n,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),c.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 c.close().catch(()=>{}),bs(n,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[Bt]:{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 _p,Dv=J(()=>{"use strict";la();Na();Yr();ho();Nt();_p=class extends qE{_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(()=>{}),bs(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 $p,kl,Hv=J(()=>{"use strict";oi();ur();$p=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())}},kl=class extends $p{_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=gs(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=Ro(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Ro(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=Ua(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=Ua(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=wr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return br(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 GE(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Za(n,e,t,s){zn();let r=GE(e,t??KE),i=0,o=null,a=null,d=()=>{let E=Ls(n)-8;return Math.max(1,Math.min(JE,e.length,E))},c=()=>{let E=d(),_=Math.max(0,e.length-E);i>_&&(i=_),i<0&&(i=0)},l=()=>{let E=d();r<i?i=r:r>=i+E&&(i=r-E+1),c()},u=null,f=0,p=(E,_)=>{if(E<i||E>=i+f)return;let H=e[E];if(!H)return;let P=_.contentW,$=_.contentY+2+(E-i);n.moveTo(_.contentX,$);let B=E===r?"\u276F":" ",N=H.description??H.name,U=` ${B} ${H.id}`;if(E===r){let G=`${U} ${N}`;n.brightWhite.bgBlue.noFormat(Ja(tt(G,P),P))}else{let G=P-U.length-2,X=G>1?` ${tt(N,G)}`:"";n.noFormat(U),X.length>0&&n.dim.noFormat(X);let Y=U.length+X.length;Y<P&&n.noFormat(" ".repeat(P-Y))}},h=(E,_)=>{let H=E.contentY+2+f+1;n.moveTo(E.contentX,H);let $=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>_?` (${r+1}/${e.length})`:""}`,B=Ja(tt($,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{c();let E=d(),_=E+4,H=Math.min(VE,Math.max(40,tn(n)-8)),P=Kn(n,{contentHeight:_,contentWidth:H,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=P,u=P,f=Math.min(E,e.length-i),o=P.contentY+2,n.moveTo(P.contentX,P.contentY),n.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let $=Math.min(e.length,i+E);for(let B=i;B<$;B++)p(B,P);return h(P,E),P},y=()=>m(),w=E=>{let _=u;if(_===null){m();return}let H=d(),P=i;if(l(),i!==P){m();return}f=Math.min(H,e.length-i),E!==r&&(p(E,_),p(r,_)),h(_,H)},b=()=>{if(r<e.length-1){let E=r;r++,w(E)}},v=()=>{if(r>0){let E=r;r--,w(E)}},k=()=>{let E=u;if(E===null){m();return}let _=d();c(),f=Math.min(_,e.length-i);let H=Math.min(e.length,i+_);for(let P=i;P<H;P++)p(P,E);for(let P=f;P<_;P++){let $=E.contentY+2+P;n.moveTo(E.contentX,$),n.noFormat(" ".repeat(E.contentW))}h(E,_)},A=E=>{let _=d(),H=Math.max(0,e.length-_);if(H===0)return;let P=Math.max(0,Math.min(H,i+E));P!==i&&(i=P,k())};return Ss({term:n,render:y,overlay:s?.overlay===!0,onKey:(E,_,H,P)=>{if(E==="CTRL_C"||E==="CTRL_D"){P({kind:"cancel"});return}if(E==="ESCAPE"){P({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let $=e[r];$&&P({kind:"select",agentId:$.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){v();return}if(E==="DOWN"||E==="TAB"){b();return}if(H?.isCharacter){let $=E.toLowerCase();if($==="s"){let B=e[r];B&&P({kind:"select",agentId:B.id,persist:!0});return}if($==="j"){b();return}if($==="k"){v();return}}},onMouse:(E,_,H)=>{if(E==="MOUSE_WHEEL_UP"){A(-1);return}if(E==="MOUSE_WHEEL_DOWN"){A(1);return}if(E==="MOUSE_MOTION"){let G=_?.y;if(typeof G!="number"||o===null)return;let X=G-o;if(X<0||X>=f)return;let Y=i+X;if(Y<0||Y>=e.length)return;if(Y!==r){let pe=r;r=Y,w(pe)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let P=_?.x,$=_?.y;if(a!==null&&typeof P=="number"&&typeof $=="number"&&(P<a.x||P>=a.x+a.w||$<a.y||$>=a.y+a.h)){H({kind:"back"});return}if(typeof $!="number"||o===null)return;let B=$-o;if(B<0||B>=f)return;let N=i+B;if(N<0||N>=e.length)return;let U=e[N];U&&H({kind:"select",agentId:U.id,persist:!1})}})}var KE,JE,VE,Fp=J(()=>{"use strict";pi();KE="opencode",JE=20,VE=88});import YE from"path";function ed(n){return Uv[YE.extname(n).toLowerCase()]??null}function QE(n){return ed(n)!==null}function Op(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(!XE.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 ZE(n){return Op(n)!==null}function Fn(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function jv(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(!ZE(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!QE(o))return null;t.push(o)}return t.length>0?t:null}var ks,Uv,XE,Il=J(()=>{"use strict";ks=10*1024*1024,Uv={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};XE=new Set(Object.values(Uv))});import{spawn as eP}from"child_process";import Lp from"fs/promises";import tP from"os";import nP from"path";async function Al(n={}){let e={...Bp,...n};return e.platform==="darwin"?oP(e):e.platform==="linux"?aP(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function zv(n={}){let e={...Bp,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Bo(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Bo(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 td(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Kv(n,e={}){let{target:t="both",...s}=e,r={...Bp,...s},i=await sP(r,n,t);if(i.ok)return i;let o=rP(r,n,t);return o.ok||o.reason!==Jv?o:i}async function sP(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await xl(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 Bo(n,"wl-copy")?Wv(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await Bo(n,"xclip")?Wv(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 Wv(n,e,t,s,r,i,o){let a=t;if(i){try{await xl(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await xl(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await xl(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function rP(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>qv)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${qv} 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??iP)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Jv}}function iP(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 oP(n){let e=nP.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 Vv(n.spawn,"osascript",s);let r=await fP(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Lp.unlink(e).catch(()=>{})}try{let r=await td(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function aP(n){let e=await dP(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await uP(n,e),s=lP(t);if(s)try{let r=await td(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>ks?{ok:!1,reason:`clipboard image is ${Fn(r.length)}, max ${Fn(ks)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await td(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Np(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function dP(n){return n.env.WAYLAND_DISPLAY&&await Bo(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Bo(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function lP(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of cP)if(e.has(t))return t;return null}async function uP(n,e){try{return(await td(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
|
|
200
200
|
`).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Np(n){return n.replace(/\r\n?/g,`
|
|
201
|
-
`)}async function Bo(n,e){try{return await Vv(n.spawn,"which",[e]),!0}catch{return!1}}async function fP(n,e){try{let t=await Lp.readFile(n);return e&&await Lp.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>ks?{ok:!1,reason:`clipboard image is ${Fn(t.length)}, max ${Fn(ks)}`}:{ok:!0,kind:"image",attachment:{mimeType:ed(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Vv(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 xl(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",d=>{d===0?r():i(new Error(`${e} exited ${d}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function td(n,e,t){return new Promise((s,r)=>{let i=n(e,t),o=[],a=i.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${d}`)))};i.stdout?.on("data",
|
|
201
|
+
`)}async function Bo(n,e){try{return await Vv(n.spawn,"which",[e]),!0}catch{return!1}}async function fP(n,e){try{let t=await Lp.readFile(n);return e&&await Lp.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>ks?{ok:!1,reason:`clipboard image is ${Fn(t.length)}, max ${Fn(ks)}`}:{ok:!0,kind:"image",attachment:{mimeType:ed(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Vv(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 xl(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",d=>{d===0?r():i(new Error(`${e} exited ${d}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function td(n,e,t){return new Promise((s,r)=>{let i=n(e,t),o=[],a=i.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${d}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{c||(c=!0,r(u))}),i.on("close",u=>{d=u??0,l()})})}var Bp,qv,Jv,cP,Cl=J(()=>{"use strict";Il();Bp={platform:process.platform,env:process.env,spawn:eP,tmpdir:tP.tmpdir};qv=74994;Jv="no TTY available for OSC 52 clipboard write";cP=["image/png","image/jpeg","image/gif","image/webp"]});function hP(n,e){return`[pasted #${n} +${e} lines]`}var pP,nd,Dp,mP,Bs,Hp=J(()=>{"use strict";pP=/\[pasted #(\d+) \+\d+ lines\]/g,nd=/\[pasted #(\d+) \+\d+ lines\]$/,Dp=/^\[pasted #(\d+) \+\d+ lines\]/;mP=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>mP&&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
202
|
`).length;if(this.collapsePastes&&t>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(hP(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":{let t=this.amend();return t.length>0?t:[{type:"toggle-sidebar"}]}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
203
|
`)}expandPastes(e){return e.replace(pP,(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(`
|
|
@@ -207,83 +207,83 @@ failed to spawn ${e.command}: ${a.message}
|
|
|
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(nd);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(nd);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(nd);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(nd);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],d=t.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{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 No,Rl,Up=J(()=>{"use strict";No=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}invalidate(e,t){this.lastFrameRows.delete(e===void 0?String(t):`${e}:${t}`)}paintRow(e,t,s,r){if(e<1||e>this.term.height)return!1;let i=r?.region,o=i===void 0?String(e):`${i}:${e}`;return this.lastFrameRows.get(o)===t?!1:(this.lastFrameRows.set(o,t),this.term.moveTo(r?.column??1,e),s(),this.term.styleReset(),r?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Rl=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{resolve as gP}from"path";function wP(n){return!yP.has(n)}function bP(n){return n.replace(/\s+/gu," ").trim()}function vP(n,e,t){let s=n.trim();for(let r of[e,t]){if(r===void 0||r==="")continue;let i=s.toLowerCase(),o=r.toLowerCase();if(i===o)return"";i.startsWith(`${o} `)&&(s=s.slice(r.length).trimStart())}return s}function SP(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function kP(n){switch(n){case"read":return"read";case"edit":return"edit";case"delete":return"delete";case"move":return"move";case"search":return"search";case"execute":return"run";case"fetch":return"fetch";case"think":return"think";default:return Gv}}function IP(n,e){if(!wP(n.status))return null;let t=kP(n.rawKind),s=c=>c===void 0?"":vP(bP(c),t,n.rawKind),r=n.editDiff?.path??Jd(n.locations),i=r===void 0||r===""?void 0:e===null?r:gP(e,r),o=s(n.latestTitle),a=t!==Gv&&SP(o)?"":o,d=s(n.detail)||xP(i)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:i}}function xP(n){return n===void 0?"":n.split("/").filter(t=>t!=="").at(-1)??""}function Yv(n,e,t){let s=[];for(let r of n){let i=e.get(r);if(i===void 0)continue;let o=IP(i,t);o!==null&&s.push(o)}return s}var jp,yP,Gv,qp=J(()=>{"use strict";ha();jp=4,yP=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);Gv="tool"});function zp(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;return t<60?`${t}m ${String(s).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function Qv(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function Wp(n){if(n<1e3)return String(n);if(n<1e6){let e=n/1e3;return`${e<10?e.toFixed(1):Math.round(e)}K`}return`${(n/1e6).toFixed(1)}M`}function AP(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),s=Math.round(t*e*8),r=Math.floor(s/8),i=s%8,o=i===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[i-1];return"\u2588".repeat(Math.min(e,r))+(r<e?o:"")+"\xB7".repeat(Math.max(0,e-r-(o?1:0)))}function Is(n,e){return{body:n,bodyStyle:e}}function Jp(n,e,t){let{cellWidth:s,truncate:r}=t.metrics,i=t.width-s(n)-s(e);return i<1?{body:r(`${n} ${e}`,t.width),bodyStyle:"dim"}:{prefix:`${n}${" ".repeat(i)}`,prefixStyle:"dim",body:e}}function nS(n,e,t,s){let r={body:n,bodyStyle:t,openPath:e,item:!0};if(s!==void 0&&s.length>0){let i=n.indexOf(s);i!==-1&&(r.openSpan={start:i,end:i+s.length})}return r}function Sr(n,e,t){let{cellWidth:s,truncate:r}=t.metrics,i=t.width-s(n)-s(e);return i<1?r(`${n} ${e}`,t.width):`${n}${" ".repeat(i)}${e}`}function sS(n){let e=n.map(s=>s.split("/").pop()??s),t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);return n.map((s,r)=>{let i=e[r];return(t.get(i)??0)<=1?i:s.split("/").slice(-2).join("/")})}function $P(n,e,t){let{cellWidth:s,truncate:r}=t.metrics;if(e<=0)return"";if(s(n)<=e)return n;let i=n.slice(n.lastIndexOf("/")+1);if(i!==n&&s(i)<=e)return i;let o=i.length<n.length?i:n;for(let a=1;a<o.length;a++){let d=`\u2026${o.slice(a)}`;if(s(d)<=e)return d}return r(o,e)}function Zv(n){if(n<1024)return`${Math.max(0,Math.round(n))}B`;let e=n/(1024*1024);return e<1?`${Math.round(n/1024)}K`:e<1024?e<10?`${e.toFixed(1)}M`:`${Math.round(e)}M`:`${(e/1024).toFixed(1)}G`}function tS(n){if(n===void 0)return"\u2013".padStart(eS);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(eS)}var Kp,Xv,CP,RP,TP,EP,PP,MP,_P,FP,eS,OP,rS,iS=J(()=>{"use strict";qp();Kp=5;Xv=5e3,CP={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${Qv(n.now-n.lastTurnEndedAt,Xv)}`:"fresh",render:(n,e)=>n.busySince!==null?[Is(Sr("\u25CF thinking",zp(n.now-n.busySince),e),"tool-status-running")]:n.lastTurnEndedAt!==null?[Is(Sr("\u25CB idle",zp(Qv(n.now-n.lastTurnEndedAt,Xv)),e),"dim")]:[Is("\u25CB ready","dim")]},RP={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,jp);return`${e.width}|${n.running.length}|`+t.map(s=>{let r=s.startedAt===void 0?"":Math.floor(Math.max(0,n.now-s.startedAt)/1e3);return`${s.verb}:${s.detail??""}:${r}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:s}=e.metrics,r=[],i=n.running.slice(0,jp);for(let o of i){let a=o.startedAt===void 0?"":zp(Math.max(0,n.now-o.startedAt)),d=`\u25B8 ${o.verb}`,c=e.width-s(d)-(a===""?0:s(a)+1)-1,l=o.detail===void 0||c<4?"":` ${t(o.detail,c)}`,f=`${d}${l}`,u=a===""?f:Sr(f,a,e),p={body:u,bodyStyle:"tool-status-running",openPath:o.path};if(o.path!==void 0){let h=o.path.slice(o.path.lastIndexOf("/")+1),m=h.length>0?u.indexOf(h):-1;m!==-1&&(p.openSpan={start:m,end:m+h.length})}r.push(p)}return n.running.length>i.length&&r.push(Is(` +${n.running.length-i.length} more`,"dim")),r}},TP={id:"context",title:"context",relevant:n=>n.usage.used!==void 0||n.usage.costAmount!==void 0,versionKey:(n,e)=>`${n.usage.used??""}/${n.usage.size??""}/${n.usage.costAmount??""}/${e.width}`,render:(n,e)=>{let t=[],{used:s,size:r,costAmount:i,costCurrency:o}=n.usage;if(s!==void 0&&r!==void 0&&r>0){let a=s/r;t.push(Is(Sr(`${Wp(s)}/${Wp(r)}`,`${Math.round(a*100)}%`,e),a>=.9?"tool-status-fail":"info")),t.push(Is(AP(a,e.width),a>=.9?"tool-status-fail":"plan-done"))}else s!==void 0&&t.push(Is(Sr("tokens",Wp(s),e),"info"));if(i!==void 0){let a=o==="USD"||o===void 0?"$":`${o} `;t.push(Is(Sr("cost",`${a}${i.toFixed(2)}`,e),"dim"))}return t}},EP={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[Is(Sr("queued",String(n.queued),e),"tool-status-pending")]},PP={id:"todo",title:"todo",pageSize:Kp,relevant:n=>n.plan.length>0,titleNote:n=>`${n.plan.filter(e=>e.status==="completed").length}/${n.plan.length}`,versionKey:(n,e)=>`${e.width}|`+n.plan.map(t=>`${t.status}:${t.content}`).join("\0"),render:(n,e)=>{let{truncate:t}=e.metrics,s=[];for(let r of n.plan){let i=r.status==="completed"?"\u2713":r.status==="in_progress"?"\u25B8":"\xB7",o=r.status==="completed"?"plan-done":r.status==="in_progress"?"plan":"plan-pending";s.push({body:t(`${i} ${r.content}`,e.width),bodyStyle:o,item:!0})}return s}};MP={id:"files",title:"edited",pageSize:Kp,relevant:n=>n.editedFiles.length>0,titleNote:n=>n.editedFiles.length>1?`${n.editedFiles.length} files`:void 0,versionKey:(n,e)=>`${e.width}|`+n.editedFiles.map(t=>`${t.path}:${t.added??""}:${t.removed??""}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:s}=e.metrics,r=[...n.editedFiles].reverse(),i=[],o=sS(r.map(a=>a.path));return r.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?s(c)+1:0),f=t(o[d],Math.max(1,l));i.push(nS(c?Sr(f,c,e):f,a.path,"tool",f))}),i}},_P={id:"git",title:"git",pageSize:Kp,relevant:n=>n.git!==null&&(n.git.staged>0||n.git.unstaged>0||n.git.untracked>0||n.git.ahead>0||n.git.behind>0),versionKey:(n,e)=>{let t=n.git;if(t===null)return"none";let s=t.files.map(r=>`${r.state}:${r.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${s}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:s}=e.metrics,r=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");r.push(d?Jp(s(t.branch,e.width-d.length-1),d,e):{body:s(t.branch,e.width)})}let i=[];t.staged>0&&i.push(`${t.staged} staged`),t.unstaged>0&&i.push(`${t.unstaged} dirty`),t.untracked>0&&i.push(`${t.untracked} new`),i.length>0&&r.push(Is(s(i.join(" \xB7 "),e.width),"dim"));let o=t.files,a=sS(o.map(d=>d.path));return o.forEach((d,c)=>{let l=d.state==="staged"?"\u25CF":d.state==="dirty"?"\u25CB":"+",f=d.state==="staged"?"plan-done":d.state==="dirty"?"tool":"plan-pending";r.push(nS(s(`${l} ${a[c]}`,e.width),d.path,f,a[c]))}),r}};FP={id:"session",title:"session",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.sessionId}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,s=[],r=(i,o)=>{let a=e.width-t(i)-1;s.push(Jp(i,$P(o,a,e),e))};return n.agent!==null&&r("agent",n.agent),n.model!==null&&r("model",n.model),n.mode!==null&&r("mode",n.mode),n.sessionId!==null&&r("id",n.sessionId),s}};eS=5;OP={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${Zv(t.rssBytes)}:${tS(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:s}=e.metrics;return n.resources.map(r=>{let i=`${Zv(r.rssBytes)} ${tS(r.cpuFraction)}`,o=r.processes>1?`${r.label} \xD7${r.processes}`:r.label,a=e.width-t(i)-1;return Jp(s(o,Math.max(1,a)),i,e)})}},rS=[CP,TP,EP,PP,MP,_P,OP,FP,RP]});function Vp(n){return n==="frame"}function oS(n=0){return{now:n,busySince:null,lastTurnEndedAt:null,queued:0,usage:{},plan:[],editedFiles:[],running:[],git:null,resources:[],sessionId:null,agent:null,model:null,mode:null}}var Gp=J(()=>{"use strict"});function BP(n){return rS.find(e=>e.id===n)}function Yp(n,e){return{body:"\u2500".repeat(Math.max(0,n)),bodyStyle:"dim",gutter:e}}function jP(n,e,t,s){if(s<=0||!Number.isFinite(s))return e;let r=Tl(e);if(r<=s)return e;let i=Math.ceil(r/s),o=t.pages?.[n.id]??0,a=Math.max(0,Math.min(i-1,o)),d=a*s,c=d+s,l=[],f=0;for(let P of e){if(P.item!==!0){l.push(P);continue}let H=f++;H>=d&&H<c&&l.push(P)}if(n.title===void 0||l.length===0)return l;let{cellWidth:u,truncate:p}=t.metrics,h=`${HP} ${a+1}/${i} ${UP}`,m=u(h),y=t.width-m-1;if(y<1)return l;let w=p(n.title,y),b=t.width-u(w)-m,v=`${w}${" ".repeat(Math.max(1,b))}${h}`,k=u(v)-m+1,A=u(v),E=[];return a>0&&E.push({start:k,end:k,page:{gadget:n.id,index:a-1}}),a<i-1&&E.push({start:A,end:A,page:{gadget:n.id,index:a+1}}),l[0]={...l[0],body:v,actions:E},l}function Tl(n){return n.reduce((e,t)=>e+(t.item===!0?1:0),0)}function qP(n,e,t){let s=n.title??"",r=n.titleNote?.(e,t);if(r===void 0||r.length===0)return{body:s,bodyStyle:"dim"};let{cellWidth:i,truncate:o}=t.metrics,a=i(r),d=t.width-a-1;if(d<1)return{body:o(s,t.width),bodyStyle:"dim"};let c=o(s,d),l=t.width-i(c)-a;return{body:`${c}${" ".repeat(Math.max(1,l))}${r}`,bodyStyle:"dim"}}function WP(n,e,t,s){let r=n.map((c,l)=>e[l]?Tl(c):0),i=n.reduce((c,l,f)=>c+(e[f]?0:Tl(l)),0),o=c=>t+i+r.reduce((l,f)=>l+Math.min(f,c),0),a=Math.max(0,...r);if(o(a)<=s)return Number.POSITIVE_INFINITY;let d=1;for(let c=1;c<=a&&o(c)<=s;c++)d=c;return d}var LP,NP,DP,HP,UP,El,aS=J(()=>{"use strict";iS();Gp();LP=["activity","context","queue","todo","files","git","resources","session","tools"];NP=Object.freeze({body:""}),DP=Object.freeze({body:"",gutter:"\u2502"});HP="\u2039",UP="\u203A";El=class{cache=new Map;rules=null;gadgets=[];constructor(e=LP){this.setGadgets(e)}setGadgets(e){let t=e.map(r=>BP(r)).filter(r=>r!==void 0);(t.length!==this.gadgets.length||t.some((r,i)=>r!==this.gadgets[i]))&&(this.gadgets=t,this.cache.clear())}configuredIds(){return this.gadgets.map(e=>e.id)}isConfigured(e){return this.gadgets.some(t=>t.id===e)}invalidate(){this.cache.clear()}render(e,t){if(t.width<=0)return[];let s=[],r=[];for(let u of this.gadgets){if(!u.relevant(e))continue;let p=`${t.border}|${u.versionKey(e,t)}`,h=this.cache.get(u.id),m;if(h!==void 0&&h.key===p)m=h.lines;else{let y=u.render(e,t),w=u.title===void 0?y:[qP(u,e,t),...y];m=y.length===0?[]:t.border==="none"?w:w.map(b=>({...b,gutter:"\u2502"})),this.cache.set(u.id,{key:p,lines:m})}m.length!==0&&(s.push(m),r.push(u))}if(s.length===0)return[];let i=Vp(t.border)?s.length+1:Math.max(0,s.length-1),o=r.map(u=>u!==null&&u.pageSize!==void 0&&u.pageSize>0),a=i+s.reduce((u,p)=>u+p.length-Tl(p),0),d;t.maxRows===void 0?d=Number.NaN:d=WP(s,o,a,t.maxRows);let c=s.map((u,p)=>{let h=r[p],m=h?.pageSize;if(h==null||m===void 0)return u;let y=Number.isNaN(d)?m:d;return jP(h,u,t,y)});s.length=0,s.push(...c);let l=[];if(Vp(t.border)){this.rules?.width!==t.width&&(this.rules={width:t.width,lines:{"\u250C":Yp(t.width,"\u250C"),"\u251C":Yp(t.width,"\u251C"),"\u2514":Yp(t.width,"\u2514")}});let u=this.rules.lines;return l.push(u["\u250C"]),s.forEach((p,h)=>{h>0&&l.push(u["\u251C"]),l.push(...p)}),l.push(u["\u2514"]),l}let f=t.border==="rule"?DP:NP;return s.forEach((u,p)=>{p>0&&l.push(f),l.push(...u)}),l}}});import zP from"string-width";function dS(n,e){if(!n||e<=0)return 0;let t=0;for(let s of KP.segment(n)){let r=zP(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function cS(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 KP,lS=J(()=>{"use strict";KP=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function JP(){sd===0&&process.stdout.write(Gb),sd++}function VP(){sd!==0&&(sd--,sd===0&&process.stdout.write(Yb))}function Be(n){JP();try{n()}finally{VP()}}var sd,Qp=J(()=>{"use strict";Ka();sd=0});import{spawn as GP}from"child_process";import{statSync as uS}from"fs";import{homedir as Pl}from"os";import{isAbsolute as Xp,resolve as fS}from"path";import Xe from"string-width";import YP from"wrap-ansi";function cM(n){let e=n.replace(/\r\n?$|\n$/,"");return dM.test(e)?e:null}function lM(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function uM(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function fM(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],d=i[o];if(a.start!==d.start||a.end!==d.end||a.url!==d.url)return!1}}return!0}function ah(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 d=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}|${d}`}function As(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 d=r[a];if(d===" "||d===" "){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 Hs(n,e,t){let s=0,r=0,i=-1;for(let d=0;d<n.length;d++){let c=n[d];if(!(!c||c.bufferIdx!==e.row)&&(i=d,e.col>=c.startCol&&e.col<c.endCol)){s=d,r=e.col-c.startCol,i=-1;break}}if(i!==-1){let d=n[i];d&&(s=i,r=e.col-d.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 pM(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){xs(n,e,t,o);return}let a=e.toLowerCase(),d=0;for(;d<e.length;){let c=a.indexOf(s,d);if(c===-1){xs(n,e.slice(d),t,o);return}c>d&&xs(n,e.slice(d,c),t,o);let l=r!==null&&c===r;xs(n,e.slice(c,c+s.length),l?"search-highlight-active":"search-highlight",o),d=c+s.length}}function id(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function xs(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,d=>d==="^K"?"\x1B[39m":d);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 hM(n,e){return e<=0?[n]:n.length===0?[""]:YP(n,e,{hard:!0,trim:!1}).split(`
|
|
211
|
-
`)}function IS(n){kS=n}function xS(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
|
|
212
|
-
`);return e===-1?n:`${n.slice(0,e)} \u21B5`}function bS(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${Ol(n.used)}/${Ol(n.size)}`):e.push(Ol(n.used)):typeof n.size=="number"&&e.push(`/${Ol(n.size)}`),typeof n.costAmount=="number"&&e.push(Gf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Ol(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function Nl(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 kr(){let n=[Po,Mo,Wb,_o,zb,Ip,
|
|
213
|
-
`)))}installBracketedPaste(){process.stdout.write(ll),process.stdout.write(jb),process.stdout.write(qb),process.stdout.write(Ub),process.stdout.write(pl);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(
|
|
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],d=t.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{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 No,Rl,Up=J(()=>{"use strict";No=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}invalidate(e,t){this.lastFrameRows.delete(e===void 0?String(t):`${e}:${t}`)}paintRow(e,t,s,r){if(e<1||e>this.term.height)return!1;let i=r?.region,o=i===void 0?String(e):`${i}:${e}`;return this.lastFrameRows.get(o)===t?!1:(this.lastFrameRows.set(o,t),this.term.moveTo(r?.column??1,e),s(),this.term.styleReset(),r?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Rl=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{resolve as gP}from"path";function wP(n){return!yP.has(n)}function bP(n){return n.replace(/\s+/gu," ").trim()}function vP(n,e,t){let s=n.trim();for(let r of[e,t]){if(r===void 0||r==="")continue;let i=s.toLowerCase(),o=r.toLowerCase();if(i===o)return"";i.startsWith(`${o} `)&&(s=s.slice(r.length).trimStart())}return s}function SP(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function kP(n){switch(n){case"read":return"read";case"edit":return"edit";case"delete":return"delete";case"move":return"move";case"search":return"search";case"execute":return"run";case"fetch":return"fetch";case"think":return"think";default:return Gv}}function IP(n,e){if(!wP(n.status))return null;let t=kP(n.rawKind),s=c=>c===void 0?"":vP(bP(c),t,n.rawKind),r=n.editDiff?.path??Jd(n.locations),i=r===void 0||r===""?void 0:e===null?r:gP(e,r),o=s(n.latestTitle),a=t!==Gv&&SP(o)?"":o,d=s(n.detail)||xP(i)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:i}}function xP(n){return n===void 0?"":n.split("/").filter(t=>t!=="").at(-1)??""}function Yv(n,e,t){let s=[];for(let r of n){let i=e.get(r);if(i===void 0)continue;let o=IP(i,t);o!==null&&s.push(o)}return s}var jp,yP,Gv,qp=J(()=>{"use strict";ha();jp=4,yP=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);Gv="tool"});function zp(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;return t<60?`${t}m ${String(s).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function Qv(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function Wp(n){if(n<1e3)return String(n);if(n<1e6){let e=n/1e3;return`${e<10?e.toFixed(1):Math.round(e)}K`}return`${(n/1e6).toFixed(1)}M`}function AP(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),s=Math.round(t*e*8),r=Math.floor(s/8),i=s%8,o=i===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[i-1];return"\u2588".repeat(Math.min(e,r))+(r<e?o:"")+"\xB7".repeat(Math.max(0,e-r-(o?1:0)))}function Ns(n,e){return{body:n,bodyStyle:e}}function Jp(n,e,t){let{cellWidth:s,truncate:r}=t.metrics,i=t.width-s(n)-s(e);return i<1?{body:r(`${n} ${e}`,t.width),bodyStyle:"dim"}:{prefix:`${n}${" ".repeat(i)}`,prefixStyle:"dim",body:e}}function nS(n,e,t,s){let r={body:n,bodyStyle:t,openPath:e,item:!0};if(s!==void 0&&s.length>0){let i=n.indexOf(s);i!==-1&&(r.openSpan={start:i,end:i+s.length})}return r}function Ds(n,e,t){let{cellWidth:s,truncate:r}=t.metrics,i=t.width-s(n)-s(e);return i<1?r(`${n} ${e}`,t.width):`${n}${" ".repeat(i)}${e}`}function sS(n){let e=n.map(s=>s.split("/").pop()??s),t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);return n.map((s,r)=>{let i=e[r];return(t.get(i)??0)<=1?i:s.split("/").slice(-2).join("/")})}function $P(n,e,t){let{cellWidth:s,truncate:r}=t.metrics;if(e<=0)return"";if(s(n)<=e)return n;let i=n.slice(n.lastIndexOf("/")+1);if(i!==n&&s(i)<=e)return i;let o=i.length<n.length?i:n;for(let a=1;a<o.length;a++){let d=`\u2026${o.slice(a)}`;if(s(d)<=e)return d}return r(o,e)}function Zv(n){if(n<1024)return`${Math.max(0,Math.round(n))}B`;let e=n/(1024*1024);return e<1?`${Math.round(n/1024)}K`:e<1024?e<10?`${e.toFixed(1)}M`:`${Math.round(e)}M`:`${(e/1024).toFixed(1)}G`}function tS(n){if(n===void 0)return"\u2013".padStart(eS);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(eS)}var Kp,Xv,CP,RP,TP,EP,PP,MP,_P,FP,eS,OP,rS,iS=J(()=>{"use strict";qp();Kp=5;Xv=5e3,CP={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${Qv(n.now-n.lastTurnEndedAt,Xv)}`:"fresh",render:(n,e)=>n.busySince!==null?[Ns(Ds("\u25CF thinking",zp(n.now-n.busySince),e),"tool-status-running")]:n.lastTurnEndedAt!==null?[Ns(Ds("\u25CB idle",zp(Qv(n.now-n.lastTurnEndedAt,Xv)),e),"dim")]:[Ns("\u25CB ready","dim")]},RP={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,jp);return`${e.width}|${n.running.length}|`+t.map(s=>{let r=s.startedAt===void 0?"":Math.floor(Math.max(0,n.now-s.startedAt)/1e3);return`${s.verb}:${s.detail??""}:${r}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:s}=e.metrics,r=[],i=n.running.slice(0,jp);for(let o of i){let a=o.startedAt===void 0?"":zp(Math.max(0,n.now-o.startedAt)),d=`\u25B8 ${o.verb}`,c=e.width-s(d)-(a===""?0:s(a)+1)-1,l=o.detail===void 0||c<4?"":` ${t(o.detail,c)}`,u=`${d}${l}`,f=a===""?u:Ds(u,a,e),p={body:f,bodyStyle:"tool-status-running",openPath:o.path};if(o.path!==void 0){let h=o.path.slice(o.path.lastIndexOf("/")+1),m=h.length>0?f.indexOf(h):-1;m!==-1&&(p.openSpan={start:m,end:m+h.length})}r.push(p)}return n.running.length>i.length&&r.push(Ns(` +${n.running.length-i.length} more`,"dim")),r}},TP={id:"context",title:"context",relevant:n=>n.usage.used!==void 0||n.usage.costAmount!==void 0,versionKey:(n,e)=>`${n.usage.used??""}/${n.usage.size??""}/${n.usage.costAmount??""}/${e.width}`,render:(n,e)=>{let t=[],{used:s,size:r,costAmount:i,costCurrency:o}=n.usage;if(s!==void 0&&r!==void 0&&r>0){let a=s/r;t.push(Ns(Ds(`${Wp(s)}/${Wp(r)}`,`${Math.round(a*100)}%`,e),a>=.9?"tool-status-fail":"info")),t.push(Ns(AP(a,e.width),a>=.9?"tool-status-fail":"plan-done"))}else s!==void 0&&t.push(Ns(Ds("tokens",Wp(s),e),"info"));if(i!==void 0){let a=o==="USD"||o===void 0?"$":`${o} `;t.push(Ns(Ds("cost",`${a}${i.toFixed(2)}`,e),"dim"))}return t}},EP={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[Ns(Ds("queued",String(n.queued),e),"tool-status-pending")]},PP={id:"todo",title:"todo",pageSize:Kp,relevant:n=>n.plan.length>0,titleNote:n=>`${n.plan.filter(e=>e.status==="completed").length}/${n.plan.length}`,versionKey:(n,e)=>`${e.width}|`+n.plan.map(t=>`${t.status}:${t.content}`).join("\0"),render:(n,e)=>{let{truncate:t}=e.metrics,s=[];for(let r of n.plan){let i=r.status==="completed"?"\u2713":r.status==="in_progress"?"\u25B8":"\xB7",o=r.status==="completed"?"plan-done":r.status==="in_progress"?"plan":"plan-pending";s.push({body:t(`${i} ${r.content}`,e.width),bodyStyle:o,item:!0})}return s}};MP={id:"files",title:"edited",pageSize:Kp,relevant:n=>n.editedFiles.length>0,titleNote:n=>n.editedFiles.length>1?`${n.editedFiles.length} files`:void 0,versionKey:(n,e)=>`${e.width}|`+n.editedFiles.map(t=>`${t.path}:${t.added??""}:${t.removed??""}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:s}=e.metrics,r=[...n.editedFiles].reverse(),i=[],o=sS(r.map(a=>a.path));return r.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?s(c)+1:0),u=t(o[d],Math.max(1,l));i.push(nS(c?Ds(u,c,e):u,a.path,"tool",u))}),i}},_P={id:"git",title:"git",pageSize:Kp,relevant:n=>n.git!==null&&(n.git.staged>0||n.git.unstaged>0||n.git.untracked>0||n.git.ahead>0||n.git.behind>0),titleNote:n=>n.git!==null&&n.git.files.length>1?`${n.git.files.length} files`:void 0,versionKey:(n,e)=>{let t=n.git;if(t===null)return"none";let s=t.files.map(r=>`${r.state}:${r.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${s}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:s,cellWidth:r}=e.metrics,i=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");i.push(d?Jp(s(t.branch,e.width-d.length-1),d,e):{body:s(t.branch,e.width)})}let o=t.files,a=sS(o.map(d=>d.path));return o.forEach((d,c)=>{let l=d.state==="staged"?"plan-done":d.state==="dirty"?"tool":"plan-pending",u=e.width-r(d.state)-1,f=s(a[c],Math.max(1,u));i.push(nS(Ds(f,d.state,e),d.path,l,f))}),i}};FP={id:"session",title:"session",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.sessionId}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,s=[],r=(i,o)=>{let a=e.width-t(i)-1;s.push(Jp(i,$P(o,a,e),e))};return n.agent!==null&&r("agent",n.agent),n.model!==null&&r("model",n.model),n.mode!==null&&r("mode",n.mode),n.sessionId!==null&&r("id",n.sessionId),s}};eS=5;OP={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${Zv(t.rssBytes)}:${tS(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:s}=e.metrics;return n.resources.map(r=>{let i=`${Zv(r.rssBytes)} ${tS(r.cpuFraction)}`,o=r.processes>1?`${r.label} \xD7${r.processes}`:r.label,a=e.width-t(i)-1;return Jp(s(o,Math.max(1,a)),i,e)})}},rS=[CP,TP,EP,PP,MP,_P,OP,FP,RP]});function Vp(n){return n==="frame"}function oS(n=0){return{now:n,busySince:null,lastTurnEndedAt:null,queued:0,usage:{},plan:[],editedFiles:[],running:[],git:null,resources:[],sessionId:null,agent:null,model:null,mode:null}}var Gp=J(()=>{"use strict"});function BP(n){return rS.find(e=>e.id===n)}function Yp(n,e){return{body:"\u2500".repeat(Math.max(0,n)),bodyStyle:"dim",gutter:e}}function jP(n,e,t,s){if(s<=0||!Number.isFinite(s))return e;let r=Tl(e);if(r<=s)return e;let i=Math.ceil(r/s),o=t.pages?.[n.id]??0,a=Math.max(0,Math.min(i-1,o)),d=a*s,c=d+s,l=[],u=0;for(let _ of e){if(_.item!==!0){l.push(_);continue}let H=u++;H>=d&&H<c&&l.push(_)}if(n.title===void 0||l.length===0)return l;let{cellWidth:f,truncate:p}=t.metrics,h=`${HP} ${a+1}/${i} ${UP}`,m=f(h),y=t.width-m-1;if(y<1)return l;let w=p(n.title,y),b=t.width-f(w)-m,v=`${w}${" ".repeat(Math.max(1,b))}${h}`,k=f(v)-m+1,A=f(v),E=[];return a>0&&E.push({start:k,end:k,page:{gadget:n.id,index:a-1}}),a<i-1&&E.push({start:A,end:A,page:{gadget:n.id,index:a+1}}),l[0]={...l[0],body:v,actions:E},l}function Tl(n){return n.reduce((e,t)=>e+(t.item===!0?1:0),0)}function qP(n,e,t){let s=n.title??"",r=n.titleNote?.(e,t);if(r===void 0||r.length===0)return{body:s,bodyStyle:"dim"};let{cellWidth:i,truncate:o}=t.metrics,a=i(r),d=t.width-a-1;if(d<1)return{body:o(s,t.width),bodyStyle:"dim"};let c=o(s,d),l=t.width-i(c)-a;return{body:`${c}${" ".repeat(Math.max(1,l))}${r}`,bodyStyle:"dim"}}function WP(n,e,t,s){let r=n.map((c,l)=>e[l]?Tl(c):0),i=n.reduce((c,l,u)=>c+(e[u]?0:Tl(l)),0),o=c=>t+i+r.reduce((l,u)=>l+Math.min(u,c),0),a=Math.max(0,...r);if(o(a)<=s)return Number.POSITIVE_INFINITY;let d=1;for(let c=1;c<=a&&o(c)<=s;c++)d=c;return d}var LP,NP,DP,HP,UP,El,aS=J(()=>{"use strict";iS();Gp();LP=["activity","context","queue","todo","files","git","resources","session","tools"];NP=Object.freeze({body:""}),DP=Object.freeze({body:"",gutter:"\u2502"});HP="\u2039",UP="\u203A";El=class{cache=new Map;rules=null;gadgets=[];constructor(e=LP){this.setGadgets(e)}setGadgets(e){let t=e.map(r=>BP(r)).filter(r=>r!==void 0);(t.length!==this.gadgets.length||t.some((r,i)=>r!==this.gadgets[i]))&&(this.gadgets=t,this.cache.clear())}configuredIds(){return this.gadgets.map(e=>e.id)}isConfigured(e){return this.gadgets.some(t=>t.id===e)}invalidate(){this.cache.clear()}render(e,t){if(t.width<=0)return[];let s=[],r=[];for(let f of this.gadgets){if(!f.relevant(e))continue;let p=`${t.border}|${f.versionKey(e,t)}`,h=this.cache.get(f.id),m;if(h!==void 0&&h.key===p)m=h.lines;else{let y=f.render(e,t),w=f.title===void 0?y:[qP(f,e,t),...y];m=y.length===0?[]:t.border==="none"?w:w.map(b=>({...b,gutter:"\u2502"})),this.cache.set(f.id,{key:p,lines:m})}m.length!==0&&(s.push(m),r.push(f))}if(s.length===0)return[];let i=Vp(t.border)?s.length+1:Math.max(0,s.length-1),o=r.map(f=>f!==null&&f.pageSize!==void 0&&f.pageSize>0),a=i+s.reduce((f,p)=>f+p.length-Tl(p),0),d;t.maxRows===void 0?d=Number.NaN:d=WP(s,o,a,t.maxRows);let c=s.map((f,p)=>{let h=r[p],m=h?.pageSize;if(h==null||m===void 0)return f;let y=Number.isNaN(d)?m:d;return jP(h,f,t,y)});s.length=0,s.push(...c);let l=[];if(Vp(t.border)){this.rules?.width!==t.width&&(this.rules={width:t.width,lines:{"\u250C":Yp(t.width,"\u250C"),"\u251C":Yp(t.width,"\u251C"),"\u2514":Yp(t.width,"\u2514")}});let f=this.rules.lines;return l.push(f["\u250C"]),s.forEach((p,h)=>{h>0&&l.push(f["\u251C"]),l.push(...p)}),l.push(f["\u2514"]),l}let u=t.border==="rule"?DP:NP;return s.forEach((f,p)=>{p>0&&l.push(u),l.push(...f)}),l}}});import zP from"string-width";function dS(n,e){if(!n||e<=0)return 0;let t=0;for(let s of KP.segment(n)){let r=zP(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function cS(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 KP,lS=J(()=>{"use strict";KP=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function JP(){sd===0&&process.stdout.write(Gb),sd++}function VP(){sd!==0&&(sd--,sd===0&&process.stdout.write(Yb))}function Be(n){JP();try{n()}finally{VP()}}var sd,Qp=J(()=>{"use strict";Ka();sd=0});import{spawn as GP}from"child_process";import{statSync as uS}from"fs";import{homedir as Pl}from"os";import{isAbsolute as Xp,resolve as fS}from"path";import Xe from"string-width";import YP from"wrap-ansi";function cM(n){let e=n.replace(/\r\n?$|\n$/,"");return dM.test(e)?e:null}function lM(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function uM(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function fM(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??"")||(n.maxWrapRows??0)!==(e.maxWrapRows??0)||(n.hangingIndent??0)!==(e.hangingIndent??0))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],d=i[o];if(a.start!==d.start||a.end!==d.end||a.url!==d.url)return!1}}return!0}function ah(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 d=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}|${d}`}function xs(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 d=r[a];if(d===" "||d===" "){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 Us(n,e,t){let s=0,r=0,i=-1;for(let d=0;d<n.length;d++){let c=n[d];if(!(!c||c.bufferIdx!==e.row)&&(i=d,e.col>=c.startCol&&e.col<c.endCol)){s=d,r=e.col-c.startCol,i=-1;break}}if(i!==-1){let d=n[i];d&&(s=i,r=e.col-d.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 pM(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Is(n,e,t,o);return}let a=e.toLowerCase(),d=0;for(;d<e.length;){let c=a.indexOf(s,d);if(c===-1){Is(n,e.slice(d),t,o);return}c>d&&Is(n,e.slice(d,c),t,o);let l=r!==null&&c===r;Is(n,e.slice(c,c+s.length),l?"search-highlight-active":"search-highlight",o),d=c+s.length}}function id(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function Is(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,d=>d==="^K"?"\x1B[39m":d);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 hM(n,e){return e<=0?[n]:n.length===0?[""]:YP(n,e,{hard:!0,trim:!1}).split(`
|
|
211
|
+
`)}function IS(n){kS=n}function xS(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 Hs(n){return Xe(n,{ambiguousIsNarrow:!kS})}function gM(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 yM(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=gM(n,e);if(s!==null)return{text:s,width:0};let r=yM(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 mM.test(t)?{text:n.slice(e,e+2),width:0}:null}function Ll(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 wM(n){let{clean:e,rawToClean:t}=Ll(n),s=new Array(e.length+1).fill(n.length);for(let r=n.length;r>=0;r--){let i=t[r];i!==void 0&&(s[i]=r)}return s}function dh(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 ch(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 lh(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 bM(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 AS(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 gS(n,e){let t=n.indexOf("^",e),s=n.indexOf("\x1B",e);return t===-1?s:s===-1?t:Math.min(t,s)}function*fh(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=gS(n,e);for(;r!==-1&&r<n.length;){if(Jn(n,r)){s=r;break}r=gS(n,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of uh.segment(n.slice(e,s)))yield{text:i,width:Hs(i)};e=s}}function vM(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 SM(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let s=t.stripMarkup===!0&&AS(n);return!s&&!SS.test(n)?kM(n,e):IM(n,e,s)}function kM(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 IM(n,e,t){let s=[],r=t?[...fh(n)]:xM(n),i=0;for(;i<r.length;){let o="",a=0,d=-1,c="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(d=i,c=o);break}l.text===" "&&l.width===1&&(d=i,c=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}d>=0?(s.push(c),i=d+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function xM(n){let e=[];for(let{segment:t}of uh.segment(n))e.push({text:t,width:Hs(t)});return e}function kt(n,e,t={}){if(e<=0)return"";let s=t.stripMarkup===!0&&AS(n);if(!s&&n.length<=e&&!SS.test(n))return n;if(!s)return Hs(n)<=e?n:e<=1?yS(n,e):yS(n,e-1)+"\u2026";let r=[...fh(n)],i=0;for(let o of r)i+=o.width;return i<=e?n:e<=1?wS(r,e):wS(r,e-1)+"\u2026"}function yS(n,e){if(e<=0)return"";let t="",s=0;for(let{segment:r}of uh.segment(n)){let i=Hs(r);if(s+i>e)break;t+=r,s+=i}return t}function wS(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 AM(n){let e=n.indexOf(`
|
|
212
|
+
`);return e===-1?n:`${n.slice(0,e)} \u21B5`}function bS(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${Ol(n.used)}/${Ol(n.size)}`):e.push(Ol(n.used)):typeof n.size=="number"&&e.push(`/${Ol(n.size)}`),typeof n.costAmount=="number"&&e.push(Gf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Ol(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function Nl(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 kr(){let n=[Po,Mo,Wb,_o,zb,Ip,Os,ui,fi,li,ci,"\x1B>",Wa,ul,fl,"\x1B]9;4;0\x07",Hb].join("");try{process.stdout.write(n)}catch{}}function CS(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 vS(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 Ml,_l,$l,pS,Zp,eh,QP,hS,XP,Qe,rt,ZP,it,th,mS,eM,rd,nh,tM,nM,sh,sM,rM,iM,rh,ih,oh,oM,aM,dM,Bl,SS,uh,kS,mM,Fl,ph=J(()=>{"use strict";Up();aS();Gp();Yf();we();ps();Il();oi();lS();Cl();Qp();Vr();Ka();Ml=500,_l=1,$l=/[A-Za-z0-9_:\-]/,pS=/[:\-]/,Zp=/[A-Za-z0-9_./\-~+@]/,eh=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,QP=/[.,;:!?)\]}'"]/,hS=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,XP=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Qe=1,rt=0,ZP=1,it=1,th=8,mS=20,eM=36,rd=2,nh=1,tM=80,nM=12,sh=5,sM=12,rM=12,iM=30,rh=6,ih=4,oh=2,oM=1e3,aM=1e4,dM=/^(https?|ftp):\/\/\S+$/;Bl=class n{term;dispatcher;onKey;onBlockClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;onLayoutChange;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;sidebarVisible=!1;sidebarConfiguredWidth=null;sidebarRenderer=new El;sidebarBorder="frame";sidebarSnapshot=oS();sidebarRowPaths=new Map;sidebarRowActions=new Map;sidebarPages={};lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;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.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??oM,this.painter=new No(this.term),this.scheduler=new Rl({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??aM,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.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),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(kp),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),re({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),re({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(fl),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Wa),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(kr(),this.term.fullscreen(!1),this.term(`
|
|
213
|
+
`)))}installBracketedPaste(){process.stdout.write(ll),process.stdout.write(jb),process.stdout.write(qb),process.stdout.write(Ub),process.stdout.write(pl);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(ui),process.stdout.write(fi),process.stdout.write(li),process.stdout.write(za),process.stdout.write(ci),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(Kb),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(Ip),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>kr(),this.onProcessSignal=e=>{kr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{kr(),process.stderr.write(`
|
|
214
214
|
uncaught: ${e.stack??e.message}
|
|
215
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(Jb),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(" ");re({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(Eo)){this.handleRawStdinSegment(t);return}if(t.includes(`
|
|
216
216
|
`)){let s=t.split(`
|
|
217
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=vS(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=vS(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=Eo,s=qa;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=jv(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=cM(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.contentWidth()}termWidth(){return this.term.width||0}sidebarReserved(){if(!this.sidebarVisible)return 0;let e=this.term.width||0;if(e<tM)return 0;let t=this.sidebarConfiguredWidth??Math.min(eM,Math.max(mS,Math.floor(e*.28))),s=e-nM-rd-nh;return Math.min(t,Math.max(mS,s))+rd+nh}sidebarOverlay(){let e=this.sidebarReserved();return e>0&&e*2>(this.term.width||0)}sidebarColumnStart(){let e=this.sidebarReserved();return e===0?0:(this.term.width||0)-e+1}contentWidth(){let e=this.term.width||0;return this.sidebarOverlay()?e:Math.max(0,e-this.sidebarReserved())}transcriptVisibleWidth(){let e=this.sidebarColumnStart();return e===0?this.contentWidth():e-1}sidebarBodyWidth(){let e=this.sidebarReserved();return e===0?0:e-rd-nh}isSidebarVisible(){return this.sidebarVisible}isSidebarSuppressed(){return this.sidebarVisible&&this.sidebarReserved()===0}isSidebarOverlay(){return this.sidebarOverlay()}setSidebarVisible(e){this.sidebarVisible!==e&&(this.sidebarVisible=e,this.lastSidebarClick=null,this.sidebarRowPaths.clear(),this.sidebarRowActions.clear(),this.sidebarPages={},this.sidebarScrollOffset=0,this.sidebarOverflowRows=0,this.sidebarRenderer.invalidate(),this.painter.clearCache())}toggleSidebar(){return this.setSidebarVisible(!this.sidebarVisible),this.sidebarVisible}setSidebarGadgets(e){this.sidebarRenderer.setGadgets(e),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}setSidebarBorder(e){this.sidebarBorder!==e&&(this.sidebarBorder=e,this.sidebarRenderer.invalidate(),this.painter.clearCache(),this.scheduleRepaint())}setSidebarWidth(e){this.sidebarConfiguredWidth=e,this.painter.clearCache()}setSidebarSnapshot(e){this.sidebarSnapshot={...this.sidebarSnapshot,...e},this.sidebarVisible&&this.scheduleRepaint()}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.contentWidth();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)),d=t.length-s.count,c=this.lines.slice(s.start,o),l=new Array(t.length),
|
|
219
|
-
`),[o,...a]=i,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let
|
|
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 d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=c===r?Math.max(0,Math.min(u,o)):0,h=c===i?Math.max(0,Math.min(u,a)):u;d.set(f,{start:p,end:h,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}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,d=Math.max(r.start,i),c=Math.min(r.end,a);if(c<=d)return null;let l,f;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let p=dh(u,i,d),h=dh(u,d,c);l=ch(e.body,o,p),f=ch(e.body,l,h)}else l=d-i+o,f=c-i+o;return{start:l,end:f,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,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.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(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!t.has(l)&&f.start>=d&&f.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,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 d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(kp),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&&re({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=Nl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let l=e==="MOUSE_WHEEL_UP"?3:-3,f=this.mouseCell(t);if(f!==null&&this.isSidebarCell(f.x,f.y)&&this.scrollSidebarBy(l))return;this.scrollBy(l);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=uM(e),d=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&o!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:o.x,y:o.y,name:e}),d==="move"){let l=o!==null?this.bannerHitAt(o.x,o.y):null;l!==this.hoveredBannerHit&&(this.hoveredBannerHit=l,this.syncedPartialRepaint(()=>this.drawBanner()))}let c=o!==null&&o.x>=1&&o.x<=this.transcriptVisibleWidth();if(o!==null&&c&&d!=="release"){let l=this.keyAndSubAtRow(o.y),f=l!==null&&l.key.startsWith("agent:")?null:l;if(f===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let u=this.nearestKeyAboveRow(o.y),p=this.nearestKeyBelowRow(o.y);u!==null&&p!==null&&this.hoveredRunKeys.has(u)&&this.hoveredRunKeys.has(p)&&(f={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(f!==null?"pointer":"default"),d==="move"){let u=f?.key??null,p=f?.sub??null;(u!==this.hoveredBlockKey||p!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=p,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(o!==null&&!c&&this.setPointerShape("default"),(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 l=this.lastLeftClick;if(l!==null&&o!==null&&Math.abs(o.x-l.x)<=_l&&Math.abs(o.y-l.y)<=_l&&Date.now()-l.t<=Ml||this.flushPendingBlockClick(),this.handleSidebarPress(o)){this.pressCell=null,this.clearSelection();return}this.pressCell=o,this.handleSelectionPress(o,lM(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 l=this.pressCell;this.pressCell=null;let f=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(l!==null&&o!==null&&o.x===l.x&&o.y===l.y&&!f){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 p=this.keyAtRow(o.y);if(p!==null){let h=o.y;for(;h>1&&this.keyAtRow(h-1)===p;)h-=1;this.schedulePendingBlockClick(p,o.y-h)}}}(o===null||!this.isSidebarCell(o.x,o.y))&&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<=Ml&&Math.abs(e.x-i.x)<=_l&&Math.abs(e.y-i.y)<=_l&&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.tryOpenLinkAt(s,e?.y??null)){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 c=this.wordBoundsAt(s);c!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:c.start},{sourceLineId:s.sourceLineId,offset:c.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.contentWidth(),{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=c<d;if(c===0&&l||u){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(c>=t-1&&f){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let i=1;i<s;i++){let o=t-i;if(o>=1){let d=this.resolveCellToSource(r,o);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+i;if(a<=s){let d=this.resolveCellToSource(r,a);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}=Ll(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),!$l.test(r[a])&&!eh.test(r[a]))return null;let d=a;for(;d>0&&eh.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&eh.test(r[c]);)c++;for(;c>d+1&&QP.test(r[c-1]);)c--;if(r.slice(d,c).includes("://")){let p=d,h=c;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!$l.test(r[a]))return null;let f=a;for(;f>0&&$l.test(r[f-1]);)f--;let u=a+1;for(;u<r.length&&$l.test(r[u]);)u++;for(;u>f+1&&pS.test(r[u-1]);)u--;for(;f<u-1&&pS.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,f,u)}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}=Ll(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),!Zp.test(r[a]))return null;let d=a;for(;d>0&&Zp.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&Zp.test(r[c]);)c++;let l=r.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=r.slice(c).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||!t.links||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Ll(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}osc8UrlFor(e){if(hS.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let t=e.indexOf("#"),s=t===-1?e:e.slice(0,t),r=t===-1?"":e.slice(t);if(s.length===0)return null;let i=s;return s==="~"||s.startsWith("~/")?i=s==="~"?Pl():`${Pl()}/${s.slice(2)}`:Xp(s)||(i=fS(this.sessionbar.cwd,s)),ep(i+r)}linkSpansForWindow(e,t,s,r,i){let o=wM(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=o[d.start]??e.length,f=o[d.end]??e.length,u=Math.max(l,s),p=Math.min(f,r);p>u&&a.push({start:u-s+i,end:p-s+i,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Pl():`${Pl()}/${t.slice(2)}`);let s=Xp(t)||e.startsWith("~"),r=Xp(t)?t:fS(this.sessionbar.cwd,t);if(s)return r;try{if(uS(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(!XP.test(s))return!1;let r=s.startsWith(zt)?[s]:[zt+s,s],i=null;for(let o of r)try{if(uS(O.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}dispatchLinkUrl(e){let t=e.match(hS);if(t){let i=t[1]??null;return i!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(i):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let s=e;if(s.startsWith("file://")){let i=s.slice(7),o=i.indexOf("/");s=o===-1?"":i.slice(o);try{s=decodeURIComponent(s)}catch{}}if(s.length===0)return!1;let r=s.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return r?this.tryOpenPathString(`${r[1]}:${r[2]}`):this.tryOpenPathString(s)}tryOpenLinkAt(e,t){let s=this.findLinkUrlAt(e);if(s!==null)return this.dispatchLinkUrl(s);let i=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(i!==void 0)return this.dispatchLinkUrl(i);if(t!==null){let o=this.blockLinkUrlAt(t);if(o!==null)return this.dispatchLinkUrl(o)}return!1}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,...d]=this.openFileCommand;if(!a)return!1;let c=!1,l=[];for(let f of d)f.includes("%f")&&(c=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));c||l.push(i);try{let f=GP(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,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)},Ml);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&&Kv(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"?Vb:fl))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null)return null;let s=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return null;let{rows:i}=this.wrapTail(s,r+this.scrollOffset);for(let o of i)if(o.blockKey===t&&o.linkSpans!==void 0&&o.linkSpans.length>0)return o.linkSpans[0]?.url??null;return null}keyAtRow(e){let t=this.contentWidth(),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,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}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.contentWidth(),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,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;if(f<0||f>=c.length)return null;let u=c[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let s=this.contentWidth(),r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-r;if(o<0||o>=i||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=Ds(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=id(p.bodyStyle)||p.ansi===!0?cS(fh(p.body),b):dS(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=dh(p.body,y,k),P=ch(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=[],d=0;for(;d<o.length;){let c=o.indexOf(t,d);if(c===-1)break;a.push(c),d=c+t.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=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.contentWidth(),s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,t).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,t),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let h=p.body.length;if(e.col<f+h){o=l.length-1-u;break}f+=h}}let a=r+o,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Qe-it-rt-ZP-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,t,s,r){return this.started?this.painter.paintRow(e,t,s,r):!1}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),Be(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-rt-it-Qe;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Qe),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=Ww(this.sessionbar.agent,this.sessionbar.model),i=lt(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Xe(r),d=1,c=Math.max(0,e-a-d),l=s?" \xB7 ":"",f=Xe(l),u,p;if(s){let b=Math.min(s.length,8);u=Math.min(i.length,Math.max(8,c-f-b)),p=Math.max(0,c-u-f)}else p=0,u=c;let h=Tt(i,u),m=s?Tt(s,p):"",y=Xe(h)+(s?f+Xe(m):0),w=Math.max(d,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=Fl(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?vs(this.banner.elapsedMs):"",d=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;d.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;d.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let c=bS(this.sessionbar.usage)??"",l="\u2500\u2500 ",f=a?` ${a}`:"",u=s?" \xB7 ":"",p=" ",h=c?" ":"",m=c?" \u2500\u2500":"\u2500\u2500",y=l.length+Xe(o)+Xe(f)+u.length+Xe(s);for(let A of d)y+=Xe(" \xB7 ")+Xe(A.text);y+=Xe(p);let w=Xe(h)+Xe(c)+Xe(m),b=Math.max(0,t-y-w),v="\u2500".repeat(b),k=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${c}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),f&&(i?this.term.brightRed.noFormat(f):r==="busy"?this.term.brightYellow.noFormat(f):this.term.dim.noFormat(f)),s&&(this.term.dim(u),this.term.dim(s));for(let A of d)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(v),c&&(this.term.dim(h),this.term.noFormat(c)),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,d=Xe(i)+Xe(a)+Xe(o),c=Math.max(0,t-d),l="\u2500".repeat(c),f=s?`${s.kind}|${s.text}`:"",u=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${t}|${this.banner.currentMode??""}|${this.banner.hint}|${f}|${u}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.terminalFocused?this.hoveredBannerHit:null;for(let w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let b=m[w];if(b===void 0)continue;let v=null;b.includes("mode")?v="mode":b.includes("pick")?v="pick":b.includes("guide")?v="guide":b.includes("detach")&&(v="detach"),v!==null&&v===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=c+Xe(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Xe(w),v=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=v:w.includes("pick")&&h.pick===null?h.pick=v:w.includes("guide")&&h.guide===null?h.guide=v:w.includes("detach")&&h.detach===null&&(h.detach=v),m+=b+Xe(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Fl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=bS(this.btwOverlayUsage),d=a?` ${a} `:"",c=a?"\u2500\u2500":"",l=s.length+Xe(t)+i.length+Xe(r)+o.length+Xe(d)+c.length,f="\u2500".repeat(Math.max(0,e-l)),u=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:t,sidSep:i,sid:r,sidTrail:o,middle:f,usage:d,right:c,signature:u}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-rt-it-Qe,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",d="\u2500\u2500 ",c=Fl(this.btwOverlaySessionId),f=1+d.length+Xe(a)+" \xB7 ".length,u=f+Xe(c)-1;return{row:o,colStart:f,colEnd:u,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),s=this.sidebarBodyWidth()>0,r=1,i=this.scrollbackVisibleRows();if(i<=0)return;let{rows:o,exhausted:a}=this.wrapTail(e,i+this.scrollOffset);if(a){let y=Math.max(0,o.length-i);this.scrollOffset>y&&(this.scrollOffset=y)}let d=o.length-this.scrollOffset,c=Math.max(0,d-i),l=o.slice(c,d),f=Math.max(0,i-l.length),u=this.currentMatchInfo(),p=u?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let h=-1,m=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let y=0;y<l.length;y++){let w=l[y]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(h===-1&&(h=y),m=y)}for(let y=0;y<i;y++){let w=r+y,b=y-f,v=b>=0?l[b]:void 0,k=this.activeMatchCol(v,u),A=v?this.selectionRangeForChunk(v):null,E=v!==void 0&&v.blockKey!==void 0&&(v.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(v.blockKey)),P=v!==void 0&&v.blockKey===void 0&&h!==-1&&b>=h&&b<=m,H=E||P,_=this.terminalFocused&&H&&(this.hoveredSubKey===null||(v.hoverSubKey??null)===this.hoveredSubKey),F=ah("sb",e,v,this.scrollbackHighlight,k,A)+(_?"|H":"");this.paintRow(w,F,()=>{v?this.writeFormattedLine(v,e,k,p,A,_,t,v.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&s&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let y=new Set;for(let b of l)b.blockKey!==void 0&&y.add(b.blockKey);let w=[];for(let b of this.pendingVisibleKeys)y.has(b)&&w.push(b);for(let b of w)this.pendingVisibleKeys.delete(b),this.onBlockVisible(b)}}drawSidebar(e,t){let s=this.sidebarBodyWidth();if(s<=0||t<=0){this.sidebarOverflowRows=0;return}let r=this.sidebarColumnStart(),i={metrics:{cellWidth:Ds,truncate:Tt},width:s,border:this.sidebarBorder,pages:this.sidebarPages,maxRows:t},o={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(o,i);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowActions.clear();let c=r+rd;for(let l=0;l<t;l++){let f=e+l,u=l+d,p=a[u];p?.openPath!==void 0&&this.sidebarRowPaths.set(f,p.openPath),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(f,p.actions.map(w=>({start:c+w.start-1,end:c+w.end-1,gadget:w.page.gadget,index:w.page.index})));let h=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",m=p?.openPath===void 0||!p.openPath.startsWith("/")||p.openSpan===void 0?null:[{...p.openSpan,url:ep(p.openPath)}],y=ah("sbar",s,p,null,null,null)+`|${h}|${m===null?"":m.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(f,y,()=>{this.term(" ".repeat(Math.max(0,rd-1))),h===" "?this.term(" "):xs(this.term,h,"dim",!1),p?this.writeFormattedLine(p,s,null,0,null,!1,!0,m):this.term(" ".repeat(s))},{region:"sidebar",column:r})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let t=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return t===this.sidebarScrollOffset||(this.sidebarScrollOffset=t,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,t){let s=this.sidebarColumnStart();return s===0?!1:e>=s&&e<=(this.term.width||0)&&t>=1&&t<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let i of this.sidebarRowActions.get(e.y)??[])if(e.x>=i.start&&e.x<=i.end)return this.sidebarPages={...this.sidebarPages,[i.gadget]:i.index},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),s=this.lastSidebarClick;if(s!==null&&t-s.t<=Ml&&e.y===s.y){this.lastSidebarClick=null;let i=this.sidebarRowPaths.get(e.y);return i!==void 0&&!this.dispatchLinkUrl(i)&&this.notify(this.hasOpenFileCommand()?`can't open ${i}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(sh,this.queuedTexts.length)}chipRows(){return Math.min(ih,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(rh,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-Qe-it-rt,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>rh,h=this.completions.length-rh+1,m=u?p?`comp|${t}|overflow|${h}`:`comp|${t}|${c}|${u.name}|${u.description??""}`:`comp|${t}|empty`;this.paintRow(f,m,()=>{if(!u)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=u.name.padEnd(c),w=u.description??"",b=t-y.length-4,v=b>0?Tt(w,b):"";this.term(" ").brightCyan(y),v.length>0&&this.term(" ").dim(v)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Qe-it-rt-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>ih,f=this.attachments.length-ih,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${Fn(u.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${f}`:u?`chip|${t}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${t}|empty`;this.paintRow(c,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,t){process.stdout.write(vM(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-Qe-it-rt,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>sh,p=this.queuedTexts.length-sh,h=f===void 0?"":u?`+ ${p+1} more queued`:Tt(AM(f),t-4),m=!u&&c===d,y=f===void 0?`queued|${t}|empty`:`queued|${t}|${m?"edit":u?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${h}`,b=w+" ".repeat(Math.max(0,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=As(s.buffer,t),i=Hs(r,s,th),o=this.term.height-i.rendered-rt-it-Qe+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,f="wrap",u="";c&&(c.bufferIdx===0&&c.startCol===0?f="first":c.startCol===0&&(f="newline"),u=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(f==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):f==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(u):this.term.noFormat(u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,s=this.term.height-oh-rt-it-Qe+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${Tt(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${Tt(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-rt-it-Qe+1,i=r,o=(a,d)=>{i>=r+s||(this.paintRow(i,a,d),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${Tt(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 d=e.options[a];if(!d)continue;let c=a===e.selectedIndex,f=` ${c?"\u276F":" "} ${a+1}. ${Tt(d.label,t-8)}`;o(`cpct|o|${t}|${a}|${c?"1":"0"}|${d.label}`,()=>{c?this.term.brightYellow(f):this.term.dim(f)})}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-rt-it-Qe+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${Tt(e.title,t-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${t}|${i}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);o(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${Tt(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${Tt(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(iM,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-rt-it-Qe+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${Tt(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(` ${Tt(a,t-2)}`)}),o(`perm|q|${t}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. ${Tt(c.label,t-8)}`;o(`perm|o|${t}|${d}|${l?"1":"0"}|${c.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}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-rt-it-Qe;this.drawSeparator(s),this.drawBottomSeparator(e-Qe)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-rt-it-Qe+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-rt-it-Qe+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-oh-rt-it-Qe+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-rt-it-Qe+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-rt-it-Qe+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=As(s.buffer,t),i=Hs(r,s,th),a=this.term.height-i.rendered-rt-it-Qe+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-rt-it-Qe;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return oh;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=As(s.buffer,t);return Math.min(th,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(sM,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(rM,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-rt-it-Qe+1,i=r,o=(c,l)=>{i>=r+s||(this.paintRow(i,c,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${Tt(e.title,t-5)}`)});let a=Math.max(...e.options.map(c=>c.label.length),0);for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let l=e.options[c];if(!l)continue;let f=c===e.selectedIndex,p=` ${f?"\u276F":" "} ${c+1}. `,h=l.label.padEnd(a),m=t-p.length-3,y=`${p}${Tt(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${c}|${f?"1":"0"}|${l.value}|${l.label}`,()=>{f?this.term.brightYellow(y):this.term.dim(y)})}let d=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${t}|${d}`,()=>{this.term.dim(` ${d}`)})}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],d=this.wrapOne(a,e);if(s.push(d),r+=d.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()-rt-it-Qe,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a,l=this.buildBtwHeaderSegments();this.paintRow(c,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let f=this.wrapBtwTail(t,d);for(let u=0;u<d;u++){let p=c+1+u,h=f.length-d+u,m=h>=0?f[h]:void 0,y=ah(`btw|c${u}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){let s=c=>c.collapsed===!0||this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let f of this.lines)s(f)||c.push(f);let l=Math.min(t,c.length);return{rows:c.slice(c.length-l),exhausted:t>=c.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 c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),i+=f.length,o=c,i>=t)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:o===0||a}}wrapOne(e,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=Ds(r),o=Math.max(1,t-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),d=Math.max(1,o-a),c=id(e.bodyStyle),l=e.ansi?hM(e.body,a>0?d:o):SM(e.body,a>0?d:o,{stripMarkup:c}),f=[],u=0,p=0;for(let h=0;h<l.length;h++){let m=l[h]??"",y=h===0||a===0?m:" ".repeat(a)+m,w={prefix:h===0?e.prefix:" ".repeat(i),body:y};if(e.prefixStyle!==void 0&&(w.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(w.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(w.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(w.hoverSubKey=e.hoverSubKey),e.fillRow&&(w.fillRow=!0),e.ansi&&(w.ansi=!0),h===0&&e.iterm2Image&&(w.iterm2Image=e.iterm2Image),s!==void 0&&m.length>0)if(e.ansi){let b=u,v=0;for(let P=0;P<m.length;){let H=Jn(m,P);if(H){P+=H.text.length,H.width>0&&(v+=1);continue}v+=1,P+=1}let k=v;for(;k>0&&u<e.body.length;){let P=Jn(e.body,u);if(P){u+=P.text.length,P.width>0&&(k-=1);continue}u+=1,k-=1}let A=u;if(h===l.length-1){for(;A<e.body.length;){let P=Jn(e.body,A);if(!P)break;A+=P.text.length}u=A}let E={sourceLineId:s,sourceColOffset:b,sourceColEnd:A};if(h>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(w,E),e.links!==void 0){let P=this.linkSpansForWindow(e.body,e.links,b,A,h===0||a===0?0:a);P!==null&&(w.linkSpans=P)}}else{let b=e.body.indexOf(m,p),v=b===-1?p:b,k={sourceLineId:s,sourceColOffset:v};if(h>0&&a>0&&(k.bodyDisplayShift=a),this.wrapOrigin.set(w,k),e.links!==void 0){let A=this.linkSpansForWindow(e.body,e.links,v,v+m.length,h===0||a===0?0:a);A!==null&&(w.linkSpans=A)}p=v+m.length}f.push(w)}return s!==void 0&&this.wrapCache.set(s,f),f}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1,a=!1,d=null){e.prefix&&xs(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let c=Math.max(0,t-Ds(e.prefix??"")),l=id(e.bodyStyle),f=e.ansi?e.body:Tt(e.body,c,{stripMarkup:l}),u=d===null||d.length===0?null:d.map(m=>({start:Math.max(0,Math.min(f.length,m.start)),end:Math.max(0,Math.min(f.length,m.end)),url:m.url})).filter(m=>m.end>m.start).sort((m,y)=>m.start-y.start),p=(m,y,w)=>{if(u===null){w(m,y);return}let b=y+m.length,v=y;for(let k of u){if(k.end<=v||k.start>=b)continue;let A=Math.max(k.start,v),E=Math.min(k.end,b);A>v&&w(m.slice(v-y,A-y),v),process.stdout.write(`\x1B]8;;${k.url}\x1B\\`),w(m.slice(A-y,E-y),A),process.stdout.write("\x1B]8;;\x1B\\"),v=E}v<b&&w(m.slice(v-y),v)},h=(m,y)=>{m.length!==0&&p(m,y,(w,b)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let v=s!==null&&s>=b?s-b:null;pM(this.term,w,e.bodyStyle,this.scrollbackHighlight,v,r,o)}else xs(this.term,w,e.bodyStyle,o)})};if(i!==null){let m=Math.max(0,Math.min(f.length,i.start)),y=Math.max(m,Math.min(f.length,i.end)),w=id(e.bodyStyle)||e.ansi===!0;if(h(f.slice(0,m),0),y>m){let v=f.slice(m,y);w&&(v=lh(v)),w?xs(this.term,v,"selection-highlight",o):p(v,m,k=>{xs(this.term,k,"selection-highlight",o)})}let b=f.slice(y);if(w&&y>m){let v=bM(f.slice(0,y));v.length>0&&(b=v+b)}h(b,y)}else h(f,0);if(e.fillRow||o||a){let m=e.ansi?Xe(f):Ds(l?lh(f):f),y=c-m;if(y>0){let w=i!==null&&i.toEndOfLine?"selection-highlight":e.fillRow||o?e.bodyStyle:void 0;xs(this.term," ".repeat(y),w,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};SS=/[^\x20-\x7e]/,uh=new Intl.Segmenter(void 0,{granularity:"grapheme"}),kS=!1;mM=/[a-zA-Z+\-:_!#/]/;Fl=ut});function CM(n,e,t=Dl){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 RS(n,e){zn();let t=ut(e.sessionId),s=e.importedFromMachine??"another machine",r=lt(e.cwd),i=Dl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+Dl.length*2+2,c=Kn(n,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)n.moveTo(c.contentX,c.contentY+u),n.dim.noFormat(` ${p.label}`),n.noFormat(tt(p.value,l-p.label.length-2)),u++;return u++,TS(n,c,u,{intro:"What do you want to do?",choices:Dl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),c};return Ss({term:n,render:o,onKey:(a,d,c,l)=>{let f=RM(a,c);if(!f)return;let u=CM(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function TS(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 c=` ${o===s.selected?"\u276F":" "} ${a.label}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Ja(c,r)):n.noFormat(c),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 RM(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 ES(n,e,t){let s=ut(e.sessionId),r=e.title??lt(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=Kn(n,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;n.moveTo(d.contentX,d.contentY+l),n.dim.noFormat(" session: "),n.noFormat(tt(s,c-10)),l++,n.moveTo(d.contentX,d.contentY+l),n.noFormat(" "+tt(r,c-2)),l++,l++,TS(n,d,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(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),t.pop(),d(p)},u=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){f("launch");return}if(y==="v"){f("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};t.push({onKey:(p,h,m)=>{c||u(p,h,m)},onResize:()=>{c||a()}})})}var Dl,hh=J(()=>{"use strict";we();ps();pi();Dl=[{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 ad(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 PS(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]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=ad(e);return o.length<=r.length?null:o+i}var Hl=J(()=>{"use strict"});var Do,mh=J(()=>{"use strict";Do=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 MS from"os";async function yi(n,e,t={}){let s=t.defaultCwd??(e?await _v(e.cwd):void 0)??MS.homedir();zn();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:ut(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:lt(e.cwd)}]:[],a=new Do(s),d=null,c=!1,l=null,f=null,u=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),b=h.indexOf(y),v=()=>{let _=o.length+6;l=Kn(n,{contentHeight:_,title:r,overlay:t.overlay===!0});let F=l.contentW,B=0;for(let q of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${q.label}`),n.noFormat(tt(q.value,F-q.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;d!==null?(n.moveTo(l.contentX,N),n.red.noFormat(` ${tt(d,F-2)}`),f=null,u=null,p=null):(n.moveTo(l.contentX,N),n.dim.noFormat(h),f=N,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+b,end:l.contentX+b+y.length-1})},k=()=>o.length+3,A=0,E=_=>{if(!l)return;let 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),q=a.text,Q=a.cursor;Q<A&&(A=Q),Q-A>=N&&(A=Q-N+1),A<0&&(A=0);let X=q.slice(A,A+N);A>0&&X.length>0&&(X="\u2026"+X.slice(1));let G=Q-A;if(c){n.noFormat(X);return}G>=X.length?(n.noFormat(X),n.bgWhite(" ")):(n.noFormat(X.slice(0,G)),n.bgWhite.noFormat(X[G]??" "),n.noFormat(X.slice(G+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),d!==null?(n.red.noFormat(` ${tt(d,l.contentW-2)}`),f=null,u=null,p=null):(n.dim.noFormat(h),f=F,u={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(c)return;let F=a.text;c=!0,d=null,P(),Xa(F).then(B=>{if(c=!1,B.ok){_({kind:"ok",path:B.path});return}d=B.reason,P()})};return Ss({term:n,render:v,overlay:t.overlay===!0,onKey:(_,F,B,N)=>{if(!c){if(_==="ENTER"||_==="KP_ENTER"){H(N);return}if(_==="ESCAPE"){N({kind:"back"});return}if(_==="CTRL_C"||_==="CTRL_D"){N({kind:"cancel"});return}if(_==="TAB"){c=!0,$v(a.text).then(q=>{if(c=!1,q.matches.length===0)return;let Q;if(q.matches.length===1)Q=q.prefix+q.matches[0];else{let X=ad(q.matches);if(X.length<=q.basePrefix.length)return;Q=q.prefix+X}Q!==a.text&&(a.setText(Q,{recordUndo:!0}),d=null,P())});return}if(a.handleKey(_,B?.isCharacter===!0)){d=null,P();return}}},onMouse:(_,F,B)=>{if(c||_!=="MOUSE_LEFT_BUTTON_PRESSED")return;let N=F?.x,q=F?.y;if(!(typeof N!="number"||typeof q!="number")){if(l!==null&&(N<l.x||N>=l.x+l.w||q<l.y||q>=l.y+l.h)){B({kind:"back"});return}if(f!==null&&q===f){if(u!==null&&N>=u.start&&N<=u.end){H(B);return}if(p!==null&&N>=p.start&&N<=p.end){B({kind:"back"});return}}}}})}var gh=J(()=>{"use strict";we();ps();Mp();Hl();pi();mh()});import*as $S from"fs";import*as FS from"os";import*as Ul from"path";function jl(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 TM(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function EM(n){return n.replace(/\\ /g," ")}function _S(n){return n.replace(/ /g,"\\ ")}function PM(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function MM(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=FS.homedir()+t.slice(1)),Ul.isAbsolute(t)?t:Ul.resolve(e,t)}function _M(n){let e;try{e=$S.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function ql(n,e,t=_M){let s=EM(n),{dirPrefix:r,base:i}=PM(s);if(r.length===0&&!TM(n)&&i.length===0)return null;let o=MM(r,e),a=t(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(u=>u.name.startsWith(i)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:_S(r+p),candidates:l}}let f=ad(c.map(u=>u.name));return{replacement:_S(r+f),candidates:l}}var yh=J(()=>{"use strict";Hl()});function $M(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function FM(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),d=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${d}%)`}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 Wl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,$M(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 c=FM(i,s,a);s=c,e.write(c)},finalize(){t||(t=!0,o(0),e.finalize())}}}function OS(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 wh=J(()=>{"use strict"});function vh(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Sh(n,e){let t=()=>{process.stdout.write(li),process.stdout.write(
|
|
218
|
+
`);this.pasteBuffer="";let a=jv(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=cM(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.contentWidth()}termWidth(){return this.term.width||0}sidebarReserved(){if(!this.sidebarVisible)return 0;let e=this.term.width||0;if(e<tM)return 0;let t=this.sidebarConfiguredWidth??Math.min(eM,Math.max(mS,Math.floor(e*.28))),s=e-nM-rd-nh;return Math.min(t,Math.max(mS,s))+rd+nh}sidebarOverlay(){let e=this.sidebarReserved();return e>0&&e*2>(this.term.width||0)}sidebarColumnStart(){let e=this.sidebarReserved();return e===0?0:(this.term.width||0)-e+1}contentWidth(){let e=this.term.width||0;return this.sidebarOverlay()?e:Math.max(0,e-this.sidebarReserved())}transcriptVisibleWidth(){let e=this.sidebarColumnStart();return e===0?this.contentWidth():e-1}sidebarBodyWidth(){let e=this.sidebarReserved();return e===0?0:e-rd-nh}isSidebarVisible(){return this.sidebarVisible}isSidebarSuppressed(){return this.sidebarVisible&&this.sidebarReserved()===0}isSidebarOverlay(){return this.sidebarOverlay()}setSidebarVisible(e){this.sidebarVisible!==e&&(this.sidebarVisible=e,this.lastSidebarClick=null,this.sidebarRowPaths.clear(),this.sidebarRowActions.clear(),this.sidebarPages={},this.sidebarScrollOffset=0,this.sidebarOverflowRows=0,this.sidebarRenderer.invalidate(),this.painter.clearCache())}toggleSidebar(){return this.setSidebarVisible(!this.sidebarVisible),this.sidebarVisible}setSidebarGadgets(e){this.sidebarRenderer.setGadgets(e),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}setSidebarBorder(e){this.sidebarBorder!==e&&(this.sidebarBorder=e,this.sidebarRenderer.invalidate(),this.painter.clearCache(),this.scheduleRepaint())}setSidebarWidth(e){this.sidebarConfiguredWidth=e,this.painter.clearCache()}setSidebarSnapshot(e){this.sidebarSnapshot={...this.sidebarSnapshot,...e},this.sidebarVisible&&this.scheduleRepaint()}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.contentWidth();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)),d=t.length-s.count,c=this.lines.slice(s.start,o),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=c[f],h=t[f];p!==void 0&&fM(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=t.length;f<c.length;f++)u.push(c[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,d!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=d);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,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",d+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:t,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(t.length);for(let l of a){let u={prefix:c,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),d+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=Fl(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&&Be(()=>{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)),re({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 d={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}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),d=o(s,e.offset,i,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(d>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let c=Math.abs(s-r)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-t.endOffset)>=c?{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 d=(r.body??"").slice(o.start,o.end);(id(r.bodyStyle)||r.ansi)&&(d=lh(d)),t.push(d)}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 d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=c===r?Math.max(0,Math.min(f,o)):0,h=c===i?Math.max(0,Math.min(f,a)):f;d.set(u,{start:p,end:h,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}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,d=Math.max(r.start,i),c=Math.min(r.end,a);if(c<=d)return null;let l,u;if(s.sourceColEnd!==void 0){let f=this.sourceBodyForId(s.sourceLineId);if(f===null)return null;let p=dh(f,i,d),h=dh(f,d,c);l=ch(e.body,o,p),u=ch(e.body,l,h)}else l=d-i+o,u=c-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,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.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(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=d&&u.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,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 d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(kp),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&&re({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=Nl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let l=e==="MOUSE_WHEEL_UP"?3:-3,u=this.mouseCell(t);if(u!==null&&this.isSidebarCell(u.x,u.y)&&this.scrollSidebarBy(l))return;this.scrollBy(l);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=uM(e),d=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&o!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:o.x,y:o.y,name:e}),d==="move"){let l=o!==null?this.bannerHitAt(o.x,o.y):null;l!==this.hoveredBannerHit&&(this.hoveredBannerHit=l,this.syncedPartialRepaint(()=>this.drawBanner()))}let c=o!==null&&o.x>=1&&o.x<=this.transcriptVisibleWidth();if(o!==null&&c&&d!=="release"){let l=this.keyAndSubAtRow(o.y),u=l!==null&&l.key.startsWith("agent:")?null:l;if(u===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let f=this.nearestKeyAboveRow(o.y),p=this.nearestKeyBelowRow(o.y);f!==null&&p!==null&&this.hoveredRunKeys.has(f)&&this.hoveredRunKeys.has(p)&&(u={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(u!==null?"pointer":"default"),d==="move"){let f=u?.key??null,p=u?.sub??null;(f!==this.hoveredBlockKey||p!==this.hoveredSubKey)&&(this.hoveredBlockKey=f,this.hoveredSubKey=p,this.hoveredRunKeys=f!==null&&this.onHoverRun?this.onHoverRun(f)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(o!==null&&!c&&this.setPointerShape("default"),(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 l=this.lastLeftClick;if(l!==null&&o!==null&&Math.abs(o.x-l.x)<=_l&&Math.abs(o.y-l.y)<=_l&&Date.now()-l.t<=Ml||this.flushPendingBlockClick(),this.handleSidebarPress(o)){this.pressCell=null,this.clearSelection();return}this.pressCell=o,this.handleSelectionPress(o,lM(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 l=this.pressCell;this.pressCell=null;let u=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(l!==null&&o!==null&&o.x===l.x&&o.y===l.y&&!u){let f=this.btwHeaderSidRegion();if(f!==null&&this.onHydraLinkClick&&o.y===f.row&&o.x>=f.colStart&&o.x<=f.colEnd)this.onHydraLinkClick(f.sessionId);else if(this.onBlockClick){let p=this.keyAndSubAtRow(o.y),h=p?.key??null;if(h!==null){let m=o.y;for(;m>1&&this.keyAtRow(m-1)===h;)m-=1;this.schedulePendingBlockClick(h,o.y-m,p?.sub??null)}}}(o===null||!this.isSidebarCell(o.x,o.y))&&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<=Ml&&Math.abs(e.x-i.x)<=_l&&Math.abs(e.y-i.y)<=_l&&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.tryOpenLinkAt(s,e?.y??null)){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 c=this.wordBoundsAt(s);c!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:c.start},{sourceLineId:s.sourceLineId,offset:c.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.contentWidth(),{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=c<d;if(c===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(c>=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=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let i=1;i<s;i++){let o=t-i;if(o>=1){let d=this.resolveCellToSource(r,o);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+i;if(a<=s){let d=this.resolveCellToSource(r,a);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}=Ll(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),!$l.test(r[a])&&!eh.test(r[a]))return null;let d=a;for(;d>0&&eh.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&eh.test(r[c]);)c++;for(;c>d+1&&QP.test(r[c-1]);)c--;if(r.slice(d,c).includes("://")){let p=d,h=c;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!$l.test(r[a]))return null;let u=a;for(;u>0&&$l.test(r[u-1]);)u--;let f=a+1;for(;f<r.length&&$l.test(r[f]);)f++;for(;f>u+1&&pS.test(r[f-1]);)f--;for(;u<f-1&&pS.test(r[u]);)u++;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}=Ll(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),!Zp.test(r[a]))return null;let d=a;for(;d>0&&Zp.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&Zp.test(r[c]);)c++;let l=r.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=r.slice(c).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.links||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Ll(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}osc8UrlFor(e){if(hS.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let t=e.indexOf("#"),s=t===-1?e:e.slice(0,t),r=t===-1?"":e.slice(t);if(s.length===0)return null;let i=s;return s==="~"||s.startsWith("~/")?i=s==="~"?Pl():`${Pl()}/${s.slice(2)}`:Xp(s)||(i=fS(this.sessionbar.cwd,s)),ep(i+r)}linkSpansForWindow(e,t,s,r,i){let o=wM(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=o[d.start]??e.length,u=o[d.end]??e.length,f=Math.max(l,s),p=Math.min(u,r);p>f&&a.push({start:f-s+i,end:p-s+i,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Pl():`${Pl()}/${t.slice(2)}`);let s=Xp(t)||e.startsWith("~"),r=Xp(t)?t:fS(this.sessionbar.cwd,t);if(s)return r;try{if(uS(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(!XP.test(s))return!1;let r=s.startsWith(Kt)?[s]:[Kt+s,s],i=null;for(let o of r)try{if(uS(L.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}dispatchLinkUrl(e){let t=e.match(hS);if(t){let i=t[1]??null;return i!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(i):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let s=e;if(s.startsWith("file://")){let i=s.slice(7),o=i.indexOf("/");s=o===-1?"":i.slice(o);try{s=decodeURIComponent(s)}catch{}}if(s.length===0)return!1;let r=s.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return r?this.tryOpenPathString(`${r[1]}:${r[2]}`):this.tryOpenPathString(s)}tryOpenLinkAt(e,t){let s=this.findLinkUrlAt(e);if(s!==null)return this.dispatchLinkUrl(s);let i=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(i!==void 0)return this.dispatchLinkUrl(i);if(t!==null){let o=this.blockLinkUrlAt(t);if(o!==null)return this.dispatchLinkUrl(o)}return!1}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,...d]=this.openFileCommand;if(!a)return!1;let c=!1,l=[];for(let u of d)u.includes("%f")&&(c=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));c||l.push(i);try{let u=GP(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,s){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,s);return}this.cancelPendingBlockClick();let r=this.onBlockClick,i=setTimeout(()=>{this.pendingBlockClick=null,r(e,t,s)},Ml);typeof i.unref=="function"&&i.unref(),this.pendingBlockClick={timer:i,key:e,rowOffset:t,subKey:s}}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,e.subKey))}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&&Kv(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"?Vb:fl))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null)return null;let s=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return null;let{rows:i}=this.wrapTail(s,r+this.scrollOffset);for(let o of i)if(o.blockKey===t&&o.linkSpans!==void 0&&o.linkSpans.length>0)return o.linkSpans[0]?.url??null;return null}keyAtRow(e){let t=this.contentWidth(),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,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),u=i-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}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.contentWidth(),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,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),u=i-l;if(u<0||u>=c.length)return null;let f=c[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.contentWidth(),r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-r;if(o<0||o>=i||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=Hs(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=w,k=id(p.bodyStyle)||p.ansi===!0?cS(fh(p.body),b):dS(p.body,b);if(h.sourceColEnd!==void 0){let A=this.sourceBodyForId(h.sourceLineId);if(A!==null){let E=dh(p.body,y,k),_=ch(A,h.sourceColOffset,E);return{sourceLineId:h.sourceLineId,offset:_}}}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=[],d=0;for(;d<o.length;){let c=o.indexOf(t,d);if(c===-1)break;a.push(c),d=c+t.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=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.contentWidth(),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,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Qe-it-rt-ZP-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,t,s,r){return this.started?this.painter.paintRow(e,t,s,r):!1}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),Be(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-rt-it-Qe;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Qe),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=Ww(this.sessionbar.agent,this.sessionbar.model),i=lt(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Xe(r),d=1,c=Math.max(0,e-a-d),l=s?" \xB7 ":"",u=Xe(l),f,p;if(s){let b=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,c-u-b)),p=Math.max(0,c-f-u)}else p=0,f=c;let h=kt(i,f),m=s?kt(s,p):"",y=Xe(h)+(s?u+Xe(m):0),w=Math.max(d,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=Fl(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?vs(this.banner.elapsedMs):"",d=[];if(this.banner.queued>0){let A=`${this.banner.queued} queued`;d.push({text:A,paint:()=>{this.term.brightYellow(A)}})}if(this.scrollOffset>0){let A=`\u2191 ${this.scrollOffset}`;d.push({text:A,paint:()=>{this.term.brightCyan(A)}})}let c=bS(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=c?" ":"",m=c?" \u2500\u2500":"\u2500\u2500",y=l.length+Xe(o)+Xe(u)+f.length+Xe(s);for(let A of d)y+=Xe(" \xB7 ")+Xe(A.text);y+=Xe(p);let w=Xe(h)+Xe(c)+Xe(m),b=Math.max(0,t-y-w),v="\u2500".repeat(b),k=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${c}`;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 d)this.term.dim(" \xB7 "),A.paint();this.term.dim(p),this.term.bold(v),c&&(this.term.dim(h),this.term.noFormat(c)),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,d=Xe(i)+Xe(a)+Xe(o),c=Math.max(0,t-d),l="\u2500".repeat(c),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 v=null;b.includes("mode")?v="mode":b.includes("pick")?v="pick":b.includes("guide")?v="guide":b.includes("detach")&&(v="detach"),v!==null&&v===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=c+Xe(i)+1,y=r.split(" \xB7 ");for(let w of y){let b=Xe(w),v=[m,m+b-1];w.includes("mode")&&h.mode===null?h.mode=v:w.includes("pick")&&h.pick===null?h.pick=v:w.includes("guide")&&h.guide===null?h.guide=v:w.includes("detach")&&h.detach===null&&(h.detach=v),m+=b+Xe(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Fl(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=bS(this.btwOverlayUsage),d=a?` ${a} `:"",c=a?"\u2500\u2500":"",l=s.length+Xe(t)+i.length+Xe(r)+o.length+Xe(d)+c.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:d,right:c,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()-rt-it-Qe,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",d="\u2500\u2500 ",c=Fl(this.btwOverlaySessionId),u=1+d.length+Xe(a)+" \xB7 ".length,f=u+Xe(c)-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.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),s=this.sidebarBodyWidth()>0,r=1,i=this.scrollbackVisibleRows();if(i<=0)return;let{rows:o,exhausted:a}=this.wrapTail(e,i+this.scrollOffset);if(a){let y=Math.max(0,o.length-i);this.scrollOffset>y&&(this.scrollOffset=y)}let d=o.length-this.scrollOffset,c=Math.max(0,d-i),l=o.slice(c,d),u=Math.max(0,i-l.length),f=this.currentMatchInfo(),p=f?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let h=-1,m=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let y=0;y<l.length;y++){let w=l[y]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(h===-1&&(h=y),m=y)}for(let y=0;y<i;y++){let w=r+y,b=y-u,v=b>=0?l[b]:void 0,k=this.activeMatchCol(v,f),A=v?this.selectionRangeForChunk(v):null,E=v!==void 0&&v.blockKey!==void 0&&(v.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(v.blockKey)),_=v!==void 0&&v.blockKey===void 0&&h!==-1&&b>=h&&b<=m,H=E||_,P=this.terminalFocused&&H&&(this.hoveredSubKey===null||(v.hoverSubKey??null)===this.hoveredSubKey),$=ah("sb",e,v,this.scrollbackHighlight,k,A)+(P?"|H":"");this.paintRow(w,$,()=>{v?this.writeFormattedLine(v,e,k,p,A,P,t,v.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&s&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let y=new Set;for(let b of l)b.blockKey!==void 0&&y.add(b.blockKey);let w=[];for(let b of this.pendingVisibleKeys)y.has(b)&&w.push(b);for(let b of w)this.pendingVisibleKeys.delete(b),this.onBlockVisible(b)}}drawSidebar(e,t){let s=this.sidebarBodyWidth();if(s<=0||t<=0){this.sidebarOverflowRows=0;return}let r=this.sidebarColumnStart(),i={metrics:{cellWidth:Hs,truncate:kt},width:s,border:this.sidebarBorder,pages:this.sidebarPages,maxRows:t},o={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(o,i);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowActions.clear();let c=r+rd;for(let l=0;l<t;l++){let u=e+l,f=l+d,p=a[f];p?.openPath!==void 0&&this.sidebarRowPaths.set(u,p.openPath),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(u,p.actions.map(w=>({start:c+w.start-1,end:c+w.end-1,gadget:w.page.gadget,index:w.page.index})));let h=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",m=p?.openPath===void 0||!p.openPath.startsWith("/")||p.openSpan===void 0?null:[{...p.openSpan,url:ep(p.openPath)}],y=ah("sbar",s,p,null,null,null)+`|${h}|${m===null?"":m.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(u,y,()=>{this.term(" ".repeat(Math.max(0,rd-1))),h===" "?this.term(" "):Is(this.term,h,"dim",!1),p?this.writeFormattedLine(p,s,null,0,null,!1,!0,m):this.term(" ".repeat(s))},{region:"sidebar",column:r})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let t=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return t===this.sidebarScrollOffset||(this.sidebarScrollOffset=t,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,t){let s=this.sidebarColumnStart();return s===0?!1:e>=s&&e<=(this.term.width||0)&&t>=1&&t<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let i of this.sidebarRowActions.get(e.y)??[])if(e.x>=i.start&&e.x<=i.end)return this.sidebarPages={...this.sidebarPages,[i.gadget]:i.index},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),s=this.lastSidebarClick;if(s!==null&&t-s.t<=Ml&&e.y===s.y){this.lastSidebarClick=null;let i=this.sidebarRowPaths.get(e.y);return i!==void 0&&!this.dispatchLinkUrl(i)&&this.notify(this.hasOpenFileCommand()?`can't open ${i}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(sh,this.queuedTexts.length)}chipRows(){return Math.min(ih,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(rh,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-Qe-it-rt,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let u=d+l,f=this.completions[l],p=l===e-1&&this.completions.length>rh,h=this.completions.length-rh+1,m=f?p?`comp|${t}|overflow|${h}`:`comp|${t}|${c}|${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(c),w=f.description??"",b=t-y.length-4,v=b>0?kt(w,b):"";this.term(" ").brightCyan(y),v.length>0&&this.term(" ").dim(v)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Qe-it-rt-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>ih,u=this.attachments.length-ih,f=this.attachments[d],p=f?`${f.name??"image"} \xB7 ${Fn(f.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${u}`:f?`chip|${t}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${t}|empty`;this.paintRow(c,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(vM(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-Qe-it-rt,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,u=this.queuedTexts[c],f=c===e-1&&this.queuedTexts.length>sh,p=this.queuedTexts.length-sh,h=u===void 0?"":f?`+ ${p+1} more queued`:kt(AM(u),t-4),m=!f&&c===d,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=xs(s.buffer,t),i=Us(r,s,th),o=this.term.height-i.rendered-rt-it-Qe+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,s=this.term.height-oh-rt-it-Qe+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${kt(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${kt(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-rt-it-Qe+1,i=r,o=(a,d)=>{i>=r+s||(this.paintRow(i,a,d),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${kt(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 d=e.options[a];if(!d)continue;let c=a===e.selectedIndex,u=` ${c?"\u276F":" "} ${a+1}. ${kt(d.label,t-8)}`;o(`cpct|o|${t}|${a}|${c?"1":"0"}|${d.label}`,()=>{c?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-rt-it-Qe+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${kt(e.title,t-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${t}|${i}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);o(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${kt(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${kt(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(iM,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-rt-it-Qe+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${kt(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(` ${kt(a,t-2)}`)}),o(`perm|q|${t}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,f=` ${l?"\u276F":" "} ${d+1}. ${kt(c.label,t-8)}`;o(`perm|o|${t}|${d}|${l?"1":"0"}|${c.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-rt-it-Qe;this.drawSeparator(s),this.drawBottomSeparator(e-Qe)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-rt-it-Qe+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-rt-it-Qe+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-oh-rt-it-Qe+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-rt-it-Qe+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-rt-it-Qe;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-rt-it-Qe+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=xs(s.buffer,t),i=Us(r,s,th),a=this.term.height-i.rendered-rt-it-Qe+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-rt-it-Qe;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return oh;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=xs(s.buffer,t);return Math.min(th,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(sM,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(rM,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-rt-it-Qe+1,i=r,o=(c,l)=>{i>=r+s||(this.paintRow(i,c,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${kt(e.title,t-5)}`)});let a=Math.max(...e.options.map(c=>c.label.length),0);for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let l=e.options[c];if(!l)continue;let u=c===e.selectedIndex,p=` ${u?"\u276F":" "} ${c+1}. `,h=l.label.padEnd(a),m=t-p.length-3,y=`${p}${kt(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${c}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let d=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${t}|${d}`,()=>{this.term.dim(` ${d}`)})}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],d=this.wrapOne(a,e);if(s.push(d),r+=d.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()-rt-it-Qe,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a,l=this.buildBtwHeaderSegments();this.paintRow(c,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(t,d);for(let f=0;f<d;f++){let p=c+1+f,h=u.length-d+f,m=h>=0?u[h]:void 0,y=ah(`btw|c${f}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){let s=c=>c.collapsed===!0||this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let u of this.lines)s(u)||c.push(u);let l=Math.min(t,c.length);return{rows:c.slice(c.length-l),exhausted:t>=c.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 c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=c,i>=t)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:o===0||a}}wrapOne(e,t){let s=this.lineIds.get(e);if(s!==void 0){let y=this.wrapCache.get(s);if(y)return y}let r=e.prefix??"",i=Hs(r),o=Math.max(1,t-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),d=Math.max(1,o-a),c=id(e.bodyStyle),l=e.ansi?hM(e.body,a>0?d:o):SM(e.body,a>0?d:o,{stripMarkup:c}),u=e.ansi?0:e.maxWrapRows??0,f=u>0&&l.length>u;f&&(l.length=u);let p=[],h=0,m=0;for(let y=0;y<l.length;y++){let w=l[y]??"",b=y===0||a===0?w:" ".repeat(a)+w;f&&y===l.length-1&&(b=kt(`${b}\u2026`,o,{stripMarkup:c}));let v={prefix:y===0?e.prefix:" ".repeat(i),body:b};if(e.prefixStyle!==void 0&&(v.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(v.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(v.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(v.hoverSubKey=e.hoverSubKey),e.fillRow&&(v.fillRow=!0),e.ansi&&(v.ansi=!0),y===0&&e.iterm2Image&&(v.iterm2Image=e.iterm2Image),s!==void 0&&w.length>0)if(e.ansi){let k=h,A=0;for(let P=0;P<w.length;){let $=Jn(w,P);if($){P+=$.text.length,$.width>0&&(A+=1);continue}A+=1,P+=1}let E=A;for(;E>0&&h<e.body.length;){let P=Jn(e.body,h);if(P){h+=P.text.length,P.width>0&&(E-=1);continue}h+=1,E-=1}let _=h;if(y===l.length-1){for(;_<e.body.length;){let P=Jn(e.body,_);if(!P)break;_+=P.text.length}h=_}let H={sourceLineId:s,sourceColOffset:k,sourceColEnd:_};if(y>0&&a>0&&(H.bodyDisplayShift=a),this.wrapOrigin.set(v,H),e.links!==void 0){let P=this.linkSpansForWindow(e.body,e.links,k,_,y===0||a===0?0:a);P!==null&&(v.linkSpans=P)}}else{let k=e.body.indexOf(w,m),A=k===-1?m:k,E={sourceLineId:s,sourceColOffset:A};if(y>0&&a>0&&(E.bodyDisplayShift=a),this.wrapOrigin.set(v,E),e.links!==void 0){let _=this.linkSpansForWindow(e.body,e.links,A,A+w.length,y===0||a===0?0:a);_!==null&&(v.linkSpans=_)}m=A+w.length}p.push(v)}return s!==void 0&&this.wrapCache.set(s,p),p}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1,a=!1,d=null){e.prefix&&Is(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let c=Math.max(0,t-Hs(e.prefix??"")),l=id(e.bodyStyle),u=e.ansi?e.body:kt(e.body,c,{stripMarkup:l}),f=d===null||d.length===0?null:d.map(m=>({start:Math.max(0,Math.min(u.length,m.start)),end:Math.max(0,Math.min(u.length,m.end)),url:m.url})).filter(m=>m.end>m.start).sort((m,y)=>m.start-y.start),p=(m,y,w)=>{if(f===null){w(m,y);return}let b=y+m.length,v=y;for(let k of f){if(k.end<=v||k.start>=b)continue;let A=Math.max(k.start,v),E=Math.min(k.end,b);A>v&&w(m.slice(v-y,A-y),v),process.stdout.write(`\x1B]8;;${k.url}\x1B\\`),w(m.slice(A-y,E-y),A),process.stdout.write("\x1B]8;;\x1B\\"),v=E}v<b&&w(m.slice(v-y),v)},h=(m,y)=>{m.length!==0&&p(m,y,(w,b)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let v=s!==null&&s>=b?s-b:null;pM(this.term,w,e.bodyStyle,this.scrollbackHighlight,v,r,o)}else Is(this.term,w,e.bodyStyle,o)})};if(i!==null){let m=Math.max(0,Math.min(u.length,i.start)),y=Math.max(m,Math.min(u.length,i.end)),w=id(e.bodyStyle)||e.ansi===!0;if(h(u.slice(0,m),0),y>m){let v=u.slice(m,y);w&&(v=lh(v)),w?Is(this.term,v,"selection-highlight",o):p(v,m,k=>{Is(this.term,k,"selection-highlight",o)})}let b=u.slice(y);if(w&&y>m){let v=bM(u.slice(0,y));v.length>0&&(b=v+b)}h(b,y)}else h(u,0);if(e.fillRow||o||a){let m=e.ansi?Xe(u):Hs(l?lh(u):u),y=c-m;if(y>0){let w=i!==null&&i.toEndOfLine?"selection-highlight":e.fillRow||o?e.bodyStyle:void 0;Is(this.term," ".repeat(y),w,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};SS=/[^\x20-\x7e]/,uh=new Intl.Segmenter(void 0,{granularity:"grapheme"}),kS=!1;mM=/[a-zA-Z+\-:_!#/]/;Fl=ut});function CM(n,e,t=Dl){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 RS(n,e){zn();let t=ut(e.sessionId),s=e.importedFromMachine??"another machine",r=lt(e.cwd),i=Dl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+Dl.length*2+2,c=Kn(n,{contentHeight:d,title:"Imported session"}),l=c.contentW,u=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)n.moveTo(c.contentX,c.contentY+f),n.dim.noFormat(` ${p.label}`),n.noFormat(tt(p.value,l-p.label.length-2)),f++;return f++,TS(n,c,f,{intro:"What do you want to do?",choices:Dl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),c};return Ss({term:n,render:o,onKey:(a,d,c,l)=>{let u=RM(a,c);if(!u)return;let f=CM(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 TS(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 c=` ${o===s.selected?"\u276F":" "} ${a.label}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Ja(c,r)):n.noFormat(c),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 RM(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 ES(n,e,t){let s=ut(e.sessionId),r=e.title??lt(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=Kn(n,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;n.moveTo(d.contentX,d.contentY+l),n.dim.noFormat(" session: "),n.noFormat(tt(s,c-10)),l++,n.moveTo(d.contentX,d.contentY+l),n.noFormat(" "+tt(r,c-2)),l++,l++,TS(n,d,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(d=>{let c=!1,l=()=>{c=!0},u=p=>{l(),t.pop(),d(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)=>{c||f(p,h,m)},onResize:()=>{c||a()}})})}var Dl,hh=J(()=>{"use strict";we();ps();pi();Dl=[{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 ad(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 PS(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]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=ad(e);return o.length<=r.length?null:o+i}var Hl=J(()=>{"use strict"});var Do,mh=J(()=>{"use strict";Do=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 MS from"os";async function yi(n,e,t={}){let s=t.defaultCwd??(e?await _v(e.cwd):void 0)??MS.homedir();zn();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:ut(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:lt(e.cwd)}]:[],a=new Do(s),d=null,c=!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),v=()=>{let P=o.length+6;l=Kn(n,{contentHeight:P,title:r,overlay:t.overlay===!0});let $=l.contentW,B=0;for(let U of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${U.label}`),n.noFormat(tt(U.value,$-U.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;d!==null?(n.moveTo(l.contentX,N),n.red.noFormat(` ${tt(d,$-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=P=>{if(!l)return;let $=P??k();n.moveTo(l.contentX,l.contentY+$).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+$),n.dim.noFormat("\u2502"),n.moveTo(l.contentX,l.contentY+$),n.noFormat(" ");let N=Math.max(1,l.contentW-1-2),U=a.text,G=a.cursor;G<A&&(A=G),G-A>=N&&(A=G-N+1),A<0&&(A=0);let X=U.slice(A,A+N);A>0&&X.length>0&&(X="\u2026"+X.slice(1));let Y=G-A;if(c){n.noFormat(X);return}Y>=X.length?(n.noFormat(X),n.bgWhite(" ")):(n.noFormat(X.slice(0,Y)),n.bgWhite.noFormat(X[Y]??" "),n.noFormat(X.slice(Y+1)))},_=()=>{if(E(),!l)return;let P=k()+2;n.moveTo(l.contentX,l.contentY+P).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+P),n.dim.noFormat("\u2502");let $=l.contentY+P;n.moveTo(l.contentX,$),d!==null?(n.red.noFormat(` ${tt(d,l.contentW-2)}`),u=null,f=null,p=null):(n.dim.noFormat(h),u=$,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=P=>{if(c)return;let $=a.text;c=!0,d=null,_(),Xa($).then(B=>{if(c=!1,B.ok){P({kind:"ok",path:B.path});return}d=B.reason,_()})};return Ss({term:n,render:v,overlay:t.overlay===!0,onKey:(P,$,B,N)=>{if(!c){if(P==="ENTER"||P==="KP_ENTER"){H(N);return}if(P==="ESCAPE"){N({kind:"back"});return}if(P==="CTRL_C"||P==="CTRL_D"){N({kind:"cancel"});return}if(P==="TAB"){c=!0,$v(a.text).then(U=>{if(c=!1,U.matches.length===0)return;let G;if(U.matches.length===1)G=U.prefix+U.matches[0];else{let X=ad(U.matches);if(X.length<=U.basePrefix.length)return;G=U.prefix+X}G!==a.text&&(a.setText(G,{recordUndo:!0}),d=null,_())});return}if(a.handleKey(P,B?.isCharacter===!0)){d=null,_();return}}},onMouse:(P,$,B)=>{if(c||P!=="MOUSE_LEFT_BUTTON_PRESSED")return;let N=$?.x,U=$?.y;if(!(typeof N!="number"||typeof U!="number")){if(l!==null&&(N<l.x||N>=l.x+l.w||U<l.y||U>=l.y+l.h)){B({kind:"back"});return}if(u!==null&&U===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 gh=J(()=>{"use strict";we();ps();Mp();Hl();pi();mh()});import*as $S from"fs";import*as FS from"os";import*as Ul from"path";function jl(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 TM(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function EM(n){return n.replace(/\\ /g," ")}function _S(n){return n.replace(/ /g,"\\ ")}function PM(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function MM(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=FS.homedir()+t.slice(1)),Ul.isAbsolute(t)?t:Ul.resolve(e,t)}function _M(n){let e;try{e=$S.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function ql(n,e,t=_M){let s=EM(n),{dirPrefix:r,base:i}=PM(s);if(r.length===0&&!TM(n)&&i.length===0)return null;let o=MM(r,e),a=t(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(f=>f.name.startsWith(i)&&(d||!f.name.startsWith(".")));if(c.length===0)return null;let l=c.map(f=>f.isDir?f.name+"/":f.name);if(c.length===1){let f=c[0],p=f.isDir?f.name+"/":f.name;return{replacement:_S(r+p),candidates:l}}let u=ad(c.map(f=>f.name));return{replacement:_S(r+u),candidates:l}}var yh=J(()=>{"use strict";Hl()});function $M(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function FM(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),d=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${d}%)`}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 Wl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,$M(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 c=FM(i,s,a);s=c,e.write(c)},finalize(){t||(t=!0,o(0),e.finalize())}}}function OS(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 wh=J(()=>{"use strict"});function vh(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Sh(n,e){let t=()=>{process.stdout.write(li),process.stdout.write(Os),process.stdout.write(ui),process.stdout.write(fi),process.stdout.write(Po),process.stdout.write(Mo),process.stdout.write(_o),process.stdout.write(ci),process.stdout.write("\x1B>")};t();let s=e.prefs??vh();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=zl(e.sessions,r),o=T=>{let M=T;return s.filters.cwdOnly&&(M=M.filter(j=>j.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(j=>j.interactive===!0)),M=HM(M,s.filters.hostFilter),M},a=o(i),d={columns:e.config.tui.sessionColumns??Io,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},c=a.map(T=>Ao(T,Date.now())),l=Co(c,d),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,v="normal",k=null,A=!1,E="input",_=new Bs({history:[],collapsePastes:!1}),H=[],P=!1,$=0,B=0,N=null,U=!1,G=null,X=null,Y=null,pe=null,nt=()=>{if(pe!==null){let T=pe;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 Y!==null?{plain:Y,render:()=>{n.dim.noFormat(` ${Y}`)}}:null},qs=!1,We=new Bs({history:[]});if(e.initialPrompt&&We.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)We.addAttachment(T);let It=e.config.tui.promptHistoryMaxEntries;ka(L.globalTuiHistoryFile()).then(T=>{let M=T.length>It?T.slice(T.length-It):T;We.setHistory(M)}).catch(()=>{});let he=new No(n),ee=Ls(n),Ee=tn(n),Je=0,Pt="",Pe=0,Mt=[],_t=1,bn=0,xr=0,bi=0,On="",Ho=[],vn=1,Ws=0,Uo=[],Jt=1,Ar=0,fd=0,pd=0,Ne=()=>{ee=Ls(n),Ee=tn(n);let T=Math.max(10,Ee-bh-1);Pe=Math.max(10,Ee-LS);let M=Math.max(10,Ee-8),j=We.state().attachments.length,Q=j>0?` \xB7 \u{1F4CE}\xD7${j}`:"",ie=Math.max(10,M-Q.length);Pt=NM(r,ie)+Q;let oe=We.state();Mt=xs(oe.buffer,Pe);let Ie=Us(Mt,oe,dd);_t=Ie.rendered,bn=Ie.windowStart,xr=Ie.cursorVisualRow,bi=Ie.cursorVisualCol;let De=6+_t,$e=Math.max(3,ee-De);Je=Math.min(a.length,$e),On=gr(xo,l,T,d).padEnd(T),Ho=c.map(Ze=>gr(Ze,l,T,d).padEnd(T))},hd=()=>{c=a.map(T=>Ao(T,Date.now())),l=Co(c,d),u=1+a.length,Ne()},Vt=()=>{let T=o(i);h&&m.length>0?a=T.filter(M=>UM(M,m)):a=T,hd(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+Je>a.length&&(p=Math.max(0,a.length-Je)),Sn()},As=T=>{if(T!==void 0){let M=a.findIndex(j=>j.sessionId===T);if(M>=0){f=M+1,Sn();return}}f=a.length>0?1:0,p=0,Sn()},Sn=()=>{if(f===0)return;let T=f-1;T<p?p=T:T>=p+Je?p=T-Je+1:p+Je>a.length&&(p=Math.max(0,a.length-Je))},Ln=()=>Math.max(2,Ee-3),yt=!1,$t=!0,xt=!1,me=[],Ht=e.composerAgentId,ot=e.composerModel,vi=()=>{let T=Ht;if(!T)return"";let M=ot;return M?`${T}\u2022${M}`:T},Gn=null,Yn=null,Ut=null,Si=()=>{let T=Ln(),M=`\u2500 ${Pt} `,j=vi(),Q="";if(j.length>0){let ze=`\u2500 ${j} `;ze.length+M.length+1<=T&&(Q=ze)}let ie=Math.max(1,T-M.length-Q.length),oe="\u2500".repeat(ie),Ie=(f===0||yt)&&$t;if(Gn=M.length>0?{start:2,end:1+M.length}:null,Q.length>0){let ze=1+M.length+ie+1;Yn={start:ze,end:ze+Q.length-1}}else Yn=null;let De=Ie?n.brightBlue:n.dim,$e=Ie?n.brightBlue.bold:n.dim.bold,Ze=(ze,ts)=>{(ts?$e:De).noFormat(ze)};De.noFormat("\u256D"),Ze(M,Ut==="cwd"),De.noFormat(oe),Q&&Ze(Q,Ut==="agent"),De.noFormat("\u256E")},ki=()=>{let T=Ln(),M="\u2500".repeat(T);(f===0||yt)&&$t?n.brightBlue.noFormat(`\u2570${M}\u256F`):n.dim.noFormat(`\u2570${M}\u256F`)},Ii=()=>{let T=nt();if(T===null)return;let M=Math.max(0,tn(n)-2);if(T.plain.length>M){let j=T.plain.slice(0,Math.max(0,M-1))+"\u2026";n.dim.noFormat(` ${j}`);return}T.render()},zs=T=>{let M=Mt[T];return M?(We.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},Cr=T=>{let M=Ln(),j=zs(T),Q=Math.max(0,M-1-j.length),ie=" ".repeat(Q);(f===0||yt)&&$t?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${j}${ie}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${j}${ie}`),n.dim.noFormat("\u2502"))},kn=T=>{let M=Ho[T]??"",j=a[T],Q=j&&j.priority&&j.priority>0?"* ":" ";f===T+1&&!yt&&$t?n.brightWhite.bgBlue.noFormat(`${Q}${M}`):n.noFormat(`${Q}${M}`)},jo=()=>{let T=p,M=Math.max(0,a.length-p-Je),j=[];if(s.filters.cwdOnly&&j.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;j.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&j.push({kind:"plain",text:"+non-interactive"}),T>0&&j.push({kind:"plain",text:`\u2191 ${T} above`}),M>0&&j.push({kind:"plain",text:`\u2193 ${M} below`}),j},Ks=()=>{let T=jo();return T.length===0?"":` ${T.map(M=>M.text).join(" \xB7 ")}`},Rr=T=>ut(T),nn=()=>{let T=k?`${k.sessionId}|${k.status}`:"";return["ind",v,T,G?`${G.text}${G.cursor}`:"",X??"",h?`1|${m}|${a.length}`:"0",Ks(),Ri?"h1":"h0",Ti?"ho1":"ho0"].join("")},ke=()=>{Be(()=>{he.paintRow(wt(),nn(),()=>{let T=()=>{An=null,Cn=null};if(v==="confirm-kill"&&k)T(),n.brightYellow.noFormat(` kill ${Rr(k.sessionId)}? [y/N]`);else if(v==="confirm-delete"&&k)T(),k.status==="warm"?n.brightRed.noFormat(` kill + delete ${Rr(k.sessionId)}? [y/N]`):n.brightRed.noFormat(` delete ${Rr(k.sessionId)}? [y/N]`);else if(v==="busy"&&k)T(),n.dim.noFormat(` working on ${Rr(k.sessionId)}\u2026`);else if(v==="rename"&&k&&G){T();let M=G.text,j=G.cursor;n.brightYellow.noFormat(" title: "),n.brightYellow.noFormat(M.slice(0,j)),j<M.length?(n.bgBrightYellow.noFormat(M[j]??" "),n.brightYellow.noFormat(M.slice(j+1))):n.bgBrightYellow(" "),n.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(X!==null)T(),n.dim.noFormat(` ${X}`);else{let M=jo(),j=Ks(),Q="Esc \xB7 Go Back",ie=Q.length,oe=5,Ie=j.length,De=Math.max(1,Ee-Ie-ie-oe);if(Cn=null,M.length>0){n.dim.noFormat(" ");let $e=3;for(let Ze=0;Ze<M.length;Ze++){let ze=M[Ze];Ze>0&&(n.dim.noFormat(" \xB7 "),$e+=3),ze.kind==="host"?(Cn={start:$e,end:$e+ze.text.length-1},Ti?n.noFormat(ze.text):n.dim.noFormat(ze.text)):n.dim.noFormat(ze.text),$e+=ze.text.length}}n.dim(" ".repeat(De)),Ri?n.noFormat(Q):n.dim.noFormat(Q),An={start:Ee-oe-ie+1,end:Ee-oe}}})})},In=T=>vn+1+T,Ae=()=>vn+_t+1,Bn=()=>vn+_t+3,Tr=T=>Bn()+1+(T-p),wt=()=>Bn()+1+Je,jt=()=>{let T=xr-bn;if(T<0||T>=_t)return;let M=3+bi;n.moveTo(M,In(T))},Js=()=>$t?f===0?"f":yt?"h":"u":"x",I=()=>`ct|${Js()}|${Ln()}|${Pt}|${vi()}|${Ut??""}`,qo=()=>`cb|${Js()}|${Ln()}`,md=()=>pe!==null?`cs|i|${pe}`:h?`cs|s|${m}|${a.length}`:Y!==null?`cs|h|${Y}`:"blank",Vs=T=>`cbb|${Js()}|${Ln()}|${zs(T)}`,xi=()=>`h|${On}`,Er=T=>{let M=a[T],j=M&&M.priority&&M.priority>0?"* ":" ",Q=Ho[T]??"";return`sr|${f===T+1&&!yt&&$t?"1":"0"}|${j}${Q}`},Ve=()=>{Be(()=>{n.hideCursor(),Ne(),Sn(),vn=1,he.ensureSize(Ee,ee),he.paintRow(vn,I(),()=>{Si()});for(let T=0;T<_t;T++){let M=bn+T;he.paintRow(In(T),Vs(M),()=>{Cr(M)})}he.paintRow(Ae(),qo(),()=>{ki()}),he.paintRow(Ae()+1,md(),()=>Ii()),he.paintRow(Bn(),xi(),()=>{n.dim.noFormat(` ${On}`)});for(let T=0;T<Je;T++){let M=p+T,j=Bn()+1+T;M<a.length?he.paintRow(j,Er(M),()=>{kn(M)}):he.paintRow(j,"blank",()=>{})}ke();for(let T=wt()+1;T<=ee;T++)he.paintRow(T,"blank",()=>{});f===0&&(jt(),n.hideCursor(!1))})},Cs=()=>{he.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Ve()},Wo=()=>{Be(()=>{n.hideCursor(),he.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(" Picker hotkeys")(`
|
|
222
222
|
|
|
223
223
|
`);for(let T of BM){if(T===null){n(`
|
|
224
|
-
`);continue}let[M,
|
|
224
|
+
`);continue}let[M,j]=T;n.brightCyan.noFormat(` ${M.padEnd(LM)}`),n.noFormat(j)(`
|
|
225
225
|
`)}n(`
|
|
226
226
|
`),n.dim.noFormat(" press any key to dismiss")(`
|
|
227
|
-
`)})},sn=()=>
|
|
228
|
-
`);Be(()=>{n.hideCursor(),he.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),gd(T);for(let
|
|
229
|
-
`),Yo=T=>{let M=
|
|
230
|
-
`);es="";let oe=M.slice(
|
|
231
|
-
`))},Br=()=>{if(
|
|
232
|
-
`);return`${
|
|
233
|
-
${
|
|
227
|
+
`)})},sn=()=>Jt+4,Yl=2,bt=0,Gt=()=>{ee=Ls(n);let T=Math.max(2,ee-(Jt+3)-Yl);return Math.max(1,Math.floor(T/2))},zo=()=>{let T=Gt();$<bt?bt=$:$>=bt+T&&(bt=$-T+1),bt+T>H.length&&(bt=Math.max(0,H.length-T)),bt<0&&(bt=0)},gd=T=>{Ee=tn(n);let M=Math.max(2,Ee-3),j="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,M-j.length));T?n.brightBlue.noFormat(`\u256D${j}${Q}\u256E`):n.dim.noFormat(`\u256D${j}${Q}\u256E`),n.styleReset()},Pr=()=>{Ee=tn(n),Ws=Math.max(10,Ee-LS);let T=_.state();Uo=xs(T.buffer,Ws);let M=Us(Uo,T,OM);Jt=M.rendered,Ar=M.windowStart,fd=M.cursorVisualRow,pd=M.cursorVisualCol},Ko=(T,M)=>{Ee=tn(n);let j=Math.max(2,Ee-3),Q=Uo[T],ie="";Q&&(ie=(_.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let oe=Math.max(0,j-1-ie.length),Ie=" ".repeat(oe);M?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${ie}${Ie}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${ie}${Ie}`),n.dim.noFormat("\u2502")),n.styleReset()},yd=T=>{Ee=tn(n);let M=Math.max(2,Ee-3),j="\u2500".repeat(M);T?n.brightBlue.noFormat(`\u2570${j}\u256F`):n.dim.noFormat(`\u2570${j}\u256F`),n.styleReset()},Mr=()=>3+pd,_r=()=>2+(fd-Ar),Gs=()=>{let T=E==="input";Be(()=>{T&&n.hideCursor(),n.moveTo(1,1),gd(T);for(let M=0;M<Jt;M++)n.moveTo(1,2+M),Ko(Ar+M,T);n.moveTo(1,2+Jt),yd(T),T&&(n.moveTo(Mr(),_r()),n.hideCursor(!1))})},Jo=()=>{Be(()=>{n.hideCursor();for(let T=0;T<Jt;T++)n.moveTo(1,2+T),Ko(Ar+T,!0);n.moveTo(Mr(),_r()),n.hideCursor(!1)})},Yt={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},At=(T,M)=>{let j=H[T];if(!j)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=tn(n),ie=Math.max(20,Q-bh),oe=ut(j.sessionId),Ie=j.title??lt(j.cwd),De=M&&j.snippets.length>1?` [${B+1}/${j.snippets.length}]`:M&&j.totalMatches>j.snippets.length?` [${j.snippets.length} of ${j.totalMatches}]`:"",$e=`${oe} ${j.status==="warm"?"warm":"cold"}`,Ze=Math.max(5,ie-$e.length-De.length-2),ze=Da(Ie,Ze),ts=`${$e} ${ze}${De}`.padEnd(ie),mt=j.snippets[M?B:0],Rn=mt?Yt[mt.kind]??mt.kind:"",Zs=mt?.toolName?`${Rn} \xB7 ${mt.toolName}`:Rn,er=Math.max(10,ie-Zs.length-6),on=mt?Da(mt.text,er):"",Br=mt?` ${Zs} ${on}`:" (no snippet)";return{rowBudget:ie,line1:ts,line2:Br.padEnd(ie+bh),focusedRow:M}},Vo=(T,M)=>{let{line1:j,focusedRow:Q}=At(T,M);Q?n.brightWhite.bgBlue.noFormat(`\u276F ${j}`):n.noFormat(` ${j}`),n.styleReset()},Ai=(T,M)=>{let{line2:j}=At(T,M);n.dim.noFormat(j),n.styleReset()},Ys=()=>{if(U)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=P?" \xB7 truncated":"",j=T>0?` ${T} ${T===1?"session":"sessions"} match${M} \xB7 `:" ";n.dim.noFormat(`${j}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Qn=()=>{Pr();let T=E==="input",M=_.state().buffer.join(`
|
|
228
|
+
`);Be(()=>{n.hideCursor(),he.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),gd(T);for(let Q=0;Q<Jt;Q++)n.moveTo(1,2+Q),Ko(Ar+Q,T);n.moveTo(1,2+Jt),yd(T);let j=H.length;if(j===0)n.moveTo(1,sn()),U||(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,sn()+1),Ys();else{zo();let Q=Gt(),ie=E!=="input";for(let oe=0;oe<Q;oe++){let Ie=bt+oe;n.moveTo(1,sn()+oe*2),Ie<j?Vo(Ie,ie&&Ie===$):n.eraseLineAfter(),n.moveTo(1,sn()+oe*2+1),Ie<j?Ai(Ie,ie&&Ie===$):n.eraseLineAfter()}n.moveTo(1,sn()+Q*2),Ys()}T&&(n.moveTo(Mr(),_r()),n.hideCursor(!1))})},Xn=(T,M)=>{let j=T-bt;j<0||j>=Gt()||Be(()=>{n.moveTo(1,sn()+j*2),Vo(T,M),n.moveTo(1,sn()+j*2+1),Ai(T,M)})},Ci=()=>{Be(()=>{n.moveTo(1,sn()+Gt()*2),Ys()})},wd=()=>{Be(()=>{let T=Gt(),M=H.length,j=E!=="input";for(let Q=0;Q<T;Q++){let ie=bt+Q;n.moveTo(1,sn()+Q*2),ie<M?Vo(ie,j&&ie===$):n.eraseLineAfter(),n.moveTo(1,sn()+Q*2+1),ie<M?Ai(ie,j&&ie===$):n.eraseLineAfter()}n.moveTo(1,sn()+T*2),Ys()})},Go=()=>_.state().buffer.join(`
|
|
229
|
+
`),Yo=T=>{let M=Jt;_.feed({type:"paste",text:T}),Pr(),Jt!==M?Qn():Jo()},bd=async()=>{let T=Go().trim();if(T.length!==0){if(a.length===0){N="no sessions in view to search",Qn();return}U=!0,N=null,Qn();try{let M=await jw(e.target,T,{sessionIds:a.map(j=>j.sessionId)});H=M.results,P=M.truncated,$=0,B=0,bt=0,E=M.results.length>0?"results":"input",Pr()}catch(M){N=`search failed: ${M.message}`}finally{U=!1,Qn()}}},Qo=()=>{},Rs=()=>{Be(()=>{let T=f===0;T&&n.hideCursor(),he.paintRow(vn,I(),()=>{Si()}),he.paintRow(Ae(),qo(),()=>{ki()});for(let M=0;M<_t;M++){let j=bn+M;he.paintRow(In(M),Vs(j),()=>{Cr(j)})}T&&(jt(),n.hideCursor(!1))})},Ts=()=>{Be(()=>{he.paintRow(Ae()+1,md(),()=>Ii())})},xn=()=>{Y!==null&&(Y=null,Ts())},Qt=()=>{Be(()=>{let T=We.state();Mt=xs(T.buffer,Pe);let M=Us(Mt,T,dd);bn=M.windowStart,xr=M.cursorVisualRow,bi=M.cursorVisualCol;let j=f===0;j&&n.hideCursor();for(let Q=0;Q<_t;Q++){let ie=bn+Q;he.paintRow(In(Q),Vs(ie),()=>{Cr(ie)})}j&&(jt(),n.hideCursor(!1))})},Qs=async()=>{let T=await Al();if(!T.ok){X=T.reason,ke();return}if(T.kind!=="image"){let M=We.state(),j=[...M.buffer],Q=M.row,ie=M.col;We.feed({type:"paste",text:T.text});let oe=We.state();if(j.length!==oe.buffer.length||Q!==oe.row||ie!==oe.col||!j.every((De,$e)=>De===oe.buffer[$e])){let De=xs(oe.buffer,Pe);Us(De,oe,dd).rendered!==_t?Ve():Qt()}return}We.addAttachment(T.attachment),X=`attached ${T.attachment.name??"image"}`,Ve()},$r=T=>{T<p||T>=p+Je||Be(()=>{he.paintRow(Tr(T),Er(T),()=>{kn(T)})})},Ct=()=>{Be(()=>{for(let T=0;T<Je;T++){let M=Bn()+1+T,j=p+T;j<a.length?he.paintRow(M,Er(j),()=>{kn(j)}):he.paintRow(M,"blank",()=>{})}ke()})},Fr=()=>{Be(()=>{he.paintRow(Bn(),xi(),()=>{n.dim.noFormat(` ${On}`)});for(let T=0;T<Je;T++){let M=Bn()+1+T,j=p+T;j<a.length?he.paintRow(M,Er(j),()=>{kn(j)}):he.paintRow(M,"blank",()=>{})}ke(),f===0&&(jt(),n.hideCursor(!1))})},Zn=!1,es="",Xo=0,Zo=200,Or=null,Es=!1,An=null,Ri=!1,Cn=null,Ti=!1,rn=null,ea=null,Lr=null,Xs=T=>{let M=T.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let Q=M.indexOf("\x1B[I"),ie=M.indexOf("\x1B[O"),oe=Q===-1?ie:ie===-1?Q:Math.min(Q,ie);if(oe===-1)break;let Ie=$t;$t=oe===Q,$t&&(Xo=Date.now()),Ie!==$t&&!xt&&me.length<=1&&Be(()=>{Rs(),Ct()}),M=M.slice(0,oe)+M.slice(oe+"\x1B[I".length)}if(M.length===0)return}if(!Zn&&M===""&&ea){ea();return}if(!Zn&&(M===""||M==="\x1B_"||M==="\x1B")){Lr?.(M);return}if(Zn){let Q=M.indexOf(qa);if(Q===-1){es+=M;return}es+=M.slice(0,Q),Zn=!1;let ie=Buffer.from(es,"binary").toString("utf-8").replace(/\r\n?/g,`
|
|
230
|
+
`);es="";let oe=M.slice(Q+qa.length);if(A)E==="input"&&!U&&Yo(ie);else if(f===0&&!h){let Ie=We.feed({type:"paste",text:ie});for(let ze of Ie)ze.type==="attachment-request"&&Qs();let De=We.state(),$e=xs(De.buffer,Pe);Us($e,De,dd).rendered!==_t?Ve():Qt()}oe.length>0&&rn&&rn(Buffer.from(oe,"binary"));return}let j=M.indexOf(Eo);if(j===-1){rn?.(T);return}j>0&&rn?.(Buffer.from(M.slice(0,j),"binary")),M=M.slice(j+Eo.length),Zn=!0,M.length>0&&Xs(Buffer.from(M,"binary"))};return Ve(),await new Promise(T=>{let M=null,j=!1,Q=null,ie=!1,oe=me,Ie=F=>{oe.push(F)},De=()=>{oe.pop(),xt||oe[oe.length-1]?.onResize()},$e={push:Ie,pop:De},Ze=()=>{let F={kind:"new",cwd:r},z=We.state().attachments;return z.length>0&&(F.attachments=[...z]),Ht&&(F.agentId=Ht),ot&&(F.model=ot),F},ze=async()=>{dn(),he.clearCache(),Ie({onKey:()=>{},onResize:()=>{}});let z;try{z=await yi(n,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{De(),Ft()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=zl(i,r),Vt()),xt||Ve()},ts=async()=>{let F=e.availableAgents;if(!F||F.length===0)return;dn(),he.clearCache(),Ie({onKey:()=>{},onResize:()=>{}});let ce;try{ce=await Za(n,F,Ht,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{De(),Ft()}if(ce.kind==="select"){Ht=ce.agentId;let V=e.config.defaultModels;if(ot=V?V[ce.agentId]:void 0,ce.persist)try{await Di(ce.agentId)}catch{}}xt||Ve()};Qo=()=>{_=new Bs({history:[],collapsePastes:!1}),H=[],P=!1,$=0,B=0,bt=0,N=null,U=!1,E="input",A=!1,De()};let mt=(F,z,ce)=>{vd(),oe[oe.length-1]?.onKey(F,z,ce)},Rn=()=>{xt||oe[oe.length-1]?.onResize()};Lr=F=>{xt||oe[oe.length-1]?.onKey(F,null,{})};let Zs=!1,er=()=>{if(Zs)return;Zs=!0,oe.length=0,M&&(clearInterval(M),M=null),Q&&(Q.abort(),Q=null,j=!1),n.off("key",mt),n.off("mouse",ft),n.off("resize",Rn),process.stdout.write(Os),process.stdout.write(za);let F=n;F.stdin&&rn&&(F.stdin.removeListener("data",Xs),F.stdin.on("data",rn),rn=null),Zn=!1,es="",n.grabInput(!1),re({src:"grab",site:"picker.detachInput",on:!1})},on=()=>{xt||(xt=!0,er(),n.hideCursor(!1),n.moveTo(1,wt()+1),n(`
|
|
231
|
+
`))},Br=()=>{if(xt||oe.length>1||v!=="normal"||h||ie)return;j&&Q&&(Q.abort(),Q=null,j=!1);let F=f>0?a[f-1]?.sessionId:void 0;j=!0;let z=new AbortController;Q=z,an(F,{silent:!0,signal:z.signal}).finally(()=>{Q===z&&(Q=null),j=!1})},vd=()=>{xt||(M&&clearInterval(M),M=setInterval(Br,3e3))},Nn=()=>(er(),Wl("",{write(z){pe=z,Ts()},finalize(){pe=null,on()}})),at=()=>(on(),T({kind:qs?"exit":"abort"}),!0),ns=()=>{let F=c.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
|
|
232
|
+
`);return`${f}:${p}:${X??""}
|
|
233
|
+
${F}`},an=async(F,z={})=>{try{let ce=z.silent?ns():"",V=u,ue=await Wn(e.target,{includeNonInteractive:!0,signal:z.signal}),le=F??(f>0?a[f-1]?.sessionId:void 0);if(i=zl(ue,r),Vt(),le!==void 0){let je=a.findIndex(Fe=>Fe.sessionId===le);je>=0?f=je+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+Je>a.length&&(p=Math.max(0,a.length-Je)),Sn(),z.silent&&ns()===ce)return;u===V?Fr():Ve()}catch(ce){if(z.silent)return;X=`refresh failed: ${ce.message}`,Ve()}},tr=async F=>{if(!k)return;let z=k;v="busy",ke();try{await Dw(e.target,z.sessionId,F),v="normal",k=null,G=null,await an(z.sessionId)}catch(ce){v="normal",k=null,G=null,X=`rename failed: ${ce.message}`,ke()}},ss=async F=>{try{await Uw(e.target,F.sessionId),X="title regen queued (press r to refresh)",ke()}catch(z){X=`regen failed: ${z.message}`,ke()}},Ei=async F=>{let ce=(F.priority&&F.priority>0?F.priority:0)>0?null:1,V=ce??0;for(let le of i)le.sessionId===F.sessionId&&(le.priority=V>0?V:void 0);let ue=F.sessionId;i=zl(i,r),Vt(),As(ue),Ve(),X=V>0?"priority: high":"priority: normal",ke();try{await Hw(e.target,F.sessionId,ce)}catch(le){X=`priority failed: ${le.message}`,ke()}},Sd=async()=>{if(ie)return;ie=!0;let F=f>0?a[f-1]?.sessionId:void 0;X="syncing agents\u2026",ke();try{let{synced:z,skipped:ce,agents:V}=await Nw(e.target);await an(F),X=`synced ${z} new (${ce} known) from ${V} agent${V===1?"":"s"}`,ke()}catch(z){X=`sync failed: ${z.message}`,ke()}finally{ie=!1}},Nr=async F=>{if(!k)return;let z=k;v="busy",ke();try{F==="kill"?await bs(e.target,z.sessionId):await qw(e.target,z.sessionId),v="normal",k=null,z.sessionId===e.currentSessionId&&(qs=!0);let ce;if(F==="kill")ce=z.sessionId;else{let V=a.findIndex(ue=>ue.sessionId===z.sessionId);V>=0&&(ce=a[V+1]?.sessionId??a[V-1]?.sessionId)}await an(ce)}catch(ce){v="normal",k=null,X=`${F} failed: ${ce.message}`,ke()}},qt=(F,z)=>{F===0!=(z===0)&&(Rs(),z===0?(n.hideCursor(!1),jt()):n.hideCursor())},vt=F=>{let z=Math.min(u-1,Math.max(0,f+F));if(z===f)return;let ce=f;f=z,Sn(),Be(()=>{Ct(),qt(ce,f)})},Dr=()=>X===null?!1:(X=null,ke(),!0),Pi=()=>{Wo(),Ie({onKey:F=>{if(F==="CTRL_C"){on(),T({kind:"abort"});return}De()},onResize:()=>Wo()})},Mi=F=>{let z=null,ce=null,V=!0,ue=()=>{Be(()=>{if(n.hideCursor(),he.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(` Session info \u2014 ${ut(F.sessionId)}`)(`
|
|
234
234
|
|
|
235
235
|
`),V)n.dim.noFormat(" loading\u2026")(`
|
|
236
236
|
`);else if(ce!==null)n.brightRed.noFormat(` ${ce}`)(`
|
|
237
237
|
`);else if(z!==null)for(let Fe of z)n.noFormat(` ${Fe}`)(`
|
|
238
238
|
`);n(`
|
|
239
239
|
`),n.dim.noFormat(" Esc / ^C to return")(`
|
|
240
|
-
`)})};ue();let le=new AbortController,je={onKey:Fe=>{if(Fe==="ESCAPE"||Fe==="CTRL_C"){le.abort(),De();return}},onResize:()=>ue()};Ie(je),(async()=>{try{let Fe=await wn(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(
|
|
241
|
-
`)}catch(Fe){if(le.signal.aborted)return;ce=`failed to load info: ${Fe.message}`}finally{V=!1,!It&&oe[oe.length-1]===je&&ue()}})()},tr=()=>{if(a.length===0){X="no sessions to search",ke();return}P=new Ns({history:[],collapsePastes:!1}),H=[],_=!1,F=0,B=0,bt=0,N=null,q=!1,E="input",A=!0,Pr(),Qn(),Ie({onKey:(z,ce,V)=>{if(E==="input"){if(q)return;if(z==="ESCAPE"||z==="CTRL_C"){Qo();return}if(z==="ENTER"||z==="KP_ENTER"){if(Go().trim().length===0)return;bd();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&H.length>0){E="results",F=0,B=0,Be(()=>{Vs(),Xn(0,!0),Ci(),n.hideCursor()});return}let ue=P.state(),le=[...ue.buffer],je=ue.row,Fe=ue.col,Me=null;if(z==="")Me={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")Me={type:"key",name:"alt-underscore"};else if(V?.isCharacter)Me={type:"char",ch:z};else{let Ge=Nl(z);Ge!==null&&(Me={type:"key",name:Ge})}if(Me===null){n.moveTo(Mr(),_r());return}P.feed(Me);let dt=P.state();if(le.length===dt.buffer.length&&le.every((Ge,Re)=>Ge===dt.buffer[Re])&&je===dt.row&&Fe===dt.col){n.moveTo(Mr(),_r());return}let rs=Kt;Pr(),Kt!==rs?Qn():Jo();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){Qo();return}if(z==="CTRL_F"){E="input",wd(),Ci(),Vs();return}if(z==="ENTER"||z==="KP_ENTER"){let le=H[F];if(!le)return;let je=a.find(Me=>Me.sessionId===le.sessionId);if(!!je?.importedFromMachine&&!je.upstreamSessionId){on();let Me={kind:"attach",sessionId:le.sessionId};je.agentId!==void 0&&(Me.agentId=je.agentId),T(Me);return}(async()=>{let Me=await ES(n,{sessionId:le.sessionId,title:le.title,cwd:le.cwd},$e);if(Me==="cancel"){on(),T({kind:"abort"});return}if(Me==="back")return;on();let dt={kind:"attach",sessionId:le.sessionId,readonly:Me==="view"};je?.agentId!==void 0&&(dt.agentId=je.agentId),T(dt)})();return}if(V?.isCharacter&&(z==="n"||z==="N")){let le=H[F];if(!le||le.snippets.length<=1)return;B=(B+1)%le.snippets.length,Xn(F,!0);return}if(V?.isCharacter&&(z==="p"||z==="P")){let le=H[F];if(!le||le.snippets.length<=1)return;B=(B-1+le.snippets.length)%le.snippets.length,Xn(F,!0);return}let ue=le=>{if(le<0&&F===0){E="input",Be(()=>{Xn(0,!1),Ci(),Vs()});return}let je=Math.min(H.length-1,Math.max(0,F+le));if(je===F)return;let Fe=F,Me=bt;F=je,B=0,zo(),bt!==Me?wd():(Be(()=>{Xn(Fe,!1),Xn(F,!0)}),Ci())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":ue(-1);return;case"DOWN":case"TAB":case"CTRL_N":ue(1);return;case"PAGE_UP":ue(-Vt());return;case"PAGE_DOWN":ue(Vt());return;case"HOME":ue(-F);return;case"END":ue(H.length);return}return}},onResize:()=>Qn()})},Hr=($,z,ce)=>{if(v!=="busy"){if($==="CTRL_O"){ze();return}if($==="CTRL_L"){Rs();return}if(v==="rename"&&Q){if($==="ENTER"||$==="KP_ENTER"){let V=Q.text.trim();if(V.length===0){v="normal",k=null,Q=null,ke();return}er(V);return}if($==="ESCAPE"||$==="CTRL_C"){v="normal",k=null,Q=null,ke();return}if(Q.handleKey($,ce?.isCharacter===!0)){ke();return}return}if(v==="confirm-kill"||v==="confirm-delete"){if(ce?.isCharacter&&($==="y"||$==="Y")){Nr(v==="confirm-kill"?"kill":"delete");return}if($==="ESCAPE"||$==="CTRL_C"||$==="ENTER"||$==="KP_ENTER"||ce?.isCharacter&&($==="n"||$==="N")){v="normal",k=null,ke();return}return}if(Dr(),yt&&(yt=!1,u=0,Be(()=>{Ts(),At()})),$==="CTRL_F"&&u!==0){tr();return}if(u===0&&!h){if($==="ESCAPE"){at();return}if($==="ENTER"||$==="KP_ENTER"){let Re=We.expandedText(),ct=Ze();Re.trim().length>0&&(ct.prompt=Re),ct.installStatus=Nn(),T(ct);return}if($==="UP"&&w){let Re=Date.now(),ct=Re-b;if(b=Re,ct<y){jt();return}w=!1}if($==="DOWN"){let Re=We.state(),ct=Re.historyIndex!==-1||Re.queueIndex!==-1,Dn=Mt.length===0||xr===Mt.length-1;if(!ct&&Dn&&a.length>0){vt(1);return}}if($==="PAGE_DOWN"&&(Mt.length===0||xr===Mt.length-1)&&a.length>0){vt(1);return}if($==="CTRL_P"){a.length>0&&vt(1);return}if(w=!1,$==="TAB"){let Re=We.state(),ct=Re.buffer[Re.row]??"",Dn=jl(ct,Re.col);if(Dn!==null){let cn=ql(Dn.token,r);if(cn!==null){if(cn.replacement!==Dn.token&&(We.replaceRangeOnCurrentLine(Dn.start,Re.col,cn.replacement),Yt()),cn.candidates.length>1){let Ms=cn.candidates.join(" ");G=`${cn.candidates.length} matches: ${Ms}`,Es()}else xn();jt();return}}}xn();let V=We.state(),ue=[...V.buffer],le=V.row,je=V.col,Fe=null;if($==="")Fe={type:"key",name:"ctrl-underscore"};else if($==="\x1B_"||$==="\x1B")Fe={type:"key",name:"alt-underscore"};else if(ce?.isCharacter)Fe={type:"char",ch:$};else{let Re=Nl($);Re!==null&&(Fe={type:"key",name:Re})}if(Fe===null){jt();return}let Me=We.feed(Fe),dt=We.state(),Xt=ue.length===dt.buffer.length&&ue.every((Re,ct)=>Re===dt.buffer[ct])&&le===dt.row&&je===dt.col;if(Me.some(Re=>Re.type==="exit")){at();return}for(let Re of Me)Re.type==="attachment-request"&&Ys();if(Xt){jt();return}let rs=As(dt.buffer,Pe);if(Hs(rs,dt,dd).rendered!==_t){Ve();return}Yt();return}if(!h&&ce?.isCharacter&&$==="?"){Pi();return}if(h){if(ce?.isCharacter){m+=$,Jt(),Ve();return}if($==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Jt(),Ve()):(h=!1,Jt(),Ve());return}if($==="ESCAPE"||$==="CTRL_C"){h=!1,m="",Jt(),Ve();return}}if(ce?.isCharacter){if($==="/"){h=!0,m="",Jt(),Ve();return}if($==="n"||$==="N"){vt(1);return}if($==="p"||$==="P"){vt(-1);return}if($==="c"||$==="C"){let V=u>0?a[u-1]:void 0,ue=Ze();V?.cwd&&(ue.cwd=V.cwd),ue.installStatus=Nn(),T(ue);return}if($==="q"||$==="Q"){at();return}if($==="o"||$==="O"){let V=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Jt(),Cs(V),Ve();return}if($==="h"||$==="H"){let V=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=BS(s.filters.hostFilter,i),Jt(),Cs(V),Ve();return}if($==="i"&&u>0){let V=a[u-1];if(!V)return;Mi(V);return}if($==="I"){let V=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Jt(),Cs(V),Ve();return}if($==="r"||$==="R"){let V=u>0?a[u-1]?.sessionId:void 0;an(V);return}if($==="s"||$==="S"){Sd();return}if(($==="v"||$==="V")&&u>0){let V=a[u-1];if(!V)return;let ue={kind:"attach",sessionId:V.sessionId,readonly:!0};V.agentId!==void 0&&(ue.agentId=V.agentId),ue.installStatus=Nn(),T(ue);return}if(($==="f"||$==="F")&&u>0){let V=a[u-1];if(!V)return;on();let ue={kind:"fork",sourceSessionId:V.sessionId,sourceCwd:V.cwd};V.agentId!==void 0&&(ue.sourceAgentId=V.agentId),V.importedFromMachine!==void 0&&(ue.sourceImportedFromMachine=V.importedFromMachine),V.upstreamSessionId!==void 0&&(ue.sourceUpstreamSessionId=V.upstreamSessionId),T(ue);return}if(($==="k"||$==="K")&&u>0){let V=a[u-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},v="confirm-kill",ke();return}if($==="t"&&u>0){let V=a[u-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},Q=new Do(V.title??""),v="rename",ke();return}if($==="T"&&u>0){let V=a[u-1];if(!V)return;ss({sessionId:V.sessionId});return}if($==="*"&&u>0){let V=a[u-1];if(!V)return;Ei(V);return}if(($==="d"||$==="D")&&u>0){let V=a[u-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},v="confirm-delete",ke();return}yt=!1,u=0,We.feed({type:"char",ch:$}),Ve();return}switch($){case"UP":case"SHIFT_TAB":case"CTRL_P":$==="UP"&&(u===1&&(w=!0),b=Date.now()),vt(-1);return;case"DOWN":case"TAB":case"CTRL_N":vt(1);return;case"PAGE_UP":vt(-Je);return;case"PAGE_DOWN":vt(Je);return;case"HOME":vt(1-u);return;case"END":vt(f);return;case"RIGHT":if(yt||u===0)break;case"ENTER":case"KP_ENTER":{if(yt){let le=We.expandedText(),je=Ze();le.trim().length>0&&(je.prompt=le),je.installStatus=Nn(),T(je);return}if(u===0){let le=Ze();le.installStatus=Nn(),T(le);return}let V=a[u-1];if(!V){on(),T({kind:"abort"});return}let ue={kind:"attach",sessionId:V.sessionId};V.agentId!==void 0&&(ue.agentId=V.agentId),ue.installStatus=Nn(),T(ue);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":at();return}}};Ie({onKey:($,z,ce)=>Hr($,z,ce),onResize:()=>{It||Ve()}});let mt=($,z)=>{if(It||oe.length!==1||v!=="normal")return;let ce=$==="MOUSE_MOTION",V=$==="MOUSE_LEFT_BUTTON_PRESSED",ue=$==="MOUSE_LEFT_BUTTON_RELEASED",le=$==="MOUSE_WHEEL_UP",je=$==="MOUSE_WHEEL_DOWN",Fe=$t&&Date.now()-Xo<Zo,Me=!$t||Fe;if(V){Or={x:z?.x??-1,y:z?.y??-1},Ps=Me;return}if(ce&&Me)return;let dt=ue&&Or!==null&&z?.x===Or.x&&z?.y===Or.y,Xt=dt&&!Ps,rs=dt&&Ps;if(ue&&(Or=null,Ps=!1,!dt))return;if(le||je){if(a.length===0)return;let Ke=le?-3:3,Ye=Math.max(0,a.length-Je),os=Math.min(Ye,Math.max(0,p+Ke));if(os===p)return;if(p=os,u>0){let ta=u-1;ta<p?u=p+1:ta>=p+Je&&(u=p+Je)}At();return}if(!ce&&!Xt)return;let Ge=z?.y;if(typeof Ge!="number")return;{let Ke=z?.x,Ye=An!==null&&Ge===wt()&&typeof Ke=="number"&&Ke>=An.start&&Ke<=An.end,os=Cn!==null&&Ge===wt()&&typeof Ke=="number"&&Ke>=Cn.start&&Ke<=Cn.end;(Ye!==Ri||os!==Ti)&&(Ri=Ye,Ti=os,ke(),u===0?(jt(),n.hideCursor(!1)):n.hideCursor(!0))}if(Xt&&An!==null&&Ge===wt()){let Ke=z?.x;if(typeof Ke=="number"&&Ke>=An.start&&Ke<=An.end){at();return}}if(Xt&&Cn!==null&&Ge===wt()){let Ke=z?.x;if(typeof Ke=="number"&&Ke>=Cn.start&&Ke<=Cn.end){let Ye=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=BS(s.filters.hostFilter,i),Jt(),Cs(Ye),Ve();return}}if(Ge>=vn&&Ge<=Ae()){let Ke=null;if(Ge===vn){let Ye=z?.x;typeof Ye=="number"&&(Yn!==null&&Ye>=Yn.start&&Ye<=Yn.end?Ke="agent":Gn!==null&&Ye>=Gn.start&&Ye<=Gn.end&&(Ke="cwd"))}if(Ke!==Ut&&(Ut=Ke,Ts()),Xt&&Ge===vn){if(Ut==="agent"){ts();return}if(Ut==="cwd"){ze();return}}if((Xt||rs)&&u!==0){yt=!1;let Ye=u;u=0,Be(()=>{At(),Qt(Ye,u)});return}ce&&!yt&&u!==0&&(yt=!0,Be(()=>{Ts(),At()}));return}Ut!==null&&(Ut=null,Ts()),yt&&(yt=!1,Be(()=>{Ts(),At()}));let ct=Bn()+1,Dn=ct+Je-1;if(Ge<ct||Ge>Dn)return;let cn=p+(Ge-ct);if(cn<0||cn>=a.length)return;let Ms=a[cn];if(!Ms)return;let Ur=cn+1;if(ce&&u===0)return;let Ql=u===0,is=u===Ur;if(rs&&u!==Ur){let Ke=u;u=Ur,Sn(),Be(()=>{At(),Qt(Ke,u)});return}if(rs)return;if(u!==Ur){let Ke=u;u=Ur,Sn(),Be(()=>{At(),Qt(Ke,u)})}if(!Xt||Ql||!is)return;let _i={kind:"attach",sessionId:Ms.sessionId};Ms.agentId!==void 0&&(_i.agentId=Ms.agentId),_i.installStatus=Nn(),T(_i)},Ft=()=>{n.grabInput({mouse:"motion"}),re({src:"grab",site:"picker.installGrab",on:!0});let $=n;$.stdin&&typeof $.onStdin=="function"&&(rn=$.onStdin,$.stdin.removeListener("data",$.onStdin),$.stdin.on("data",Qs),process.stdout.write(ll),process.stdout.write(pl)),n.on("key",ht),n.on("mouse",mt),n.on("resize",Rn)},dn=()=>{process.stdout.write(Ls),process.stdout.write(za);let $=n;$.stdin&&rn&&($.stdin.removeListener("data",Qs),$.stdin.on("data",rn),rn=null),Zn=!1,es="",n.off("key",ht),n.off("mouse",mt),n.off("resize",Rn),n.grabInput(!1),re({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Ft(),process.platform!=="win32"){let $=!1,z=()=>{$&&($=!1,n.fullscreen(!0),t(),n.hideCursor(),Ft(),It||Rs())};ea=()=>{$||It||($=!0,dn(),n.fullscreen(!1),process.stdout.write(`${Wa}${ul}
|
|
240
|
+
`)})};ue();let le=new AbortController,je={onKey:Fe=>{if(Fe==="ESCAPE"||Fe==="CTRL_C"){le.abort(),De();return}},onResize:()=>ue()};Ie(je),(async()=>{try{let Fe=await wn(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(F.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:le.signal});if(!Fe.ok)throw new Error(`daemon returned HTTP ${Fe.status}`);let Me=await Fe.json(),dt=qn(Me),Xt=lp(dt,F.status);z=tl(Xt,!1).replace(/\n$/,"").split(`
|
|
241
|
+
`)}catch(Fe){if(le.signal.aborted)return;ce=`failed to load info: ${Fe.message}`}finally{V=!1,!xt&&oe[oe.length-1]===je&&ue()}})()},nr=()=>{if(a.length===0){X="no sessions to search",ke();return}_=new Bs({history:[],collapsePastes:!1}),H=[],P=!1,$=0,B=0,bt=0,N=null,U=!1,E="input",A=!0,Pr(),Qn(),Ie({onKey:(z,ce,V)=>{if(E==="input"){if(U)return;if(z==="ESCAPE"||z==="CTRL_C"){Qo();return}if(z==="ENTER"||z==="KP_ENTER"){if(Go().trim().length===0)return;bd();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&H.length>0){E="results",$=0,B=0,Be(()=>{Gs(),Xn(0,!0),Ci(),n.hideCursor()});return}let ue=_.state(),le=[...ue.buffer],je=ue.row,Fe=ue.col,Me=null;if(z==="")Me={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")Me={type:"key",name:"alt-underscore"};else if(V?.isCharacter)Me={type:"char",ch:z};else{let Ge=Nl(z);Ge!==null&&(Me={type:"key",name:Ge})}if(Me===null){n.moveTo(Mr(),_r());return}_.feed(Me);let dt=_.state();if(le.length===dt.buffer.length&&le.every((Ge,Re)=>Ge===dt.buffer[Re])&&je===dt.row&&Fe===dt.col){n.moveTo(Mr(),_r());return}let rs=Jt;Pr(),Jt!==rs?Qn():Jo();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){Qo();return}if(z==="CTRL_F"){E="input",wd(),Ci(),Gs();return}if(z==="ENTER"||z==="KP_ENTER"){let le=H[$];if(!le)return;let je=a.find(Me=>Me.sessionId===le.sessionId);if(!!je?.importedFromMachine&&!je.upstreamSessionId){on();let Me={kind:"attach",sessionId:le.sessionId};je.agentId!==void 0&&(Me.agentId=je.agentId),T(Me);return}(async()=>{let Me=await ES(n,{sessionId:le.sessionId,title:le.title,cwd:le.cwd},$e);if(Me==="cancel"){on(),T({kind:"abort"});return}if(Me==="back")return;on();let dt={kind:"attach",sessionId:le.sessionId,readonly:Me==="view"};je?.agentId!==void 0&&(dt.agentId=je.agentId),T(dt)})();return}if(V?.isCharacter&&(z==="n"||z==="N")){let le=H[$];if(!le||le.snippets.length<=1)return;B=(B+1)%le.snippets.length,Xn($,!0);return}if(V?.isCharacter&&(z==="p"||z==="P")){let le=H[$];if(!le||le.snippets.length<=1)return;B=(B-1+le.snippets.length)%le.snippets.length,Xn($,!0);return}let ue=le=>{if(le<0&&$===0){E="input",Be(()=>{Xn(0,!1),Ci(),Gs()});return}let je=Math.min(H.length-1,Math.max(0,$+le));if(je===$)return;let Fe=$,Me=bt;$=je,B=0,zo(),bt!==Me?wd():(Be(()=>{Xn(Fe,!1),Xn($,!0)}),Ci())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":ue(-1);return;case"DOWN":case"TAB":case"CTRL_N":ue(1);return;case"PAGE_UP":ue(-Gt());return;case"PAGE_DOWN":ue(Gt());return;case"HOME":ue(-$);return;case"END":ue(H.length);return}return}},onResize:()=>Qn()})},Hr=(F,z,ce)=>{if(v!=="busy"){if(F==="CTRL_O"){ze();return}if(F==="CTRL_L"){Cs();return}if(v==="rename"&&G){if(F==="ENTER"||F==="KP_ENTER"){let V=G.text.trim();if(V.length===0){v="normal",k=null,G=null,ke();return}tr(V);return}if(F==="ESCAPE"||F==="CTRL_C"){v="normal",k=null,G=null,ke();return}if(G.handleKey(F,ce?.isCharacter===!0)){ke();return}return}if(v==="confirm-kill"||v==="confirm-delete"){if(ce?.isCharacter&&(F==="y"||F==="Y")){Nr(v==="confirm-kill"?"kill":"delete");return}if(F==="ESCAPE"||F==="CTRL_C"||F==="ENTER"||F==="KP_ENTER"||ce?.isCharacter&&(F==="n"||F==="N")){v="normal",k=null,ke();return}return}if(Dr(),yt&&(yt=!1,f=0,Be(()=>{Rs(),Ct()})),F==="CTRL_F"&&f!==0){nr();return}if(f===0&&!h){if(F==="ESCAPE"){at();return}if(F==="ENTER"||F==="KP_ENTER"){let Re=We.expandedText(),ct=Ze();Re.trim().length>0&&(ct.prompt=Re),ct.installStatus=Nn(),T(ct);return}if(F==="UP"&&w){let Re=Date.now(),ct=Re-b;if(b=Re,ct<y){jt();return}w=!1}if(F==="DOWN"){let Re=We.state(),ct=Re.historyIndex!==-1||Re.queueIndex!==-1,Dn=Mt.length===0||xr===Mt.length-1;if(!ct&&Dn&&a.length>0){vt(1);return}}if(F==="PAGE_DOWN"&&(Mt.length===0||xr===Mt.length-1)&&a.length>0){vt(1);return}if(F==="CTRL_P"){a.length>0&&vt(1);return}if(w=!1,F==="TAB"){let Re=We.state(),ct=Re.buffer[Re.row]??"",Dn=jl(ct,Re.col);if(Dn!==null){let cn=ql(Dn.token,r);if(cn!==null){if(cn.replacement!==Dn.token&&(We.replaceRangeOnCurrentLine(Dn.start,Re.col,cn.replacement),Qt()),cn.candidates.length>1){let Ps=cn.candidates.join(" ");Y=`${cn.candidates.length} matches: ${Ps}`,Ts()}else xn();jt();return}}}xn();let V=We.state(),ue=[...V.buffer],le=V.row,je=V.col,Fe=null;if(F==="")Fe={type:"key",name:"ctrl-underscore"};else if(F==="\x1B_"||F==="\x1B")Fe={type:"key",name:"alt-underscore"};else if(ce?.isCharacter)Fe={type:"char",ch:F};else{let Re=Nl(F);Re!==null&&(Fe={type:"key",name:Re})}if(Fe===null){jt();return}let Me=We.feed(Fe),dt=We.state(),Xt=ue.length===dt.buffer.length&&ue.every((Re,ct)=>Re===dt.buffer[ct])&&le===dt.row&&je===dt.col;if(Me.some(Re=>Re.type==="exit")){at();return}for(let Re of Me)Re.type==="attachment-request"&&Qs();if(Xt){jt();return}let rs=xs(dt.buffer,Pe);if(Us(rs,dt,dd).rendered!==_t){Ve();return}Qt();return}if(!h&&ce?.isCharacter&&F==="?"){Pi();return}if(h){if(ce?.isCharacter){m+=F,Vt(),Ve();return}if(F==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Vt(),Ve()):(h=!1,Vt(),Ve());return}if(F==="ESCAPE"||F==="CTRL_C"){h=!1,m="",Vt(),Ve();return}}if(ce?.isCharacter){if(F==="/"){h=!0,m="",Vt(),Ve();return}if(F==="n"||F==="N"){vt(1);return}if(F==="p"||F==="P"){vt(-1);return}if(F==="c"||F==="C"){let V=f>0?a[f-1]:void 0,ue=Ze();V?.cwd&&(ue.cwd=V.cwd),ue.installStatus=Nn(),T(ue);return}if(F==="q"||F==="Q"){at();return}if(F==="o"||F==="O"){let V=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Vt(),As(V),Ve();return}if(F==="h"||F==="H"){let V=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=BS(s.filters.hostFilter,i),Vt(),As(V),Ve();return}if(F==="i"&&f>0){let V=a[f-1];if(!V)return;Mi(V);return}if(F==="I"){let V=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Vt(),As(V),Ve();return}if(F==="r"||F==="R"){let V=f>0?a[f-1]?.sessionId:void 0;an(V);return}if(F==="s"||F==="S"){Sd();return}if((F==="v"||F==="V")&&f>0){let V=a[f-1];if(!V)return;let ue={kind:"attach",sessionId:V.sessionId,readonly:!0};V.agentId!==void 0&&(ue.agentId=V.agentId),ue.installStatus=Nn(),T(ue);return}if((F==="f"||F==="F")&&f>0){let V=a[f-1];if(!V)return;on();let ue={kind:"fork",sourceSessionId:V.sessionId,sourceCwd:V.cwd};V.agentId!==void 0&&(ue.sourceAgentId=V.agentId),V.importedFromMachine!==void 0&&(ue.sourceImportedFromMachine=V.importedFromMachine),V.upstreamSessionId!==void 0&&(ue.sourceUpstreamSessionId=V.upstreamSessionId),T(ue);return}if((F==="k"||F==="K")&&f>0){let V=a[f-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},v="confirm-kill",ke();return}if(F==="t"&&f>0){let V=a[f-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},G=new Do(V.title??""),v="rename",ke();return}if(F==="T"&&f>0){let V=a[f-1];if(!V)return;ss({sessionId:V.sessionId});return}if(F==="*"&&f>0){let V=a[f-1];if(!V)return;Ei(V);return}if((F==="d"||F==="D")&&f>0){let V=a[f-1];if(!V)return;k={sessionId:V.sessionId,cwd:V.cwd,status:V.status},v="confirm-delete",ke();return}yt=!1,f=0,We.feed({type:"char",ch:F}),Ve();return}switch(F){case"UP":case"SHIFT_TAB":case"CTRL_P":F==="UP"&&(f===1&&(w=!0),b=Date.now()),vt(-1);return;case"DOWN":case"TAB":case"CTRL_N":vt(1);return;case"PAGE_UP":vt(-Je);return;case"PAGE_DOWN":vt(Je);return;case"HOME":vt(1-f);return;case"END":vt(u);return;case"RIGHT":if(yt||f===0)break;case"ENTER":case"KP_ENTER":{if(yt){let le=We.expandedText(),je=Ze();le.trim().length>0&&(je.prompt=le),je.installStatus=Nn(),T(je);return}if(f===0){let le=Ze();le.installStatus=Nn(),T(le);return}let V=a[f-1];if(!V){on(),T({kind:"abort"});return}let ue={kind:"attach",sessionId:V.sessionId};V.agentId!==void 0&&(ue.agentId=V.agentId),ue.installStatus=Nn(),T(ue);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":at();return}}};Ie({onKey:(F,z,ce)=>Hr(F,z,ce),onResize:()=>{xt||Ve()}});let ft=(F,z)=>{if(xt||oe.length!==1||v!=="normal")return;let ce=F==="MOUSE_MOTION",V=F==="MOUSE_LEFT_BUTTON_PRESSED",ue=F==="MOUSE_LEFT_BUTTON_RELEASED",le=F==="MOUSE_WHEEL_UP",je=F==="MOUSE_WHEEL_DOWN",Fe=$t&&Date.now()-Xo<Zo,Me=!$t||Fe;if(V){Or={x:z?.x??-1,y:z?.y??-1},Es=Me;return}if(ce&&Me)return;let dt=ue&&Or!==null&&z?.x===Or.x&&z?.y===Or.y,Xt=dt&&!Es,rs=dt&&Es;if(ue&&(Or=null,Es=!1,!dt))return;if(le||je){if(a.length===0)return;let Ke=le?-3:3,Ye=Math.max(0,a.length-Je),os=Math.min(Ye,Math.max(0,p+Ke));if(os===p)return;if(p=os,f>0){let ta=f-1;ta<p?f=p+1:ta>=p+Je&&(f=p+Je)}Ct();return}if(!ce&&!Xt)return;let Ge=z?.y;if(typeof Ge!="number")return;{let Ke=z?.x,Ye=An!==null&&Ge===wt()&&typeof Ke=="number"&&Ke>=An.start&&Ke<=An.end,os=Cn!==null&&Ge===wt()&&typeof Ke=="number"&&Ke>=Cn.start&&Ke<=Cn.end;(Ye!==Ri||os!==Ti)&&(Ri=Ye,Ti=os,ke(),f===0?(jt(),n.hideCursor(!1)):n.hideCursor(!0))}if(Xt&&An!==null&&Ge===wt()){let Ke=z?.x;if(typeof Ke=="number"&&Ke>=An.start&&Ke<=An.end){at();return}}if(Xt&&Cn!==null&&Ge===wt()){let Ke=z?.x;if(typeof Ke=="number"&&Ke>=Cn.start&&Ke<=Cn.end){let Ye=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=BS(s.filters.hostFilter,i),Vt(),As(Ye),Ve();return}}if(Ge>=vn&&Ge<=Ae()){let Ke=null;if(Ge===vn){let Ye=z?.x;typeof Ye=="number"&&(Yn!==null&&Ye>=Yn.start&&Ye<=Yn.end?Ke="agent":Gn!==null&&Ye>=Gn.start&&Ye<=Gn.end&&(Ke="cwd"))}if(Ke!==Ut&&(Ut=Ke,Rs()),Xt&&Ge===vn){if(Ut==="agent"){ts();return}if(Ut==="cwd"){ze();return}}if((Xt||rs)&&f!==0){yt=!1;let Ye=f;f=0,Be(()=>{Ct(),qt(Ye,f)});return}ce&&!yt&&f!==0&&(yt=!0,Be(()=>{Rs(),Ct()}));return}Ut!==null&&(Ut=null,Rs()),yt&&(yt=!1,Be(()=>{Rs(),Ct()}));let ct=Bn()+1,Dn=ct+Je-1;if(Ge<ct||Ge>Dn)return;let cn=p+(Ge-ct);if(cn<0||cn>=a.length)return;let Ps=a[cn];if(!Ps)return;let Ur=cn+1;if(ce&&f===0)return;let Ql=f===0,is=f===Ur;if(rs&&f!==Ur){let Ke=f;f=Ur,Sn(),Be(()=>{Ct(),qt(Ke,f)});return}if(rs)return;if(f!==Ur){let Ke=f;f=Ur,Sn(),Be(()=>{Ct(),qt(Ke,f)})}if(!Xt||Ql||!is)return;let _i={kind:"attach",sessionId:Ps.sessionId};Ps.agentId!==void 0&&(_i.agentId=Ps.agentId),_i.installStatus=Nn(),T(_i)},Ft=()=>{n.grabInput({mouse:"motion"}),re({src:"grab",site:"picker.installGrab",on:!0});let F=n;F.stdin&&typeof F.onStdin=="function"&&(rn=F.onStdin,F.stdin.removeListener("data",F.onStdin),F.stdin.on("data",Xs),process.stdout.write(ll),process.stdout.write(pl)),n.on("key",mt),n.on("mouse",ft),n.on("resize",Rn)},dn=()=>{process.stdout.write(Os),process.stdout.write(za);let F=n;F.stdin&&rn&&(F.stdin.removeListener("data",Xs),F.stdin.on("data",rn),rn=null),Zn=!1,es="",n.off("key",mt),n.off("mouse",ft),n.off("resize",Rn),n.grabInput(!1),re({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Ft(),process.platform!=="win32"){let F=!1,z=()=>{F&&(F=!1,n.fullscreen(!0),t(),n.hideCursor(),Ft(),xt||Cs())};ea=()=>{F||xt||(F=!0,dn(),n.fullscreen(!1),process.stdout.write(`${Wa}${ul}
|
|
242
242
|
`),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(Br,3e3)})}function NM(n,e){let t="Create new session in ",s=Math.max(1,e-t.length);return t+Da(lt(n),s)}function zl(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 DM(n,e){return n?e.has(n):!0}function HM(n,e,t=Wu()){return e==="__all"?n:e==="__local"?n.filter(s=>DM(s.importedFromMachine,t)||!!s.upstreamSessionId):n.filter(s=>s.importedFromMachine===e&&!t.has(e)&&!s.upstreamSessionId)}function BS(n,e,t=Wu()){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 UM(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),s=[ut(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,lt(n.cwd)];for(let r of s)if(r.toLowerCase().includes(t))return!0;return!1}var bh,dd,OM,LS,LM,BM,NS=J(()=>{"use strict";Yc();pa();we();ps();et();Na();Fp();ac();Cl();Hp();ph();hh();gh();mh();yh();pi();Up();Qp();Ka();Zr();up();Vr();wh();bh=2,dd=4,OM=4,LS=4,LM=20,BM=[["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 jM from"wrap-ansi";async function DS(n,e,t,s){zn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=t.split(`
|
|
243
|
-
`).map(c=>c.trimEnd()).filter(c=>c.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",d=()=>{let c=tn(n),l=
|
|
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=Kn(n,{contentHeight:w,contentWidth:
|
|
245
|
-
`;
|
|
246
|
-
`)){if(r.startsWith("# branch.head ")){let
|
|
247
|
-
`)){let s=t.trim().split(/\s+/);if(s.length<4)continue;let r=Number(s[0]),i=Number(s[1]),o=Number(s[2]),a=g_(s[3]);!Number.isInteger(r)||!Number.isInteger(i)||!Number.isFinite(o)||a===null||e.set(r,{pid:r,ppid:i,rssBytes:o*1024,cpuSeconds:a})}return e}function g_(n){let e=n,t=0,s=e.indexOf("-");if(s!==-1){let o=e.slice(0,s);if(o.length===0||(t=Number(o),e=e.slice(s+1),!Number.isInteger(t)||t<0))return null}let r=e.split(":");if(r.length<2||r.length>3)return null;let i=0;for(let o of r){let a=Number(o);if(!Number.isFinite(a)||a<0)return null;i=i*60+a}return t*86400+i}function Ah(n,e){let t=new Map;for(let i of n.values()){let o=t.get(i.ppid);o===void 0?t.set(i.ppid,[i.pid]):o.push(i.pid)}let s=new Set;if(!n.has(e))return s;let r=[e];for(;r.length>0;){let i=r.pop();if(!s.has(i)){s.add(i);for(let o of t.get(i)??[])s.has(o)||r.push(o)}}return s}function dk(n,e,t){let s=Ah(n.rows,t);if(s.size===0)return null;let r=0,i=0,o=!1;for(let c of s){if(n.rssKnown!==void 0&&!n.rssKnown.has(c))return null;let l=n.rows.get(c);r+=l.rssBytes;let
|
|
243
|
+
`).map(c=>c.trimEnd()).filter(c=>c.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",d=()=>{let c=tn(n),l=Ls(n),u=Math.min(qM,Math.max(20,c-4)),f=Math.max(1,u-1),p=o.flatMap(A=>jM(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=Kn(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),v=b.contentW,k=0;n.moveTo(b.contentX,b.contentY+k),n.brightWhite.bold.noFormat(tt(` ${i}`,v)),k+=2;for(let A of y)n.moveTo(b.contentX,b.contentY+k),n.brightRed.noFormat(tt(` ${A}`,v)),k++;return m&&(n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(tt(" \u2026 (full details in ~/.hydra-acp/tui.log)",v)),k++),k++,n.moveTo(b.contentX,b.contentY+k),n.dim.noFormat(tt(` ${a}`,v)),b};return Ss({term:n,render:()=>{d()},onKey:(c,l,u,f)=>{if(c==="r"||c==="R"||c==="ENTER"||c==="KP_ENTER"){f("retry");return}if(c==="ESCAPE"){f(r?"back":"cancel");return}c==="CTRL_C"&&f("cancel")}})}var qM,HS=J(()=>{"use strict";pi();qM=100});import{spawn as WM}from"child_process";function zM(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 KM(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function JM(n,e){let t=KM(n.command);if(t.length===0)return null;let s=t.map(a=>st(zM(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 VM(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,d)=>{let c=a.split(/\r?\n/);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let l of c)i.push({text:l,style:d})};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 US(n,e,t){let s=JM(n,e);if(s===null){t.notify("hotkey: empty command");return}let r=VM(t.maxOutputBytes??GM),i=t.spawnFn??WM,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,d)=>{t.emitLines(r.onExit(a,d))})}var GM,jS=J(()=>{"use strict";et();GM=16*1024});import{spawn as YM,spawnSync as QM}from"child_process";import*as js from"fs";import*as Kl from"path";function qS(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${XM}1337;SetUserVar=${n}=${t}${ZM}`)}function WS(n){if(process.env.TMUX_PANE)try{let e=YM("tmux",n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function e_(){if(!process.stdin.isTTY)return null;let n=t=>{try{let s=js.readlinkSync(t);return s.startsWith("/dev/")&&s!=="/dev/tty"?Kl.basename(s):null}catch{return null}},e=n("/proc/self/fd/0")??n("/dev/fd/0");if(e)return e;try{let t=QM("tty",[],{encoding:"utf8",timeout:500});if(t.status!==0)return null;let s=t.stdout.trim();return!s.startsWith("/dev/")||s==="/dev/tty"?null:Kl.basename(s)}catch{return null}}function zS(){return kh===void 0&&(kh=e_()),kh}function t_(n){let e=zS();if(e)try{js.mkdirSync(L.ttySessionDir(),{recursive:!0});let t=`${process.pid}:${process.ppid}:${n}
|
|
245
|
+
`;js.writeFileSync(L.ttySessionFile(e),t,{mode:384})}catch{}}function n_(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 s_(){let n=zS();if(!n)return null;try{let e=js.readFileSync(L.ttySessionFile(n),"utf8");return n_(e)}catch{return null}}function r_(){let n=s_();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function Ih(n){qS("hydra_session",n),WS(["set-option","-pt",process.env.TMUX_PANE??"","@hydra_session",n]),t_(n)}function KS(){qS("hydra_session",""),WS(["set-option","-put",process.env.TMUX_PANE??"","@hydra_session"])}function JS(){return r_()}var XM,ZM,kh,VS=J(()=>{"use strict";we();XM="\x1B]",ZM="\x07"});function GS(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 YS(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function QS(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 XS=J(()=>{"use strict"});import{resolve as i_}from"path";function a_(n,e){let t=0;for(let s=0;s<e;s++){let r=n.indexOf(" ",t);if(r===-1)return"";t=r+1}return n.slice(t)}function d_(){return{branch:null,staged:0,unstaged:0,untracked:0,ahead:0,behind:0,files:[]}}function ZS(n,e){let t=d_(),s=(r,i)=>{e===null||r===""||t.files.push({path:i_(e,r),state:i})};for(let r of n.split(`
|
|
246
|
+
`)){if(r.startsWith("# branch.head ")){let u=r.slice(14).trim();t.branch=u==="(detached)"?null:u;continue}if(r.startsWith("# branch.ab ")){let u=/\+(\d+) -(\d+)/.exec(r);u!==null&&(t.ahead=Number(u[1]),t.behind=Number(u[2]));continue}if(r.startsWith("? ")){t.untracked++,s(r.slice(2),"new");continue}let i=r.slice(0,1),o=o_[i];if(o===void 0||r[1]!==" ")continue;let a=r.slice(2,4),d=a[0]!==void 0&&a[0]!==".",c=a[1]!==void 0&&a[1]!==".";d&&t.staged++,c&&t.unstaged++;let l=a_(r,o).split(" ")[0]??"";s(l,c?"dirty":"staged")}return t}var o_,ek=J(()=>{"use strict";o_={1:8,2:9,u:10}});import{resolve as c_}from"path";function l_(n,e){return e!==void 0||pg(n.rawKind)}function tk(n,e,t){if(n.status!=="completed"||!l_(n,e))return null;let s=e?.path??Jd(n.locations);if(s===void 0||s==="")return null;let r=e===void 0?void 0:sp(e);return{path:t===null?s:c_(t,s),added:r?.added,removed:r?.removed}}function nk(n){let e=new Map;for(let t of n){let s=e.get(t.path);if(s===void 0){e.set(t.path,{...t});continue}t.added!==void 0&&(s.added=(s.added??0)+t.added),t.removed!==void 0&&(s.removed=(s.removed??0)+t.removed),e.delete(t.path),e.set(t.path,s)}return[...e.values()]}var sk=J(()=>{"use strict";ha();oi()});function rk(n){if(n===null||typeof n!="object")return null;let t=n.rawInput;if(t===null||typeof t!="object")return null;let s=t.todos;if(!Array.isArray(s))return null;let r=[];for(let i of s){if(i===null||typeof i!="object")continue;let{content:o,status:a,priority:d}=i;if(typeof o!="string"||o.length===0)continue;let c={content:o,status:typeof a=="string"&&u_.has(a)?a:"pending"};typeof d=="string"&&d.length>0&&(c.priority=d),r.push(c)}return r}var u_,ik=J(()=>{"use strict";u_=new Set(["pending","in_progress","completed"])});import{readdirSync as f_,readFileSync as p_}from"fs";function xh(n){let e=n.lastIndexOf(")");if(e===-1)return null;let t=Number(n.slice(0,n.indexOf(" "))),s=n.slice(e+2).split(" "),r=Number(s[1]),i=Number(s[11]),o=Number(s[12]),a=Number(s[13]),d=Number(s[14]);if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isFinite(i)||!Number.isFinite(o))return null;let c=Number.isFinite(a)&&Number.isFinite(d)?(a+d)/ok:void 0;return{pid:t,ppid:r,rssBytes:0,cpuSeconds:(i+o)/ok,...c===void 0?{}:{childCpuSeconds:c}}}function h_(n){let e=/^VmRSS:\s+(\d+)\s+kB$/m.exec(n);if(e===null)return null;let t=Number(e[1]);return Number.isFinite(t)?t*1024:null}function ak(n,e,t){if(e===null||t<=0)return;let s=n.user-e.user+(n.system-e.system);return Math.max(0,s/1e3/t)}function m_(n){let e=new Map;for(let t of n.split(`
|
|
247
|
+
`)){let s=t.trim().split(/\s+/);if(s.length<4)continue;let r=Number(s[0]),i=Number(s[1]),o=Number(s[2]),a=g_(s[3]);!Number.isInteger(r)||!Number.isInteger(i)||!Number.isFinite(o)||a===null||e.set(r,{pid:r,ppid:i,rssBytes:o*1024,cpuSeconds:a})}return e}function g_(n){let e=n,t=0,s=e.indexOf("-");if(s!==-1){let o=e.slice(0,s);if(o.length===0||(t=Number(o),e=e.slice(s+1),!Number.isInteger(t)||t<0))return null}let r=e.split(":");if(r.length<2||r.length>3)return null;let i=0;for(let o of r){let a=Number(o);if(!Number.isFinite(a)||a<0)return null;i=i*60+a}return t*86400+i}function Ah(n,e){let t=new Map;for(let i of n.values()){let o=t.get(i.ppid);o===void 0?t.set(i.ppid,[i.pid]):o.push(i.pid)}let s=new Set;if(!n.has(e))return s;let r=[e];for(;r.length>0;){let i=r.pop();if(!s.has(i)){s.add(i);for(let o of t.get(i)??[])s.has(o)||r.push(o)}}return s}function dk(n,e,t){let s=Ah(n.rows,t);if(s.size===0)return null;let r=0,i=0,o=!1;for(let c of s){if(n.rssKnown!==void 0&&!n.rssKnown.has(c))return null;let l=n.rows.get(c);r+=l.rssBytes;let u=e?.rows.get(c);u!==void 0&&(o=!0,i+=Math.max(0,l.cpuSeconds-u.cpuSeconds))}o&&e!==null&&(i+=y_(n,e,s,t));let a={processes:s.size,rssBytes:r},d=e===null?0:n.at-e.at;return o&&d>0&&(a.cpuFraction=Math.max(0,i)/(d/1e3)),a}function y_(n,e,t,s){let r=0,i=!1;for(let o of t){let a=n.rows.get(o).childCpuSeconds,d=e.rows.get(o)?.childCpuSeconds;a===void 0||d===void 0||(i=!0,r+=Math.max(0,a-d))}if(!i)return 0;for(let o of Ah(e.rows,s)){if(t.has(o))continue;let a=e.rows.get(o);a!==void 0&&a.childCpuSeconds!==void 0&&(r-=a.cpuSeconds+a.childCpuSeconds)}return r}async function w_(n,e,t){let s=[],r;try{r=await e(`/proc/${n}/task`)}catch{return s}for(let i of r){if(!/^\d+$/.test(i))continue;let o;try{o=await t(`/proc/${n}/task/${i}/children`)}catch{continue}for(let a of o.split(/\s+/)){if(a.length===0)continue;let d=Number(a);Number.isInteger(d)&&d>0&&s.push(d)}}return s}async function b_(n,e,t){let s=new Map,r=new Set;for(let i of n){if(r.has(i))continue;let o;try{o=await t(`/proc/${i}/stat`)}catch{continue}try{await t(`/proc/${i}/task/${i}/children`)}catch{return null}let a=xh(o);if(a===null)continue;s.set(i,a),r.add(i);let d=[i];for(;d.length>0;){let c=d.pop();for(let l of await w_(c,e,t)){if(r.has(l))continue;r.add(l);let u;try{u=xh(await t(`/proc/${l}/stat`))}catch{continue}u!==null&&(s.set(l,u),d.push(l))}}}return s}async function v_(n,e){let t=new Map,s;try{s=await n("/proc")}catch{return t}return await Promise.all(s.map(async r=>{if(/^\d+$/.test(r))try{let i=xh(await e(`/proc/${r}/stat`));i!==null&&t.set(i.pid,i)}catch{}})),t}async function S_(n,e,t){for(let s of e){let r=n.get(s);if(r!==void 0)try{let i=h_(await t(`/proc/${s}/status`));i!==null&&(r.rssBytes=i)}catch{}}}async function ck(n,e={}){let t=e.platform??process.platform,s=Date.now();if(t==="linux"){let i=e.readDir??(l=>f_(l)),o=e.readFile??(l=>p_(l,"utf8")),a=await b_(n,i,o),d=a??await v_(i,o),c=new Set;if(a!==null)for(let l of d.keys())c.add(l);else for(let l of n)for(let u of Ah(d,l))c.add(u);return await S_(d,c,o),{at:s,rows:d,rssKnown:c}}let r=e.runPs??(async()=>{let{execFile:i}=await import("child_process"),{promisify:o}=await import("util"),{stdout:a}=await o(i)("ps",["-A","-o","pid=,ppid=,rss=,time="],{timeout:5e3,maxBuffer:8*1024*1024});return a});try{return{at:s,rows:m_(await r())}}catch{return{at:s,rows:new Map}}}var ok,lk=J(()=>{"use strict";ok=100});import{readFileSync as k_}from"fs";import{performance as I_}from"perf_hooks";import{writeHeapSnapshot as x_}from"v8";import{nanoid as uk}from"nanoid";import A_ from"terminal-kit";import Ch from"fs/promises";import wi from"path";import{execFile as fk}from"child_process";function C_(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function R_(n){let e=Jl(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function T_(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 Jl(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 E_(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function P_(n,e,t,s,r=60){let i=n.map((o,a)=>{let d=Jl(o.representative),c=e[a]??0,l=t[a]?Th:d[c]??d[0]??"";return{label:E_(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 M_(n,e,t){return n===Th?{type:"dismiss",method:Lv,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:Ov,params:{sessionId:t,questionId:e.id,answer:n}}}function __(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 d=s[o]?Th:Jl(a.representative)[e[o]??0]??"";if(d)for(let c of a.ids){let l={...a.representative,id:c},u=M_(d,l,r);u!==null&&i.push(u)}}return i}function $_(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 c=parseInt(n.ch,10)-1;if(c<t.length)return{type:"row",selectedRow:c}}return{type:"noop"}}if(n.type!=="key")return{type:"noop"};let d=c=>{let l=t[o];if(!l)return{type:"noop"};let u=Jl(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+c+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 d(1);case"left":return d(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:__(t,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function pk(n){if(!Array.isArray(n))return;let e=gs({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function Rh(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 O_(n,e=process.env){return n!==void 0?n:e.VISUAL??e.EDITOR}function B_(n,e){e.has(n)?e.delete(n):e.add(n)}function N_(){if(hk)return;hk=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{re({src:"uncaughtException",stack:n(e)}),kr(),process.stderr.write(`
|
|
248
248
|
uncaught: ${n(e)}
|
|
249
249
|
`),process.exit(1)}),process.on("unhandledRejection",e=>{re({src:"unhandledRejection",stack:n(e)}),kr(),process.stderr.write(`
|
|
250
250
|
unhandled rejection: ${n(e)}
|
|
251
251
|
`),process.exit(1)}),process.on("exit",e=>{e!==0&&re({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=x_(e),s=process.memoryUsage();re({src:"heap-snapshot",path:t,rss:s.rss,heapUsed:s.heapUsed,heapTotal:s.heapTotal,external:s.external}),process.stderr.write(`
|
|
252
252
|
[heap] ${t} rss=${s.rss} heapUsed=${s.heapUsed}
|
|
253
|
-
`)}catch(e){re({src:"heap-snapshot-failed",err:e instanceof Error?e.message:String(e)})}})}async function yk(n){N_(),I_.setResourceTimingBufferSize(0);let e=await xe(),t=n.target??await
|
|
254
|
-
`))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let
|
|
255
|
-
`),process.stdout.isTTY){let p=await ti(e);if(p?.version!==void 0){let h=p.version!==be,m=
|
|
253
|
+
`)}catch(e){re({src:"heap-snapshot-failed",err:e instanceof Error?e.message:String(e)})}})}async function yk(n){N_(),I_.setResourceTimingBufferSize(0);let e=await xe(),t=n.target??await Wt(e);if(Rm(e.tui.logMaxBytes),t.isLocal&&!n.target&&await hr(e,t),n.agentId)try{let p=await ri(t),h=ja(n.agentId,p.map(m=>m.id));h!==void 0&&h!==n.agentId&&(n.agentId=h)}catch{}let s=A_.terminal;CS(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:tm(e),defaultEnterAction:e.tui.defaultEnterAction,sidebarVisible:e.tui.sidebar.enabled,...n.agentId?{lastChosenAgent:n.agentId}:{}},o=vh(),a=!1,d=()=>{a||(s.fullscreen(!0),a=!0)},c=()=>{a&&(kr(),s.fullscreen(!1),a=!1,process.stdout.write(`
|
|
254
|
+
`))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=n;try{for(;u!==null;)u=await U_(s,e,t,u,r,i,o)}finally{KS(),c(),process.off("exit",l)}let f=await Ga();if(f&&process.stderr.write(`\u2728 ${Ya(f)}
|
|
255
|
+
`),process.stdout.isTTY){let p=await ti(e);if(p?.version!==void 0){let h=p.version!==be,m=lr(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let w=h?`daemon ${p.version} \u2260 cli ${be}`:"config changed since daemon started",b=v=>`\x1B[33m${v}\x1B[0m`;process.stderr.write(b(`! ${w} \u2014 run \`${cs()} daemon restart\` to apply.`)+`
|
|
256
256
|
`)}}}if(r.sessionId&&process.stdout.isTTY){let p=ut(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${cs()} --session ${p}${h}
|
|
257
|
-
`)}}function D_(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,d=e.length,c=a>0,l;if(!c||n.expanded)l=e;else{let _=Math.max(0,d-a),F=e.slice(_),B=[];for(let N=0;N<_;N++){let q=e[N];if(q===void 0)continue;let Q=t.get(q);Q&&!ip(Q.status)&&B.push(q)}l=[...B,...F]}let f=d-l.length,u=r===null,p=r??Date.now(),h=p-s,m=!u&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",w=y?`amended \xB7 ${vs(h)}`:`stopped (${m}) \xB7 ${vs(h)}`,b;if(d===0)m!==null?b=w:b=u?`thinking \xB7 ${vs(h)}`:`thought \xB7 ${vs(h)}`;else{let _=d===1?"tool":"tools",F=m!==null?w:u?vs(h):`took ${vs(h)}`,B=[`${d} ${_}`,F];u&&c&&f>0&&B.push(`${f} hidden`),b=B.join(" \xB7 ")}let v=d===0&&u,k=y?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:v?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:v?"tool-status-running":m!==null?k:"dim"}],H=[null];for(let _ of l){let F=t.get(_);if(F){let B=Ua(F,p);for(let N of B)N.hoverSubKey=_;if(P.push(...B),H.push(...B.map(()=>_)),o?.has(_)){let N=ub(F);for(let q of N)q.hoverSubKey=_;P.push(...N),H.push(...N.map(()=>_))}}}return{lines:P,rowOwners:H}}async function H_(n,e,t,s,r,i,o){let a=await U_(n,e,t,s,o,i);if(!a)return n.grabInput(!1),re({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let d=a.resolved?.status==="warm"&&t.isLocal,c=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 f=a.installStatus??l??Wl(d?"":c,OS(n));d||f.write(c);let u=t.isLocal?async()=>(await qt(await xe())).wsUrl:t.wsUrl,p=["acp.v1",`hydra-acp-token.${t.token}`],h=null,m=null,y=new Fo({url:u,subprotocols:p,onConnect:async g=>{g||h&&await h()},onDisconnect:g=>{m&&m(g)},log:g=>re({src:"resilient-ws",line:g})}),w=new Zt(y);await y.start(),w.onNotification(qd,g=>{let S=cg.safeParse(g);S.success&&f.applyProgress(S.data)});let b=[],v=null,k=!1,A=!1,E=(g,S)=>{g&&(v?v(g,S):b.push({event:g,rawUpdate:S}))},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,q=0,Q=!1,X=!1,G,pe=null,nt=null,js=!1,We=!1,kt=null,he=null,ee=null,Ee=()=>setInterval(()=>{if(pe===null||Pe===null)return;let g=ee===null?0:Date.now()-ee;Pe.setBanner({elapsedMs:Date.now()-pe,stalled:g>=F_}),Ye()},1e3),Je=!1,Pt=g=>{let S=q;q=Math.max(0,q+g);let x=typeof Pe<"u"&&Pe!==null;S===0&&q>0?(X=!1,pe=Date.now(),ee=Date.now(),Pe?.setSidebarSnapshot({busySince:pe}),Mt?.setTurnRunning(!0),x&&Pe.setBanner({status:"busy",elapsedMs:0,stalled:!1}),kt===null&&x&&(kt=Ee())):S>0&&q===0?(X=!1,pe=null,js?nt=Date.now():We=!0,Pe?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:nt}),ee=null,Mt?.setTurnRunning(!1),kt!==null&&(clearInterval(kt),kt=null),x&&Pe.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):q>0&&X&&(X=!1,x&&Pe.setBanner({status:"busy",stalled:!1}))},Pe=null,Mt=null,_t,bn=null,xr=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"]),bi=g=>{let{update:S}=g??{},x=gs(S,{cwd:ot});j_(S,x),ee=Date.now();let R=S?.sessionUpdate;if(typeof R=="string"&&!xr.has(R)){let C=S??{};typeof C.messageId=="string"&&(_t=C.messageId)}if(R==="prompt_received"?Pt(1):x?.kind==="turn-complete"&&(Pt(-1),B=!0),R==="permission_resolved"){pd(S);return}if(R==="hydra_compaction"){Kt(S);return}if(R==="clarifier_question_asked"){let C=S,L=typeof C.question?.question=="string"?C.question.question:"",K=L.length>50?L.slice(0,49)+"\u2026":L;I.notify(K?`new question: ${K} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(E(x,S),Jt(S))};w.onNotification("session/update",g=>{if(!k){if(bn!==null){bn.push(g);return}bi(g)}}),w.onNotification("hydra-acp/session/closed",()=>{if(k)return;q>0&&Pt(-q),typeof Pe<"u"&&Pe!==null&&Pe.setBanner({status:"cold",elapsedMs:void 0})});let On=new Map,Ho=200,vn=0,qs=!1,Uo=4e3;w.onNotification("hydra-acp/prompt_queue/added",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string")return;if(typeof S._meta?.["hydra-acp"]?.amending=="string"){let R=S.messageId,C=S.prompt,L=setTimeout(()=>{k||(On.delete(R),$e.set(R,De(R,C)),Pe&&Mt&&Rn())},Ho);On.set(R,L)}else $e.set(S.messageId,De(S.messageId,S.prompt)),Pe&&Mt&&Rn();if(Gn!==void 0&&S.originator?.clientId===Gn){let R=Ze.shift();R&&(R.messageId=S.messageId,ze.set(S.messageId,R))}}),w.onNotification("hydra-acp/prompt_queue/updated",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string"||!$e.has(S.messageId))return;$e.set(S.messageId,De(S.messageId,S.prompt));let x=ze.get(S.messageId);if(x){let R=Array.isArray(S.prompt)?S.prompt:[],C="",L=[];for(let K of R){if(!K||typeof K!="object")continue;let D=K;D.type==="text"&&typeof D.text=="string"?C+=D.text:D.type==="image"&&typeof D.data=="string"&&typeof D.mimeType=="string"&&L.push({data:D.data,mimeType:D.mimeType,sizeBytes:Math.floor(D.data.length*3/4)})}x.text=C,x.attachments=L}Pe&&Mt&&Rn()}),w.onNotification("hydra-acp/prompt_queue/removed",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string")return;S.reason==="started"&&(G=S.messageId);let x=On.get(S.messageId);x!==void 0&&(clearTimeout(x),On.delete(S.messageId)),$e.delete(S.messageId)&&Pe&&Mt&&Rn();let C=ze.get(S.messageId);C&&(ze.delete(S.messageId),S.reason==="started"&&(C.flushed=!0,E({kind:"user-text",text:C.displayText,attachments:C.attachments}),ht=C))}),w.onNotification("hydra-acp/cancel_failed",g=>{if(k)return;let S=g??{};if(!(typeof Pe<"u"&&Pe!==null))return;vn=Date.now(),qs=!0;let R=typeof S.code=="number"?` (${S.code})`:"",C=typeof S.message=="string"&&S.message.length>0?`: ${S.message}`:"";Pe.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 S=g??{};if(typeof S.cancelledMessageId!="string")return;let x=S.cancelledMessageId;ts.add(x),ht!==null&&ht.messageId!==void 0&&ht.messageId===x&&(E({kind:"turn-complete",stopReason:"cancelled",amended:!0}),ht=null,ts.delete(x))});let Kt=g=>{let S=g??{},x=typeof S.phase=="string"?S.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 S.error=="string"?S.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;I.notify(`compaction failed: ${C}`,5e3)}},Ar=()=>{he===null&&(he=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let S=await g.json();S.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),he!==null&&(clearInterval(he),he=null)):S.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),he!==null&&(clearInterval(he),he=null))}catch{}},5e3))},fd=()=>{he!==null&&(clearInterval(he),he=null)},pd=g=>{let S=g??{},x=typeof S.toolCallId=="string"?S.toolCallId:void 0,R;S.outcome&&typeof S.outcome=="object"?R=S.outcome:typeof S.chosenOptionId=="string"&&(R={kind:"selected",optionId:S.chosenOptionId}),hd(x,R?{outcome:R}:void 0)},Ne=null,hd=(g,S)=>{if(!Ne||Ne.toolCallId&&g&&Ne.toolCallId!==g)return;let x=Ne.resolve;Ne=null,I.setPermissionPrompt(null),x(S??{outcome:{outcome:"cancelled"}})},Jt=g=>{if(!Ne?.toolCallId)return;let S=g??{};S.sessionUpdate!=="tool_call"&&S.sessionUpdate!=="tool_call_update"||S.toolCallId===Ne.toolCallId&&(!S.status||S.status==="pending"||hd(S.toolCallId,void 0))},Cs=()=>{if(!Ne){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:Ne.title,detail:Ne.detail,options:Ne.options.map(g=>({label:g.name})),selectedIndex:Ne.selectedIndex})},Sn=g=>{if(!Ne)return;let{options:S,resolve:x}=Ne;if(Ne=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 hi(g);let S=g??{},R=(Array.isArray(S.options)?S.options:[]).map(Z=>({optionId:Z.optionId,name:Te(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=S.toolCall?.title??S.toolCall?.name??"tool",L=Te(C),K=Te(uv(lv(g))),D=S.toolCall?.toolCallId;return R.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${L} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{Ne={title:L,detail:K,options:R,selectedIndex:0,resolve:Z,toolCallId:D},Cs()})}),w.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Ln,yt,$t=!0,It=!1;try{let g=await w.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}});yt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&($t=!1),It=hn(g?._meta??void 0).prompt?.amending===!0}catch{}let me=a.sessionId,Ht=a.agentId,ot=a.cwd,vi,Gn,Yn,Ut,Si,ki,Ii,Ws,Cr,kn,jo=!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 S={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Bt]:g}}:{}},x;try{x=await tv({request:()=>w.request("session/new",S),showBanner:(L,K,D)=>nv(n,L,K,D,{authenticate:Z=>w.request("authenticate",{methodId:Z})}),resolveOnboarding:async L=>{if(L)try{return(await ri(t)).find(Z=>Z.id===L)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(L){n.grabInput(!1),re({src:"grab",site:"runSession.session-new-failed",on:!1}),y.close().catch(()=>{});let K=L instanceof Error?L.message:String(L);re({src:"session-new-failed",agentId:s.agentId??null,message:K});let D=await DS(n,s.agentId,K,{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),re({src:"grab",site:"runSession.auth-cancel",on:!1}),y.close().catch(()=>{}),null;if(x.kind==="back"){n.grabInput(!1),re({src:"grab",site:"runSession.auth-back",on:!1}),y.close().catch(()=>{});let L={...s};return delete L.sessionId,delete L.forceNew,delete L.resume,delete L.agentId,L}let R=x.result;f.write(c),me=R.sessionId,Ih(me),r.sessionId=me,r.readonly=!1;let C=hn(R._meta??void 0);C.clientId&&(Gn=C.clientId),Ln=C.upstreamSessionId,C.agentId&&(Ht=C.agentId),C.cwd&&(ot=C.cwd),C.title&&(vi=C.title),Yn=C.currentModel,Ut=C.currentMode,Cr=C.currentUsage,kn=C.turnStartedAt,C.availableCommands&&(Si=xc(C.availableCommands)),C.availableModes&&(ki=C.availableModes),Ii=pk(R.configOptions),Ws=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 S=await w.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:be},...Object.keys(g).length>0?{_meta:{[Bt]:g}}:{}});me=S.sessionId,Ih(me),S.clientId&&(Gn=S.clientId),r.sessionId=me,r.readonly=s.readonly===!0;let x=hn(S._meta??void 0);jo=x.resurrected===!0,Ln=x.upstreamSessionId,x.agentId&&(Ht=x.agentId),x.cwd&&(ot=x.cwd),x.title&&(vi=x.title),Yn=x.currentModel,Ut=x.currentMode,Cr=x.currentUsage,kn=x.turnStartedAt,x.availableCommands&&(Si=xc(x.availableCommands)),x.availableModes&&(ki=x.availableModes),Ii=pk(S.configOptions),Ws=x.queue}let zs=O.tuiHistoryFile(me),Rr=O.globalTuiHistoryFile(),nn=await ka(zs).catch(()=>[]),ke=await ka(Rr).catch(()=>[]);ke.length>e.tui.promptHistoryMaxEntries&&(ke=ke.slice(ke.length-e.tui.promptHistoryMaxEntries));let In=[...nn],Ae=new Ns({history:oc(ke,In)});Mt=Ae;let Bn=!1,Tr=(g,S)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let R=(S??g).replace(/\n+$/,""),C=Ia(nn,x),L=C!==nn;nn=C,In=Ia(In,R);let K=Ia(ke,x,e.tui.promptHistoryMaxEntries),D=K!==ke;ke=K,Ae.setHistory(oc(ke,In)),L&&Xr(zs,nn).catch(()=>{}),D&&uy(Rr,x).catch(()=>{})};q>0&&Ae.setTurnRunning(!0);let wt=null,jt=null;IS(xS(e.tui.ambiguousWidth,process.env)),pb(e.tui.diffContextLines);let Ks=!1,I,qo=()=>{Ks&&(Ks=!1,I.start())},md=()=>{Ks||(Ks=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",qo);let Js=null,xi=null;I=new Bl({term:n,dispatcher:Ae,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:O_(e.tui.openFileCommand),progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?md:void 0,onLayoutChange:()=>{Uh()},onBlockClick:(g,S)=>{Kk(g,S)},onHydraLinkClick:g=>(U(g),!0),onBlockVisible:g=>{Ok(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let S=Hr.get(g);if(S!==void 0&&S.length>0)return new Set(S);let x=I.contiguousRun(g,new Set(tr.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Js=I.bannerHitAt(g.x,g.y),xi=Js?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=xi,R=Js;if(xi=null,Js=null,R!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Br(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Rh(C))return;Y(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let S={type:"attachment-request",source:"primary"};s.readonly===!0&&Rh(S)||Y(S)},onKey:g=>{for(let S of g){if(Q&&Qo(S)){S.type==="key"&&re({src:"key-swallowed",site:"compactionPrompt",name:S.name});continue}if(Ne&&Mr(S)){S.type==="key"&&re({src:"key-swallowed",site:"permission",name:S.name});continue}if(Ts(S)){S.type==="key"&&re({src:"key-swallowed",site:"help",name:S.name});continue}if(ea(S)){S.type==="key"&&re({src:"key-swallowed",site:"questions",name:S.name});continue}if(rn(S)){S.type==="key"&&re({src:"key-swallowed",site:"options",name:S.name});continue}if(yd(S)){S.type==="key"&&re({src:"key-swallowed",site:"scrollbackSearch",name:S.name});continue}if(gd(S)){S.type==="key"&&re({src:"key-swallowed",site:"completion",name:S.name});continue}if(Ko(S)){S.type==="key"&&re({src:"key-swallowed",site:"btwClose",name:S.name});continue}if(S.type==="key"&&S.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(S.type==="attachment-paths"){ie(S.paths);continue}if(S.type==="key"&&_r(S.name)){re({src:"key-swallowed",site:"userHotkey",name:S.name});continue}let x=Ae.feed(S);for(let R of x)s.readonly===!0&&Rh(R)||Y(R)}zo(),I.setBannerSearchIndicator(Ae.state().historySearchQuery),I.setAttachments(Ae.state().attachments),I.refreshPrompt()}}),Pe=I,I.setStickyBottomKey("plan");let Er=[{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]"}],Ve=Si??[],Rs=ki??[],Wo=Ii??[],sn=()=>Wo.find(g=>g.id==="agent"),Yl=()=>{let g=new Set,S=[];for(let x of[...Er,...Ve])g.has(x.name)||(g.add(x.name),S.push(x));return S},bt=()=>{let g=Ae.state().buffer,S=g[0]??"";if(!S.startsWith("/"))return[];if(g.length>1)return[];let x=S.indexOf(" "),R=x===-1?S:S.slice(0,x);if(R.lastIndexOf("/")>0)return[];let C=Yl().filter(L=>L.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},Vt=[],zo=()=>{let g=bt();if(g.length>0){Vt=[],I.setCompletions(g);return}I.setCompletions(Vt)},gd=g=>{if(g.type!=="key"||g.name!=="tab")return Vt.length>0&&(Vt=[]),!1;let S=bt();if(I.isOverlayOpen()&&S.length===0)return I.toggleFocusedPane(),!0;if(S.length>0){Vt=[];let x=Ae.state().buffer[0]??"",R=PS({matches:S.map(C=>C.name),firstLine:x});return R===null||Ae.replaceFirstLine(R),!0}return Pr()},Pr=()=>{let g=Ae.state(),S=g.buffer[g.row]??"",x=jl(S,g.col);if(x===null)return!1;let R=ql(x.token,ot);return R===null?!1:(R.replacement!==x.token&&Ae.replaceRangeOnCurrentLine(x.start,g.col,R.replacement),Vt=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},Ko=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(_&&(_.cancel(),_=null,F=null),I.closeBtwOverlay(),!0),yd=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 S=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(S),!0}if(g.type==="paste"){let S=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(S),!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 S=I.scrollbackSearchTerm();return S.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(S.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Mr=g=>{if(!Ne)return!1;let S=Ne.options;if(g.type==="key")switch(g.name){case"up":return Ne.selectedIndex=Math.max(0,Ne.selectedIndex-1),Cs(),!0;case"down":return Ne.selectedIndex=Math.min(S.length-1,Ne.selectedIndex+1),Cs(),!0;case"enter":{let x=S[Ne.selectedIndex];return x&&Sn(x.optionId),!0}case"escape":case"ctrl-c":return Sn(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,R=S[x];return R&&Sn(R.optionId),!0}return!0},_r=g=>{let S=e.tui.hotkeys[g];return S?(US(S,{sessionId:me,cwd:ot,agentId:Ht||yt||"",baseUrl:t.baseUrl,tokenFile:O.authToken()},{notify:x=>I.notify(x),cwd:ot,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},Vs=()=>Ht||yt||"?",Jo=Vs(),Gt={...Cr??{}};f.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSidebarGadgets(e.tui.sidebar.gadgets),I.setSidebarWidth(e.tui.sidebar.width??null),I.setSidebarBorder(e.tui.sidebar.border),I.setSidebarSnapshot({usage:{...Gt},model:Yn??null,mode:Ut??null,sessionId:me===null?null:ut(me),agent:Jo}),I.setSessionbar({agent:Jo,cwd:ot,sessionId:me,title:vi,model:Yn,usage:{...Gt}}),Ut&&I.setBanner({currentMode:Ut}),Ga().then(g=>{g&&I.notify(`\u2728 ${Ya(g)}`,3e4)}).catch(()=>{});let xt=null,Vo=new Promise(g=>{xt=g}),Ai=()=>{w.notify("session/cancel",{sessionId:me}).catch(()=>{})},Gs=()=>{Pe!==null&&q===1&&(X=!0,Pe.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Qn=()=>{if(wt){wt.cancel(),Gs();return}if(q>0){Ai(),Gs();return}Xn()},Xn=()=>{Qs(0)},Ci=()=>{let g="enqueue prompt (sends now, or queues during a turn)",S="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",S],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",S]],...L_]},wd=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:Ci(),hint:"any key dismisses \xB7 /help lists commands"})},Go=()=>{Q=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Yo=()=>{Q=!1,I.setCompactionPrompt(null)},bd=g=>{let S=I.compactionPromptSpec();if(!S)return;let x=S.options.length;if(x===0)return;let R=((S.selectedIndex+g)%x+x)%x;R!==S.selectedIndex&&I.setCompactionPrompt({...S,selectedIndex:R})},Qo=g=>{if(!Q)return!1;if(g.type==="key"){if(g.name==="escape")return Yo(),!0;if(g.name==="up")return bd(-1),!0;if(g.name==="down")return bd(1),!0;if(g.name==="enter"){let S=I.compactionPromptSpec();return S?.options[S.selectedIndex]?.key==="y"?Go():Yo(),!0}}if(g.type==="char"){let S=g.ch.toLowerCase();if(S==="y"||S==="1")return Go(),!0;if(S==="n"||S==="2")return Yo(),!0}return!0},Ts=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Es=["tools","plan","thoughts","diffs","mouse","enter","sidebar"],xn=0,Yt=null,Ys=[],$r=[],At=[],Fr=0,Zn=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;case"sidebar":return I.isSidebarVisible()?"shown":"hidden"}},es=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";case"sidebar":return"Sidebar"}},Xo=()=>({title:"Session options",options:Es.map(g=>({label:es(g),value:Zn(g)})),selectedIndex:xn}),Zo=()=>{I.isOptionsPromptActive()&&Yt===null&&I.setOptionsPrompt(Xo())},Or=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}xn=0,I.setOptionsPrompt(Xo())},Ps=()=>{if(Yt===null)return;let g=P_(Yt,Ys,At,Fr);I.setOptionsPrompt(g)},An=()=>{Yt=null,Ys=[],$r=[],At=[],Fr=0,I.setOptionsPrompt(null)},Ri=async()=>{if(Yt!==null){An();return}try{let S=await w.request(Fv,{sessionId:me}),x=C_(S.questions??[]);if(x.length===0){I.notify("no open questions");return}let R=T_(x);Yt=R,Fr=0,Ys=R.map(C=>R_(C.representative)),$r=R.map(()=>!1),At=R.map(()=>!1),Ps()}catch(g){I.notify("clarifier unavailable"),re({src:"questions",step:"list_failed",error:g.message})}},Cn=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Dr.clear(),Pi.clear(),ta();break;case"plan":i.planExpanded=!i.planExpanded,z=null,je();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",an.clear(),Hh();break;case"mouse":{let S=!I.isMouseEnabled();I.setMouseEnabled(S),i.mouseEnabled=S;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":cu(!I.isSidebarVisible());break}Zo()},Ti=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${es(g)} is session-only \u2014 not saved`);return;case"thoughts":await ia("showThoughts",i.showThoughts);break;case"diffs":await ia("showFileUpdates",i.showFileUpdates);break;case"mouse":await ia("mouse",i.mouseEnabled);break;case"enter":await ia("defaultEnterAction",i.defaultEnterAction);break;case"sidebar":await rm(I.isSidebarVisible());break}I.notify(`saved default: ${es(g)} ${Zn(g)}`)}catch(S){I.notify(`save failed: ${S instanceof Error?S.message:String(S)}`)}})()},rn=g=>{if(Yt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return xn=Math.max(0,xn-1),Zo(),!0;case"down":return xn=Math.min(Es.length-1,xn+1),Zo(),!0;case"enter":{let S=Es[xn];return S&&Cn(S),!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 S=parseInt(g.ch,10)-1,x=Es[S];return x&&(xn=S,Cn(x)),!0}if(g.ch==="s"||g.ch==="S"){let S=Es[xn];return S&&Ti(S),!0}}return!0},ea=g=>{if(Yt===null)return!1;let S=$_(g,!0,Yt,Ys,$r,At,Fr,me);switch(S.type){case"noop":return!0;case"row":return Fr=S.selectedRow,Ps(),!0;case"cycle":return Ys[S.selectedRow]=S.newValueIndex,$r[S.selectedRow]=!0,At[S.selectedRow]=!1,Ps(),!0;case"dismiss-toggle":{let x=S.selectedRow;return At[x]?(At[x]=!1,$r[x]=!1):(At[x]=!0,$r[x]=!0),Ps(),!0}case"discard":return An(),!0;case"save":{let x=S.dispatches;return An(),x.length===0||(async()=>{let R=0,C=0,L=0;for(let D of x)try{await w.request(D.method,D.params),D.type==="dismiss"?C++:R++}catch(Z){L++,re({src:"questions",step:"dispatch_failed",method:D.method,error:Z.message})}let K=[];R>0&&K.push(`${R} answered`),C>0&&K.push(`${C} dismissed`),L>0&&K.push(`${L} failed`),K.length>0&&I.notify(`clarifier: ${K.join(", ")}`)})(),!0}}return!1},Lr=()=>{if(!k){k=!0,_?(_.cancel(),_=null,F=null):F!==null&&(bs(t,F).catch(()=>{}),F=null),process.off("SIGINT",Qn),process.platform!=="win32"&&process.off("SIGCONT",qo),kt!==null&&(clearInterval(kt),kt=null),he!==null&&(clearInterval(he),he=null);for(let g of On.values())clearTimeout(g);On.clear(),Jh(),Kh(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Xr(zs,nn).catch(()=>{}),y.close().catch(()=>{})}},Qs=(g=0)=>{Lr(),xt&&(xt(null),xt=null),g!==0&&process.exit(g)},T=async()=>{if(re({src:"switch-session",step:"entered",finishSessionNull:xt===null}),!xt)return;_?(_.cancel(),_=null,F=null):F!==null&&(bs(t,F).catch(()=>{}),F=null),fd(),I.setSynthesisIndicator(null);let g=Ae.state().buffer.join(`
|
|
258
|
-
`);g.replace(/\s+$/,"").length>0&&Tr(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Xr(
|
|
259
|
-
`))return!1;let x=S.indexOf(" ");switch(x===-1?S:S.slice(0,x)){case"/quit":case"/exit":return Xn(),!0;case"/clear":return at.clear(),
|
|
260
|
-
`);if(x.length===0)return;let{text:R,truncated:C}=lb(x);g.resultText=R,g.resultTruncated=C},kd=new Set,$k=(g,S)=>{!S.some(R=>"hash"in R)||kd.has(g)||(kd.add(g),(async()=>{let R=await Promise.all(S.map(async
|
|
257
|
+
`)}}function H_(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,d=e.length,c=a>0,l;if(!c||n.expanded)l=e;else{let P=Math.max(0,d-a),$=e.slice(P),B=[];for(let N=0;N<P;N++){let U=e[N];if(U===void 0)continue;let G=t.get(U);G&&!ip(G.status)&&B.push(U)}l=[...B,...$]}let u=d-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 ${vs(h)}`:`stopped (${m}) \xB7 ${vs(h)}`,b;if(d===0)m!==null?b=w:b=f?`thinking \xB7 ${vs(h)}`:`thought \xB7 ${vs(h)}`;else{let P=d===1?"tool":"tools",$=m!==null?w:f?vs(h):`took ${vs(h)}`,B=[`${d} ${P}`,$];f&&c&&u>0&&B.push(`${u} hidden`),b=B.join(" \xB7 ")}let v=d===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",_=[{prefix:"\u2699 ",prefixStyle:v?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:v?"tool-status-running":m!==null?k:"dim"}],H=[null];for(let P of l){let $=t.get(P);if($){let B=Ua($,p),N=o?.has(P)??!1;for(let U of B)U.hoverSubKey=P,N||(U.maxWrapRows=D_);if(_.push(...B),H.push(...B.map(()=>P)),N){let U=ub($);for(let G of U)G.hoverSubKey=P;_.push(...U),H.push(...U.map(()=>P))}}}return{lines:_,rowOwners:H}}async function U_(n,e,t,s,r,i,o){let a=await j_(n,e,t,s,o,i);if(!a)return n.grabInput(!1),re({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let d=a.resolved?.status==="warm"&&t.isLocal,c=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??Wl(d?"":c,OS(n));d||u.write(c);let f=t.isLocal?async()=>(await Wt(await xe())).wsUrl:t.wsUrl,p=["acp.v1",`hydra-acp-token.${t.token}`],h=null,m=null,y=new Fo({url:f,subprotocols:p,onConnect:async g=>{g||h&&await h()},onDisconnect:g=>{m&&m(g)},log:g=>re({src:"resilient-ws",line:g})}),w=new Zt(y);await y.start(),w.onNotification(qd,g=>{let S=cg.safeParse(g);S.success&&u.applyProgress(S.data)});let b=[],v=null,k=!1,A=!1,E=(g,S)=>{g&&(v?v(g,S):b.push({event:g,rawUpdate:S}))},_,H=g=>{g!==_&&(_=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},P=null,$=null,B=!1,N=0,U=0,G=!1,X=!1,Y,pe=null,nt=null,qs=!1,We=!1,It=null,he=null,ee=null,Ee=()=>setInterval(()=>{if(pe===null||Pe===null)return;let g=ee===null?0:Date.now()-ee;Pe.setBanner({elapsedMs:Date.now()-pe,stalled:g>=F_}),Ye()},1e3),Je=!1,Pt=g=>{let S=U;U=Math.max(0,U+g);let x=typeof Pe<"u"&&Pe!==null;S===0&&U>0?(X=!1,pe=Date.now(),ee=Date.now(),Pe?.setSidebarSnapshot({busySince:pe}),Mt?.setTurnRunning(!0),x&&Pe.setBanner({status:"busy",elapsedMs:0,stalled:!1}),It===null&&x&&(It=Ee())):S>0&&U===0?(X=!1,pe=null,qs?nt=Date.now():We=!0,Pe?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:nt}),ee=null,Mt?.setTurnRunning(!1),It!==null&&(clearInterval(It),It=null),x&&Pe.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):U>0&&X&&(X=!1,x&&Pe.setBanner({status:"busy",stalled:!1}))},Pe=null,Mt=null,_t,bn=null,xr=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"]),bi=g=>{let{update:S}=g??{},x=gs(S,{cwd:ot});q_(S,x),ee=Date.now();let R=S?.sessionUpdate;if(typeof R=="string"&&!xr.has(R)){let C=S??{};typeof C.messageId=="string"&&(_t=C.messageId)}if(R==="prompt_received"?Pt(1):x?.kind==="turn-complete"&&(Pt(-1),B=!0),R==="permission_resolved"){pd(S);return}if(R==="hydra_compaction"){Jt(S);return}if(R==="clarifier_question_asked"){let C=S,O=typeof C.question?.question=="string"?C.question.question:"",K=O.length>50?O.slice(0,49)+"\u2026":O;I.notify(K?`new question: ${K} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}R==="clarifier_question_answered"||R==="clarifier_question_dismissed"||(E(x,S),Vt(S))};w.onNotification("session/update",g=>{if(!k){if(bn!==null){bn.push(g);return}bi(g)}}),w.onNotification("hydra-acp/session/closed",()=>{if(k)return;U>0&&Pt(-U),typeof Pe<"u"&&Pe!==null&&Pe.setBanner({status:"cold",elapsedMs:void 0})});let On=new Map,Ho=200,vn=0,Ws=!1,Uo=4e3;w.onNotification("hydra-acp/prompt_queue/added",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string")return;if(typeof S._meta?.["hydra-acp"]?.amending=="string"){let R=S.messageId,C=S.prompt,O=setTimeout(()=>{k||(On.delete(R),$e.set(R,De(R,C)),Pe&&Mt&&Rn())},Ho);On.set(R,O)}else $e.set(S.messageId,De(S.messageId,S.prompt)),Pe&&Mt&&Rn();if(Gn!==void 0&&S.originator?.clientId===Gn){let R=Ze.shift();R&&(R.messageId=S.messageId,ze.set(S.messageId,R))}}),w.onNotification("hydra-acp/prompt_queue/updated",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string"||!$e.has(S.messageId))return;$e.set(S.messageId,De(S.messageId,S.prompt));let x=ze.get(S.messageId);if(x){let R=Array.isArray(S.prompt)?S.prompt:[],C="",O=[];for(let K of R){if(!K||typeof K!="object")continue;let D=K;D.type==="text"&&typeof D.text=="string"?C+=D.text:D.type==="image"&&typeof D.data=="string"&&typeof D.mimeType=="string"&&O.push({data:D.data,mimeType:D.mimeType,sizeBytes:Math.floor(D.data.length*3/4)})}x.text=C,x.attachments=O}Pe&&Mt&&Rn()}),w.onNotification("hydra-acp/prompt_queue/removed",g=>{if(k)return;let S=g??{};if(typeof S.messageId!="string")return;S.reason==="started"&&(Y=S.messageId);let x=On.get(S.messageId);x!==void 0&&(clearTimeout(x),On.delete(S.messageId)),$e.delete(S.messageId)&&Pe&&Mt&&Rn();let C=ze.get(S.messageId);C&&(ze.delete(S.messageId),S.reason==="started"&&(C.flushed=!0,E({kind:"user-text",text:C.displayText,attachments:C.attachments}),mt=C))}),w.onNotification("hydra-acp/cancel_failed",g=>{if(k)return;let S=g??{};if(!(typeof Pe<"u"&&Pe!==null))return;vn=Date.now(),Ws=!0;let R=typeof S.code=="number"?` (${S.code})`:"",C=typeof S.message=="string"&&S.message.length>0?`: ${S.message}`:"";Pe.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 S=g??{};if(typeof S.cancelledMessageId!="string")return;let x=S.cancelledMessageId;ts.add(x),mt!==null&&mt.messageId!==void 0&&mt.messageId===x&&(E({kind:"turn-complete",stopReason:"cancelled",amended:!0}),mt=null,ts.delete(x))});let Jt=g=>{let S=g??{},x=typeof S.phase=="string"?S.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 S.error=="string"?S.error:"unknown error",C=R.length>40?R.slice(0,40)+"...":R;I.notify(`compaction failed: ${C}`,5e3)}},Ar=()=>{he===null&&(he=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let S=await g.json();S.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),he!==null&&(clearInterval(he),he=null)):S.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),he!==null&&(clearInterval(he),he=null))}catch{}},5e3))},fd=()=>{he!==null&&(clearInterval(he),he=null)},pd=g=>{let S=g??{},x=typeof S.toolCallId=="string"?S.toolCallId:void 0,R;S.outcome&&typeof S.outcome=="object"?R=S.outcome:typeof S.chosenOptionId=="string"&&(R={kind:"selected",optionId:S.chosenOptionId}),hd(x,R?{outcome:R}:void 0)},Ne=null,hd=(g,S)=>{if(!Ne||Ne.toolCallId&&g&&Ne.toolCallId!==g)return;let x=Ne.resolve;Ne=null,I.setPermissionPrompt(null),x(S??{outcome:{outcome:"cancelled"}})},Vt=g=>{if(!Ne?.toolCallId)return;let S=g??{};S.sessionUpdate!=="tool_call"&&S.sessionUpdate!=="tool_call_update"||S.toolCallId===Ne.toolCallId&&(!S.status||S.status==="pending"||hd(S.toolCallId,void 0))},As=()=>{if(!Ne){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:Ne.title,detail:Ne.detail,options:Ne.options.map(g=>({label:g.name})),selectedIndex:Ne.selectedIndex})},Sn=g=>{if(!Ne)return;let{options:S,resolve:x}=Ne;if(Ne=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 hi(g);let S=g??{},R=(Array.isArray(S.options)?S.options:[]).map(Z=>({optionId:Z.optionId,name:Te(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=S.toolCall?.title??S.toolCall?.name??"tool",O=Te(C),K=Te(uv(lv(g))),D=S.toolCall?.toolCallId;return R.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${O} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{Ne={title:O,detail:K,options:R,selectedIndex:0,resolve:Z,toolCallId:D},As()})}),w.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Ln,yt,$t=!0,xt=!1;try{let g=await w.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}});yt=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&($t=!1),xt=hn(g?._meta??void 0).prompt?.amending===!0}catch{}let me=a.sessionId,Ht=a.agentId,ot=a.cwd,vi,Gn,Yn,Ut,Si,ki,Ii,zs,Cr,kn,jo=!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 S={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Bt]:g}}:{}},x;try{x=await tv({request:()=>w.request("session/new",S),showBanner:(O,K,D)=>nv(n,O,K,D,{authenticate:Z=>w.request("authenticate",{methodId:Z})}),resolveOnboarding:async O=>{if(O)try{return(await ri(t)).find(Z=>Z.id===O)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(O){n.grabInput(!1),re({src:"grab",site:"runSession.session-new-failed",on:!1}),y.close().catch(()=>{});let K=O instanceof Error?O.message:String(O);re({src:"session-new-failed",agentId:s.agentId??null,message:K});let D=await DS(n,s.agentId,K,{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),re({src:"grab",site:"runSession.auth-cancel",on:!1}),y.close().catch(()=>{}),null;if(x.kind==="back"){n.grabInput(!1),re({src:"grab",site:"runSession.auth-back",on:!1}),y.close().catch(()=>{});let O={...s};return delete O.sessionId,delete O.forceNew,delete O.resume,delete O.agentId,O}let R=x.result;u.write(c),me=R.sessionId,Ih(me),r.sessionId=me,r.readonly=!1;let C=hn(R._meta??void 0);C.clientId&&(Gn=C.clientId),Ln=C.upstreamSessionId,C.agentId&&(Ht=C.agentId),C.cwd&&(ot=C.cwd),C.title&&(vi=C.title),Yn=C.currentModel,Ut=C.currentMode,Cr=C.currentUsage,kn=C.turnStartedAt,C.availableCommands&&(Si=xc(C.availableCommands)),C.availableModes&&(ki=C.availableModes),Ii=pk(R.configOptions),zs=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 S=await w.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:be},...Object.keys(g).length>0?{_meta:{[Bt]:g}}:{}});me=S.sessionId,Ih(me),S.clientId&&(Gn=S.clientId),r.sessionId=me,r.readonly=s.readonly===!0;let x=hn(S._meta??void 0);jo=x.resurrected===!0,Ln=x.upstreamSessionId,x.agentId&&(Ht=x.agentId),x.cwd&&(ot=x.cwd),x.title&&(vi=x.title),Yn=x.currentModel,Ut=x.currentMode,Cr=x.currentUsage,kn=x.turnStartedAt,x.availableCommands&&(Si=xc(x.availableCommands)),x.availableModes&&(ki=x.availableModes),Ii=pk(S.configOptions),zs=x.queue}let Ks=L.tuiHistoryFile(me),Rr=L.globalTuiHistoryFile(),nn=await ka(Ks).catch(()=>[]),ke=await ka(Rr).catch(()=>[]);ke.length>e.tui.promptHistoryMaxEntries&&(ke=ke.slice(ke.length-e.tui.promptHistoryMaxEntries));let In=[...nn],Ae=new Bs({history:oc(ke,In)});Mt=Ae;let Bn=!1,Tr=(g,S)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let R=(S??g).replace(/\n+$/,""),C=Ia(nn,x),O=C!==nn;nn=C,In=Ia(In,R);let K=Ia(ke,x,e.tui.promptHistoryMaxEntries),D=K!==ke;ke=K,Ae.setHistory(oc(ke,In)),O&&Xr(Ks,nn).catch(()=>{}),D&&uy(Rr,x).catch(()=>{})};U>0&&Ae.setTurnRunning(!0);let wt=null,jt=null;IS(xS(e.tui.ambiguousWidth,process.env)),pb(e.tui.diffContextLines);let Js=!1,I,qo=()=>{Js&&(Js=!1,I.start())},md=()=>{Js||(Js=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",qo);let Vs=null,xi=null;I=new Bl({term:n,dispatcher:Ae,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:O_(e.tui.openFileCommand),progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?md:void 0,onLayoutChange:()=>{Uh()},onBlockClick:(g,S,x)=>{Kk(g,S,x)},onHydraLinkClick:g=>(j(g),!0),onBlockVisible:g=>{Ok(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let S=Hr.get(g);if(S!==void 0&&S.length>0)return new Set(S);let x=I.contiguousRun(g,new Set(nr.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Vs=I.bannerHitAt(g.x,g.y),xi=Vs?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=xi,R=Vs;if(xi=null,Vs=null,R!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===R){if(R==="mode"){Br(!0);return}let C=R==="pick"?{type:"switch-session"}:R==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Rh(C))return;Q(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let S={type:"attachment-request",source:"primary"};s.readonly===!0&&Rh(S)||Q(S)},onKey:g=>{for(let S of g){if(G&&Qo(S)){S.type==="key"&&re({src:"key-swallowed",site:"compactionPrompt",name:S.name});continue}if(Ne&&Mr(S)){S.type==="key"&&re({src:"key-swallowed",site:"permission",name:S.name});continue}if(Rs(S)){S.type==="key"&&re({src:"key-swallowed",site:"help",name:S.name});continue}if(ea(S)){S.type==="key"&&re({src:"key-swallowed",site:"questions",name:S.name});continue}if(rn(S)){S.type==="key"&&re({src:"key-swallowed",site:"options",name:S.name});continue}if(yd(S)){S.type==="key"&&re({src:"key-swallowed",site:"scrollbackSearch",name:S.name});continue}if(gd(S)){S.type==="key"&&re({src:"key-swallowed",site:"completion",name:S.name});continue}if(Ko(S)){S.type==="key"&&re({src:"key-swallowed",site:"btwClose",name:S.name});continue}if(S.type==="key"&&S.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(S.type==="attachment-paths"){ie(S.paths);continue}if(S.type==="key"&&_r(S.name)){re({src:"key-swallowed",site:"userHotkey",name:S.name});continue}let x=Ae.feed(S);for(let R of x)s.readonly===!0&&Rh(R)||Q(R)}zo(),I.setBannerSearchIndicator(Ae.state().historySearchQuery),I.setAttachments(Ae.state().attachments),I.refreshPrompt()}}),Pe=I,I.setStickyBottomKey("plan");let Er=[{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]"}],Ve=Si??[],Cs=ki??[],Wo=Ii??[],sn=()=>Wo.find(g=>g.id==="agent"),Yl=()=>{let g=new Set,S=[];for(let x of[...Er,...Ve])g.has(x.name)||(g.add(x.name),S.push(x));return S},bt=()=>{let g=Ae.state().buffer,S=g[0]??"";if(!S.startsWith("/"))return[];if(g.length>1)return[];let x=S.indexOf(" "),R=x===-1?S:S.slice(0,x);if(R.lastIndexOf("/")>0)return[];let C=Yl().filter(O=>O.name.startsWith(R));return C.length===1&&C[0]?.name===R?[]:C},Gt=[],zo=()=>{let g=bt();if(g.length>0){Gt=[],I.setCompletions(g);return}I.setCompletions(Gt)},gd=g=>{if(g.type!=="key"||g.name!=="tab")return Gt.length>0&&(Gt=[]),!1;let S=bt();if(I.isOverlayOpen()&&S.length===0)return I.toggleFocusedPane(),!0;if(S.length>0){Gt=[];let x=Ae.state().buffer[0]??"",R=PS({matches:S.map(C=>C.name),firstLine:x});return R===null||Ae.replaceFirstLine(R),!0}return Pr()},Pr=()=>{let g=Ae.state(),S=g.buffer[g.row]??"",x=jl(S,g.col);if(x===null)return!1;let R=ql(x.token,ot);return R===null?!1:(R.replacement!==x.token&&Ae.replaceRangeOnCurrentLine(x.start,g.col,R.replacement),Gt=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},Ko=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(P&&(P.cancel(),P=null,$=null),I.closeBtwOverlay(),!0),yd=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 S=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(S),!0}if(g.type==="paste"){let S=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(S),!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 S=I.scrollbackSearchTerm();return S.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(S.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},Mr=g=>{if(!Ne)return!1;let S=Ne.options;if(g.type==="key")switch(g.name){case"up":return Ne.selectedIndex=Math.max(0,Ne.selectedIndex-1),As(),!0;case"down":return Ne.selectedIndex=Math.min(S.length-1,Ne.selectedIndex+1),As(),!0;case"enter":{let x=S[Ne.selectedIndex];return x&&Sn(x.optionId),!0}case"escape":case"ctrl-c":return Sn(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,R=S[x];return R&&Sn(R.optionId),!0}return!0},_r=g=>{let S=e.tui.hotkeys[g];return S?(US(S,{sessionId:me,cwd:ot,agentId:Ht||yt||"",baseUrl:t.baseUrl,tokenFile:L.authToken()},{notify:x=>I.notify(x),cwd:ot,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},Gs=()=>Ht||yt||"?",Jo=Gs(),Yt={...Cr??{}};u.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSidebarGadgets(e.tui.sidebar.gadgets),I.setSidebarWidth(e.tui.sidebar.width??null),I.setSidebarBorder(e.tui.sidebar.border),I.setSidebarSnapshot({usage:{...Yt},model:Yn??null,mode:Ut??null,sessionId:me===null?null:ut(me),agent:Jo}),I.setSessionbar({agent:Jo,cwd:ot,sessionId:me,title:vi,model:Yn,usage:{...Yt}}),Ut&&I.setBanner({currentMode:Ut}),Ga().then(g=>{g&&I.notify(`\u2728 ${Ya(g)}`,3e4)}).catch(()=>{});let At=null,Vo=new Promise(g=>{At=g}),Ai=()=>{w.notify("session/cancel",{sessionId:me}).catch(()=>{})},Ys=()=>{Pe!==null&&U===1&&(X=!0,Pe.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Qn=()=>{if(wt){wt.cancel(),Ys();return}if(U>0){Ai(),Ys();return}Xn()},Xn=()=>{Xs(0)},Ci=()=>{let g="enqueue prompt (sends now, or queues during a turn)",S="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",S],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",S]],...L_]},wd=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:Ci(),hint:"any key dismisses \xB7 /help lists commands"})},Go=()=>{G=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Yo=()=>{G=!1,I.setCompactionPrompt(null)},bd=g=>{let S=I.compactionPromptSpec();if(!S)return;let x=S.options.length;if(x===0)return;let R=((S.selectedIndex+g)%x+x)%x;R!==S.selectedIndex&&I.setCompactionPrompt({...S,selectedIndex:R})},Qo=g=>{if(!G)return!1;if(g.type==="key"){if(g.name==="escape")return Yo(),!0;if(g.name==="up")return bd(-1),!0;if(g.name==="down")return bd(1),!0;if(g.name==="enter"){let S=I.compactionPromptSpec();return S?.options[S.selectedIndex]?.key==="y"?Go():Yo(),!0}}if(g.type==="char"){let S=g.ch.toLowerCase();if(S==="y"||S==="1")return Go(),!0;if(S==="n"||S==="2")return Yo(),!0}return!0},Rs=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Ts=["tools","plan","thoughts","diffs","mouse","enter","sidebar"],xn=0,Qt=null,Qs=[],$r=[],Ct=[],Fr=0,Zn=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;case"sidebar":return I.isSidebarVisible()?"shown":"hidden"}},es=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";case"sidebar":return"Sidebar"}},Xo=()=>({title:"Session options",options:Ts.map(g=>({label:es(g),value:Zn(g)})),selectedIndex:xn}),Zo=()=>{I.isOptionsPromptActive()&&Qt===null&&I.setOptionsPrompt(Xo())},Or=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}xn=0,I.setOptionsPrompt(Xo())},Es=()=>{if(Qt===null)return;let g=P_(Qt,Qs,Ct,Fr);I.setOptionsPrompt(g)},An=()=>{Qt=null,Qs=[],$r=[],Ct=[],Fr=0,I.setOptionsPrompt(null)},Ri=async()=>{if(Qt!==null){An();return}try{let S=await w.request(Fv,{sessionId:me}),x=C_(S.questions??[]);if(x.length===0){I.notify("no open questions");return}let R=T_(x);Qt=R,Fr=0,Qs=R.map(C=>R_(C.representative)),$r=R.map(()=>!1),Ct=R.map(()=>!1),Es()}catch(g){I.notify("clarifier unavailable"),re({src:"questions",step:"list_failed",error:g.message})}},Cn=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Dr.clear(),Pi.clear(),ta();break;case"plan":i.planExpanded=!i.planExpanded,z=null,je();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",an.clear(),Hh();break;case"mouse":{let S=!I.isMouseEnabled();I.setMouseEnabled(S),i.mouseEnabled=S;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":cu(!I.isSidebarVisible());break}Zo()},Ti=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${es(g)} is session-only \u2014 not saved`);return;case"thoughts":await ia("showThoughts",i.showThoughts);break;case"diffs":await ia("showFileUpdates",i.showFileUpdates);break;case"mouse":await ia("mouse",i.mouseEnabled);break;case"enter":await ia("defaultEnterAction",i.defaultEnterAction);break;case"sidebar":await rm(I.isSidebarVisible());break}I.notify(`saved default: ${es(g)} ${Zn(g)}`)}catch(S){I.notify(`save failed: ${S instanceof Error?S.message:String(S)}`)}})()},rn=g=>{if(Qt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return xn=Math.max(0,xn-1),Zo(),!0;case"down":return xn=Math.min(Ts.length-1,xn+1),Zo(),!0;case"enter":{let S=Ts[xn];return S&&Cn(S),!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 S=parseInt(g.ch,10)-1,x=Ts[S];return x&&(xn=S,Cn(x)),!0}if(g.ch==="s"||g.ch==="S"){let S=Ts[xn];return S&&Ti(S),!0}}return!0},ea=g=>{if(Qt===null)return!1;let S=$_(g,!0,Qt,Qs,$r,Ct,Fr,me);switch(S.type){case"noop":return!0;case"row":return Fr=S.selectedRow,Es(),!0;case"cycle":return Qs[S.selectedRow]=S.newValueIndex,$r[S.selectedRow]=!0,Ct[S.selectedRow]=!1,Es(),!0;case"dismiss-toggle":{let x=S.selectedRow;return Ct[x]?(Ct[x]=!1,$r[x]=!1):(Ct[x]=!0,$r[x]=!0),Es(),!0}case"discard":return An(),!0;case"save":{let x=S.dispatches;return An(),x.length===0||(async()=>{let R=0,C=0,O=0;for(let D of x)try{await w.request(D.method,D.params),D.type==="dismiss"?C++:R++}catch(Z){O++,re({src:"questions",step:"dispatch_failed",method:D.method,error:Z.message})}let K=[];R>0&&K.push(`${R} answered`),C>0&&K.push(`${C} dismissed`),O>0&&K.push(`${O} failed`),K.length>0&&I.notify(`clarifier: ${K.join(", ")}`)})(),!0}}return!1},Lr=()=>{if(!k){k=!0,P?(P.cancel(),P=null,$=null):$!==null&&(bs(t,$).catch(()=>{}),$=null),process.off("SIGINT",Qn),process.platform!=="win32"&&process.off("SIGCONT",qo),It!==null&&(clearInterval(It),It=null),he!==null&&(clearInterval(he),he=null);for(let g of On.values())clearTimeout(g);On.clear(),Jh(),Kh(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Xr(Ks,nn).catch(()=>{}),y.close().catch(()=>{})}},Xs=(g=0)=>{Lr(),At&&(At(null),At=null),g!==0&&process.exit(g)},T=async()=>{if(re({src:"switch-session",step:"entered",finishSessionNull:At===null}),!At)return;P?(P.cancel(),P=null,$=null):$!==null&&(bs(t,$).catch(()=>{}),$=null),fd(),I.setSynthesisIndicator(null);let g=Ae.state().buffer.join(`
|
|
258
|
+
`);g.replace(/\s+$/,"").length>0&&Tr(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Xr(Ks,nn).catch(()=>{});let S=!1;try{let x=null,R=null;for(;x===null;){let D=await Wn(t,{includeNonInteractive:!0}),Z=s.agentId??i.lastChosenAgent??e.defaultAgent,Ce=Z?e.defaultModels?.[Z]:void 0,ye=[];try{ye=await ri(t)}catch{}let ae=await Sh(n,{cwd:ot,sessions:D,config:e,target:t,currentSessionId:me,prefs:o,...Z?{composerAgentId:Z}:{},...Ce?{composerModel:Ce}:{},...ye.length>0?{availableAgents:ye}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){S=!0,Xs(0);return}if(ae.kind==="new"){x={choice:ae,sessions:D};break}if(ae.kind==="fork"){let un=await vk(n,t,ae,D);if(un.kind==="cancel")return;if(un.kind==="back")continue;x={choice:{kind:"attach",sessionId:un.ctx.sessionId,...un.ctx.agentId?{agentId:un.ctx.agentId}:{}},sessions:D},R={readonly:!1,cwd:un.ctx.cwd},un.ctx.resumeHint!==void 0&&(R.resumeHint=un.ctx.resumeHint);break}let qe=D.find(un=>un.sessionId===ae.sessionId);if(!(qe!==void 0&&!!qe.importedFromMachine&&!qe.upstreamSessionId&&ae.readonly!==!0)){if(t.isLocal&&qe&&!qe.importedFromMachine&&ae.readonly!==!0&&!(await Xa(qe.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let sa=await yi(n,qe,{defaultCwd:st(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(sa.kind==="cancel")return;if(sa.kind==="back")continue;x={choice:ae,sessions:D},R={readonly:!1,cwd:sa.path,resumeHint:{agentId:ae.agentId??qe.agentId??"",cwd:sa.path,upstreamSessionId:""}};break}x={choice:ae,sessions:D};break}let ln={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let as=await wk(n,t,qe,ae,ln);if(as.kind==="cancel")return;as.kind!=="back"&&(x={choice:ae,sessions:D},R={readonly:ln.readonly===!0,cwd:as.ctx.cwd},as.ctx.resumeHint!==void 0&&(R.resumeHint=as.ctx.resumeHint))}let{choice:C}=x,O=At;if(At=null,Lr(),S=!0,C.kind==="new"){let{sessionId:D,agentId:Z,...Ce}=s,ye={...Ce,cwd:C.cwd??ot,forceNew:!0,readonly:!1};C.prompt!==void 0&&(ye.initialPrompt=C.prompt),C.attachments&&C.attachments.length>0&&(ye.initialAttachments=C.attachments),C.agentId!==void 0&&(ye.agentId=C.agentId,i.lastChosenAgent=C.agentId),C.model!==void 0&&(ye.model=C.model),C.installStatus!==void 0&&(ye.installStatus=C.installStatus),O(ye);return}if(C.kind!=="attach")return;let K={...s,sessionId:C.sessionId,cwd:R?.cwd??ot,readonly:R?.readonly??C.readonly===!0};C.agentId!==void 0&&(K.agentId=C.agentId),R?.resumeHint!==void 0?K.resumeHint=R.resumeHint:delete K.resumeHint,C.installStatus!==void 0?K.installStatus=C.installStatus:delete K.installStatus,O(K)}finally{!S&&At&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},M=async(g="next")=>{if(!At)return;let x=(await Wn(t)).filter(ye=>ye.status==="warm");if(x.length<=1)return;let R=x.findIndex(ye=>ye.sessionId===me),K=((R===-1?0:R)+(g==="prev"?-1:1)+x.length)%x.length,D=x[K],Z=At;At=null,Lr();let Ce={...s,sessionId:D.sessionId,cwd:ot,readonly:!1,resolved:D};D.agentId!==void 0&&(Ce.agentId=D.agentId),Z(Ce)},j=async g=>{if(!At)return;let S=await Wn(t,{includeNonInteractive:!0}),x=g.trim();if(!x){I.notify("usage: /session <id|next|prev>");return}let R=x.startsWith(Kt)?[x]:[x,Kt+x],C=S.find(D=>R.includes(D.sessionId));if(!C){let D=S.filter(Z=>R.some(Ce=>Z.sessionId.startsWith(Ce)));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===me){I.notify("already on that session");return}let O=At;At=null,Lr();let K={...s,sessionId:C.sessionId,cwd:C.cwd??ot,readonly:!1,resolved:C};C.agentId!==void 0&&(K.agentId=C.agentId),delete K.resumeHint,O(K)},Q=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?on(g.text,g.attachments,g.displayText):er(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?er(g.text,g.attachments,g.displayText):on(g.text,g.attachments,g.displayText);return;case"queue-edit":{let S=Zs(g.index);if(!S)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:me,messageId:S,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 S=Zs(g.index);if(!S)return;w.request("hydra-acp/prompt/cancel",{sessionId:me,messageId:S}).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()){P&&(P.cancel(),P=null,$=null),I.closeBtwOverlay();return}if(g.prefill&&wt){let S=$e.size===0,x=Ae.state().buffer.every(R=>R==="");S&&x&&(jt={text:wt.text,attachments:wt.attachments})}wt?wt.cancel():U>0&&Ai(),Ys();return}case"exit":Xn();return;case"plan-toggle":Br(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":T().catch(S=>{re({src:"switch-session-failed",stack:S instanceof Error?S.stack??S.message:String(S)})});return;case"next-live-session":M("next").catch(()=>{});return;case"prev-live-session":M("prev").catch(()=>{});return;case"toggle-options":Or();return;case"toggle-sidebar":cu(!I.isSidebarVisible());return;case"toggle-questions":Ri();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 S=!I.isMouseEnabled();I.setMouseEnabled(S),i.mouseEnabled=S,I.notify(S?"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":wd();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":oe(g.source);return}},ie=async g=>{if(!$t){I.notify("agent does not accept image attachments");return}let S=0;for(let x of g){if(x.startsWith("data:")){let C=Op(x);if(!C){I.notify("unsupported data: URI");continue}if(C.sizeBytes>ks){I.notify(`image too large (${Fn(C.sizeBytes)}, max ${Fn(ks)})`);continue}Ae.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),S++;continue}let R=ed(x);if(!R){I.notify(`unsupported image type: ${wi.basename(x)}`);continue}try{let C=await Ch.readFile(x);if(C.length>ks){I.notify(`image too large (${Fn(C.length)}, max ${Fn(ks)})`);continue}Ae.addAttachment({mimeType:R,data:C.toString("base64"),name:wi.basename(x),sizeBytes:C.length}),S++}catch(C){I.notify(`cannot read ${wi.basename(x)}: ${C.message}`)}}S>0&&(I.setAttachments(Ae.state().attachments),I.refreshPrompt())},oe=async(g="clipboard")=>{let S=g==="primary"?await zv():await Al();if(!S.ok){I.notify(S.reason);return}if(S.kind==="image"){if(!$t){I.notify("agent does not accept image attachments");return}Ae.addAttachment(S.attachment),I.setAttachments(Ae.state().attachments),I.refreshPrompt();return}let x=Ae.feed({type:"paste",text:S.text});for(let R of x)Q(R);I.refreshPrompt()},Ie=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,De=(g,S)=>{let x=Array.isArray(S)?S:[],R="",C=0;for(let O of x){if(!O||typeof O!="object")continue;let K=O;K.type==="text"&&typeof K.text=="string"?R+=K.text:K.type==="image"&&(C+=1)}return{messageId:g,text:Te(R),attachmentCount:C}},$e=new Map,Ze=[],ze=new Map,ts=new Set,mt=null,Rn=()=>{let g=[...$e.values()],S=g.map(Ie);I.setQueuedPrompts(S),I.setBanner({queued:g.length}),I.setSidebarSnapshot({queued:g.length}),Ae.setQueue(g.map(x=>x.text))},Zs=g=>[...$e.values()][g]?.messageId;if(zs&&zs.length>0){for(let g of zs){if(g.position===0){Y=g.messageId;continue}$e.set(g.messageId,De(g.messageId,g.prompt))}$e.size>0&&Rn()}let er=(g,S,x)=>{I.scrollToBottom(),!vd(g)&&(Tr(g,x),Nn(g,S,x))},on=(g,S,x)=>{if(I.scrollToBottom(),vd(g))return;if(Tr(g,x),!xt||Y===void 0){Nn(g,S,x);return}let R=Y,C=[];g.length>0&&C.push({type:"text",text:g});for(let D of S)C.push({type:"image",data:D.data,mimeType:D.mimeType});let O={text:g,displayText:x??g,attachments:S,flushed:!1};Ze.push(O);let K=()=>{let D=Ze.indexOf(O);D>=0&&Ze.splice(D,1),O.messageId!==void 0&&ze.delete(O.messageId)};w.request("hydra-acp/prompt/amend",{sessionId:me,targetMessageId:R,prompt:C}).then(D=>{let Z=D;if(Z.amended&&Z.reason==="ok"){Pt(1);return}if(K(),Z.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),Ae.setBuffer(g,S),I.refreshPrompt();return}if(Z.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),Ae.setBuffer(g,S),I.refreshPrompt();return}if(Z.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),Ae.setBuffer(g,S),I.refreshPrompt();return}}).catch(D=>{K(),I.notify(`amend failed: ${D.message}`),Ae.setBuffer(g,S),I.refreshPrompt()})},Br=async g=>{if(Cs.length===0){I.notify("no modes advertised by agent");return}let S=I.currentModeId(),x=Cs.findIndex(O=>O.id===S),R=x===-1?0:(x+1)%Cs.length,C=Cs[R]?.id;if(C){I.setBanner({currentMode:C});try{await w.request("session/set_mode",{sessionId:me,modeId:C})}catch(O){I.notify(`set_mode failed: ${O.message}`)}}},vd=g=>{let S=g.replace(/\s+$/,"");if(!S.startsWith("/")||S.includes(`
|
|
259
|
+
`))return!1;let x=S.indexOf(" ");switch(x===-1?S:S.slice(0,x)){case"/quit":case"/exit":return Xn(),!0;case"/clear":return at.clear(),tr.clear(),ss.length=0,Ei.clear(),ft=null,Ft=null,dn=null,ns.clear(),an.clear(),vt.clear(),Dr.clear(),nr.clear(),Hr.clear(),I.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let O of Er)C.push({prefix:" ",body:` ${O.name.padEnd(12)} ${O.description??""}`,bodyStyle:"info"});if(Ve.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let O of Ve)C.push({prefix:" ",body:` ${O.name.padEnd(12)} ${O.description??""}`,bodyStyle:"info"})}return I.appendLines(C),!0}case"/agent":{let C=x===-1?"":S.slice(x+1).trim(),O=sn();if(!O)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 O.options){let Ce=Z.value===O.currentValue?"* ":" ";D.push({prefix:" ",body:`${Ce}${Z.value.padEnd(16)} ${Z.name}`,bodyStyle:"info"})}return I.appendLines(D),!0}let K=O.options.find(D=>D.value===C)?.value;if(!K){let D=C.toLowerCase(),Z=O.options.filter(Ce=>Ce.value.toLowerCase().startsWith(D));Z.length===1&&(K=Z[0].value)}return K?K===O.currentValue?(I.notify(`already on agent ${K}`),!0):(I.notify(`switching to ${K}\u2026`),w.request("session/set_config_option",{sessionId:me,configId:"agent",value:K}).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 T().catch(C=>{re({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=x===-1?"":S.slice(x+1).trim();return C?C==="next"||C==="prev"?(M(C).catch(O=>{I.notify(`session ${C} failed: ${O.message}`)}),!0):(j(C).catch(O=>{I.notify(`session switch failed: ${O.message}`)}),!0):(T().catch(O=>{re({src:"switch-session-failed",stack:O instanceof Error?O.stack??O.message:String(O)})}),!0)}case"/rename":{let C=x===-1?"":S.slice(x+1).trim(),O=C.length>0?`/hydra title ${C}`:"/hydra title";return Tr(S,S),Nn(O,[],S),!0}case"/btw":{let C=x===-1?"":S.slice(x+1).trim();if(!C)return I.isOverlayOpen()?(P&&(P.cancel(),P=null,$=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(me==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let O=N;P&&(P.cancel(),P=null);let K=null;$!==null&&!B?K=$:$!==null&&(bs(t,$).catch(()=>{}),$=null),B=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let D=new kl({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 Ce=ae=>{D.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},ye={};return K!==null&&(ye.reuseSessionId=K),Nv(t,me,C,ye).then(ae=>{if(O!==N){ae.cancel();return}P=ae,$=ae.sessionId,I.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",qe=>{if(O===N)if(qe.kind==="update"){D.append(qe.update);let ve=gs(qe.update);if(ve&&ve.kind==="usage-update"){let ln=!1;ve.used!==void 0&&Z.used!==ve.used&&(Z.used=ve.used,ln=!0),ve.size!==void 0&&Z.size!==ve.size&&(Z.size=ve.size,ln=!0),ve.costAmount!==void 0&&Z.costAmount!==ve.costAmount&&(Z.costAmount=ve.costAmount,ln=!0),ve.costCurrency!==void 0&&Z.costCurrency!==ve.costCurrency&&(Z.costCurrency=ve.costCurrency,ln=!0),ln&&I.setBtwOverlayMeta({usage:{...Z}})}}else qe.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),P=null):qe.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),P=null,$=null):qe.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ce(`btw errored: ${qe.error.message}`),$!==null&&bs(t,$).catch(()=>{}),P=null,$=null)})}).catch(ae=>{if(O!==N)return;let qe=ae instanceof Error?ae.message:String(ae);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ce(`btw startup failed: ${qe}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${qe}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(me==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=x===-1?"":S.slice(x+1).trim(),O=me;return(async()=>{try{let K=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(O)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!K.ok){let qe=await K.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${K.status} ${qe}`.trim(),bodyStyle:"info"}]);return}let D=await K.text(),Z=new Date().toISOString().replace(/[:.]/g,"-"),Ce=`hydra-${ut(O)}-${Z}.md`,ye=C.length>0?st(C):Ce,ae=wi.resolve(ye);await Ch.mkdir(wi.dirname(ae),{recursive:!0}),await Ch.writeFile(ae,D,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(K){I.appendLines([{prefix:" ",body:`/export failed: ${K.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Nn=async(g,S,x)=>{let R=[];g.length>0&&R.push({type:"text",text:g});for(let ye of S)R.push({type:"image",data:ye.data,mimeType:ye.mimeType});Pt(1);let C={text:g,displayText:x??g,attachments:S,flushed:!1};Ze.push(C),Ws=!1;let O=!1,K=null,D=ye=>{typeof Pe<"u"&&Pe!==null&&Pe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:ye,bodyStyle:"tool-status-fail"}])},Z=!1;wt={text:g,attachments:S,cancel:()=>{if(Ws){Ws=!1,Z=!0,D("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),w.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(ae=>{D(`force-stop failed: ${ae.message}`)});return}if(O)return;O=!0,w.notify("session/cancel",{sessionId:me}).catch(()=>{});let ye=Date.now();K=setTimeout(()=>{wt!==null&&(vn>=ye||(Ws=!0,D("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Uo)}};let Ce;try{let ye=await w.request("session/prompt",{sessionId:me,prompt:R});ye&&typeof ye.stopReason=="string"&&(Ce=ye.stopReason)}catch(ye){let ae=Ze.indexOf(C);ae>=0&&Ze.splice(ae,1),C.messageId!==void 0&&ze.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:ye.message,bodyStyle:"tool-status-fail"}])}finally{if(wt=null,K!==null&&(clearTimeout(K),K=null),Pt(-1),C.flushed&&mt===C){let ye=C.messageId!==void 0&&ts.has(C.messageId);ye&&C.messageId!==void 0&&ts.delete(C.messageId);let ae={kind:"turn-complete"};Ce!==void 0&&(ae.stopReason=Ce),ye&&(ae.amended=!0),E(ae),mt=null}if(jt!==null){let{text:ye,attachments:ae}=jt;jt=null,Ae.state().buffer.every(ve=>ve==="")&&(Ae.setBuffer(ye,ae),I.refreshPrompt())}}},at=new Map,ns=new Map,an=new Map,tr=new Map,ss=[],Ei=new Map,Sd=[],Nr=0,qt=`tools:${Nr}`,vt=new Map,Dr=new Map,Pi=new Set,Mi=new Map,nr=new Map,Hr=new Map,ft=null,Ft=null,dn=null,F=null,z=null,ce=e.tui.maxToolItems,V=e.tui.maxPlanItems,ue=()=>({maxPlanItems:z??i.planExpanded?1/0:V}),le=g=>{let S=wr(g,ue());S.length>0&&I.upsertLines("plan",[{body:""},...S]);let x=g.entries.length>0&&g.entries.every(R=>(R.status??"pending")==="completed");I.setStickyBottomKey(x?null:"plan")},je=()=>{if(F===null)return;let g=wr(F,ue());g.length>0&&I.upsertLines("plan",[{body:""},...g])},Fe="",Me=null,dt=0,Xt=()=>{if(Me===null)return;let g=I.width(),S=br(Fe,g>0?{maxWidth:g}:void 0);S.length!==0&&I.upsertLines(Me,S)},rs=g=>{g.length!==0&&(Me===null&&(I.ensureSeparator(),Me=`agent:${dt}`,dt+=1,Fe=""),Fe+=g,Xt())},Ge=()=>{Me=null,Fe=""},Re="",ct=null,Dn=0,cn=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Ps=()=>{if(ct===null||Re.length===0)return;let g=Ro(Re);g.length!==0&&I.upsertLines(ct,g)},Ur=g=>{let S=nr.get(g);if(S===void 0)return[];let x=Ro(S.text);return S.workerTaskId&&x.unshift({prefix:" ",body:`[T${S.workerTaskId}] `,bodyStyle:"dim"}),x},Ql=(g,S)=>{g.length!==0&&(ct===null&&(I.ensureSeparator("thought"),ct=`thought:${Dn}`,Dn+=1,Re=""),Re+=g,nr.set(ct,{text:Re,workerTaskId:S}),Ps())},is=()=>{ct=null,Re=""},_i=g=>H_({...g,collapsedLimit:ce}),Ke=g=>Dr.get(g)??i.toolsExpanded,Ye=()=>{if(ft===null)return;let{lines:g,rowOwners:S}=_i({order:ss,states:at,startedAt:ft,endedAt:Ft,stopReason:dn,expanded:Ke(qt),perToolExpanded:Pi});I.upsertLines(qt,g),Mi.set(qt,S)},os=g=>{let S=vt.get(g);if(!S)return;let{lines:x,rowOwners:R}=_i({order:S.order,states:S.states,startedAt:S.startedAt,endedAt:S.endedAt,stopReason:S.stopReason,expanded:Ke(g),perToolExpanded:Pi});I.upsertLines(g,x),Mi.set(g,R)},ta=()=>{ft!==null&&!vt.has(qt)&&Ye();for(let g of vt.keys())os(g)},Xl=()=>{ft!==null&&vt.set(qt,{order:[...ss],states:new Map(at),startedAt:ft,endedAt:Ft??Date.now(),stopReason:dn,rowOwners:Mi.get(qt)??[]})},Fh=()=>{Nr+=1,qt=`tools:${Nr}`,ft=Date.now(),Ft=null,dn=null,Ye()};function _k(g){if(!g||typeof g!="object")return null;let S=g,x=Array.isArray(S.content)?S.content:void 0;if(!x)return null;let R=[],C=O=>{if(typeof O=="string"){R.push({text:St(O)});return}if(O&&typeof O=="object"){let K=O;typeof K.__hydraBlob=="string"&&R.push({hash:K.__hydraBlob})}};for(let O of x){if(!O||typeof O!="object")continue;let K=O;if(K.type==="content"&&K.content&&typeof K.content=="object"){let D=K.content;if(D.text!==void 0){C(D.text);continue}}if(K.type==="text"&&K.text!==void 0){C(K.text);continue}K.text!==void 0&&C(K.text)}return R.length>0?R:null}let Oh=(g,S)=>{let x=S.map(O=>"text"in O?O.text:"").join(`
|
|
260
|
+
`);if(x.length===0)return;let{text:R,truncated:C}=lb(x);g.resultText=R,g.resultTruncated=C},kd=new Set,$k=(g,S)=>{!S.some(R=>"hash"in R)||kd.has(g)||(kd.add(g),(async()=>{let R=await Promise.all(S.map(async O=>"text"in O?O:{text:await eu(O.hash)??""}));kd.delete(g);let C=at.get(g);if(!C)for(let O of vt.values()){let K=O.states.get(g);if(K){C=K;break}}if(C){Oh(C,R),at.has(g)&&Ye();for(let[O,K]of vt)K.states.has(g)&&os(O);I.repaintNow()}})().catch(()=>{kd.delete(g)}))},Zl=(g,S)=>{let x=S??at.get(g);if(x===void 0)return;let R=tk(x,ns.get(g)??x.editDiff,ot);if(R===null){Ei.delete(g);return}Ei.set(g,R)},Lh=(g,S,x,R,C,O,K,D,Z,Ce,ye)=>{let ae=!at.has(g),qe=at.get(g),ve=qe??{initialTitle:S??"tool",latestTitle:S??"tool",status:x??"pending",startedAt:Date.now()};if(!qe&&Z!==void 0&&(ve.workerTaskId=Z),ye!==void 0&&ve.rawKind===void 0&&(ve.rawKind=ye),qe&&S!==void 0&&(ve.latestTitle=S),O!==void 0&&ve.detail===void 0&&(ve.detail=O),K!==void 0&&ve.detailFull===void 0&&(ve.detailFull=K),D!==void 0&&D.length>0&&(ve.locations=D),qe&&x!==void 0&&(ve.status=x),qe||(ve.status=x??"pending"),ve.endedAt===void 0&&ip(ve.status)&&(ve.endedAt=Date.now(),du()),R!==void 0&&(ve.errorText=R),C!==void 0&&(ve.editDiff=C),Ce!==void 0){let as=_k(Ce);as!==null&&(Oh(ve,as),as.some(un=>"hash"in un)&&$k(g,as))}at.set(g,ve),Zl(g,ve);let ln=rk(Ce);ln!==null&&(Sd=ln,du(),ln.length>0&&le({kind:"plan",entries:ln})),ae&&(ft===null&&(Nr+=1,qt=`tools:${Nr}`,ft=Date.now(),Ft=null,dn=null),ss.push(g),I.isSidebarVisible()&&Rd())},eu=async g=>{try{let S=await w.request("hydra-acp/session/tool_content",{sessionId:me,hash:g});return typeof S?.content=="string"?S.content:null}catch{return null}},Id=new Set,Fk=(g,S)=>{Id.has(g)||S.oldRef===void 0&&S.newRef===void 0||(Id.add(g),(async()=>{let[x,R]=await Promise.all([S.oldRef?eu(S.oldRef.hash):Promise.resolve(S.oldText),S.newRef?eu(S.newRef.hash):Promise.resolve(S.newText)]);if(S.oldRef!==void 0&&x===null||S.newRef!==void 0&&R===null){Id.delete(g);let Ce=Nh(g,S,np(S,"diff",{deferredStatus:"error"}));Ce.length>0&&(I.upsertLines(`editdiff:${g}`,Ce),I.repaintNow());return}let O={...S.path!==void 0?{path:S.path}:{},oldText:x??"",newText:R??""};ns.set(g,O);let K=at.get(g);K?.editDiff&&(K.editDiff=O),Zl(g),Id.delete(g);let D=an.get(g),Z=D===void 0?i.showFileUpdates:D?"diff":"edit";Z!=="none"&&(xd(g,O,Z==="diff"?"diff":"edit"),I.repaintNow())})())},Bh=new Map,Nh=(g,S,x)=>{let R=Bh.get(g);return R===void 0&&(R=at.get(g)?.locations?.[0]?.line??zk(S),Bh.set(g,R)),R===null?x:x.map(C=>C.links===void 0?C:{...C,links:C.links.map(O=>({...O,url:`${O.url}#L${R}`}))})},xd=(g,S,x)=>{let R=`editdiff:${g}`,C=Nh(g,S,np(S,x));if(C.length===0){I.removeKey(R);return}I.upsertLines(R,C),x==="diff"&&(S.oldRef!==void 0||S.newRef!==void 0)&&I.notifyWhenVisible(R)},Ok=g=>{if(!g.startsWith("editdiff:"))return;let S=g.slice(9),x=ns.get(S);x&&(x.oldRef!==void 0||x.newRef!==void 0)&&Fk(S,x)},Dh=g=>{let S=`editdiff:${g}`,x=i.showFileUpdates,R=at.get(g),C;if(x==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let K=an.get(g);C=K!==void 0?K?"diff":"edit":x==="diff"?"diff":"edit"}if(C===null){I.removeKey(S);return}let O=R.editDiff;ns.set(g,O),Zl(g),xd(g,O,C)},Hh=()=>{let g=i.showFileUpdates;for(let[S,x]of ns){let R=`editdiff:${S}`,C=an.get(S),O=C===void 0?g:C?"diff":"edit";if(O==="none"){I.removeKey(R);continue}xd(S,x,O==="diff"?"diff":"edit")}},Uh=()=>{I.isSidebarOverlay()||(ta(),Hh(),je(),Xt(),Ps())},tu=!1,nu=null,jh=g=>{fk("git",["status","--porcelain=v2","--branch"],{cwd:g,timeout:3e3,maxBuffer:4*1024*1024},(S,x)=>{tu=!1,I.setSidebarSnapshot({git:S?null:ZS(x,nu)})})},su=()=>{if(tu||ot===null)return;let g=ot;if(tu=!0,nu!==null){jh(g);return}fk("git",["rev-parse","--show-toplevel"],{cwd:g,timeout:3e3},(S,x)=>{S||(nu=x.trim()||null),jh(g)})},Lk="hydra",Bk="agent",Ad=null,ru=!1,Cd=null,na=null,iu=null,ou=!1,qh=(()=>{try{let g=new URL(t.baseUrl).hostname;return g==="127.0.0.1"||g==="localhost"||g==="::1"||g==="[::1]"}catch{return!1}})(),Wh=()=>{ou||me===null||(ou=!0,(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(g.ok){let S=await g.json();iu=typeof S.agentPid=="number"?S.agentPid:null}}catch{}finally{ou=!1}})())},zh=()=>{ru||(ru=!0,(async()=>{try{let g=[],S=process.cpuUsage(),x=Date.now();g.push({label:Lk,rssBytes:process.memoryUsage.rss(),cpuFraction:ak(S,Cd,na===null?0:x-na),processes:1}),Cd=S,na=x;let R=iu;if(R!==null){let C=await ck([R]),O=dk(C,Ad,R);O!==null&&g.push({label:Bk,...O}),Ad=C}I.setSidebarSnapshot({resources:g})}finally{ru=!1}})())},Nk=()=>{I.isSidebarGadgetConfigured("resources")&&(Ad=null,Cd=null,na=null,qh&&Wh(),zh())},Dk=()=>{Ad=null,Cd=null,na=null,iu=null,I.setSidebarSnapshot({resources:[]})},Hk=()=>{I.isSidebarGadgetConfigured("git")&&su()},Kh=()=>{I.setSidebarSnapshot({git:null})},Uk=5,$i=null,au=0,jk=()=>{$i===null&&(au=0,$i=setInterval(()=>{au++;let g=au%Uk===0;(pe!==null||g)&&Rd(),g&&I.isSidebarGadgetConfigured("git")&&su(),g&&I.isSidebarGadgetConfigured("resources")&&(qh&&Wh(),zh())},1e3),$i.unref?.())},Jh=()=>{$i!==null&&(clearInterval($i),$i=null)},du=()=>{I.isSidebarVisible()&&(Rd(),I.isSidebarGadgetConfigured("git")&&su())},cu=g=>{i.sidebarVisible=g,I.setSidebarVisible(g),Uh(),Rd(),I.isSidebarSuppressed()?I.notify("sidebar needs a wider terminal (80+ columns)"):g&&I.isSidebarOverlay()&&I.notify("sidebar overlaying transcript (too wide to reflow)"),I.fullRedraw(),g?(Hk(),Nk(),jk()):(Kh(),Dk(),Jh())},Rd=()=>{I.setSidebarSnapshot({busySince:pe,lastTurnEndedAt:nt,queued:$e.size,plan:qk(),editedFiles:Wk(),running:Yv(ss,at,ot),sessionId:me===null?null:ut(me),agent:Gs()})},qk=()=>F!==null&&F.entries.length>0?F.entries:Sd,Wk=()=>nk(Ei.values()),zk=g=>{if(!g.path)return null;let S=St(g.oldText).split(`
|
|
261
261
|
`),x=St(g.newText).split(`
|
|
262
|
-
`),R=0,C=Math.min(S.length,x.length);for(;R<C&&S[R]===x[R];)R++;let
|
|
263
|
-
`);for(let Ce=0;Ce<Z.length;Ce++)if(Z[Ce]===
|
|
262
|
+
`),R=0,C=Math.min(S.length,x.length);for(;R<C&&S[R]===x[R];)R++;let O=x[R];if(!O)return null;let K=wi.isAbsolute(g.path)?g.path:wi.resolve(ot,g.path),D;try{D=k_(K,"utf8")}catch{return null}let Z=D.split(`
|
|
263
|
+
`);for(let Ce=0;Ce<Z.length;Ce++)if(Z[Ce]===O)return Ce+1;return null},Kk=(g,S,x=null)=>{if(g.startsWith("editdiff:")){let R=g.slice(9),C=ns.get(R);if(!C)return;let O=an.get(R)??i.showFileUpdates==="diff";an.set(R,!O),xd(R,C,O?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(F===null)return;z=!(z??i.planExpanded),je(),I.repaintNow();return}if(g.startsWith("tools:")){if(x===null&&S===0){let O=Dr.get(g)??i.toolsExpanded;Dr.set(g,!O),g===qt&&ft!==null?Ye():os(g),I.repaintNow();return}let C=x??Mi.get(g)?.[S];if(!C)return;B_(C,Pi),g===qt&&ft!==null?Ye():os(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!nr.has(g))return;let R=Hr.get(g);if(R!==void 0){Hr.delete(g),I.setRunCollapsed(R,!1,Ur(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(nr.keys()));if(C.length===0)return;let O=C[0];Hr.set(O,C),I.setRunCollapsed(C,!0,[cn()]),I.repaintNow();return}};v=(g,S)=>{if(g.kind==="available-commands"){Ve=g.commands,zo();return}if(g.kind==="available-modes"){Cs=g.modes;return}if(g.kind==="config-options"){Wo=g.options;let R=g.options.find(O=>O.id==="agent");R&&R.currentValue&&R.currentValue!==Ht&&(Ht=R.currentValue,I.setSessionbar({agent:R.currentValue}),I.setSidebarSnapshot({agent:Gs()}));let C=g.options.find(O=>O.id==="mode");C&&(Cs=C.options.map(O=>({id:O.value,name:O.name??O.value,...O.description!==void 0?{description:O.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0}),I.setSidebarSnapshot({mode:g.mode||null});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Ht&&(Ht=g.agentId,I.setSessionbar({agent:g.agentId}),I.setSidebarSnapshot({agent:Gs()})),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&&Yt.used!==g.used&&(Yt.used=g.used,R=!0),g.size!==void 0&&Yt.size!==g.size&&(Yt.size=g.size,R=!0),g.costAmount!==void 0&&Yt.costAmount!==g.costAmount&&(Yt.costAmount=g.costAmount,R=!0),g.costCurrency!==void 0&&Yt.costCurrency!==g.costCurrency&&(Yt.costCurrency=g.costCurrency,R=!0),R&&(I.setSessionbar({usage:{...Yt}}),I.setSidebarSnapshot({usage:{...Yt}}));return}if(g.kind==="user-text"){Bn&&Tr(g.text),Ge(),is(),ft!==null&&(Ft=Date.now(),Ye()),mt=null,I.ensureSeparator();let R=wr(g);R.length>0&&I.appendLines(R),Xl(),I.clearKey("plan"),F=null,z=null,at.clear(),tr.clear(),ss.length=0,Ft=null,Fh(),I.redraw();return}if(g.kind==="agent-text"){is(),Me===null&&H(g.workerTaskId),rs(g.text);return}if(g.kind==="agent-thought"){Ge(),ct===null&&H(g.workerTaskId),Ql(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){Ge(),is();let R=tr.get(g.toolCallId),C={plan:g.plan??R?.plan??"",status:g.status??R?.status};if(tr.set(g.toolCallId,C),C.plan.length===0)return;let O=gb(C);O.length>0&&I.upsertLines(g.toolCallId,O);return}if(g.kind==="tool-call"){Ge(),is(),at.has(g.toolCallId)||H(g.workerTaskId),Lh(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,S,g.rawKind),Ye(),Dh(g.toolCallId);return}if(g.kind==="plan"){Ge(),is(),F=g,du(),le(g);return}if(g.kind==="tool-call-update"){Ge(),is(),Lh(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,S),g.upstreamInterrupted&&(Je=!0),Ye(),Dh(g.toolCallId);return}g.kind==="model-changed"&&(I.setSessionbar({model:g.model}),I.setSidebarSnapshot({model:g.model}));let x=wr(g);if(x.length>0&&I.appendLines(x),g.kind==="turn-complete"){Y=void 0,Ge(),is();let R=g.amended?"amended":g.stopReason;if(!g.amended&&Je&&(R===void 0||R==="end_turn")&&(R="error"),F!==null&&R!==void 0&&R!=="end_turn"){let C=wr({...F,stopped:!0,amended:g.amended===!0},ue());C.length>0&&I.upsertLines("plan",[{body:""},...C])}F=null,z=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),ft!==null?(Ft=Date.now(),dn=R??null,Ye(),Xl()):R!==void 0&&R!=="end_turn"&&R!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${R}`,bodyStyle:"tool-status-fail"}]),at.clear(),tr.clear(),ss.length=0,ft=null,Ft=null,dn=null,Je=!1,I.ensureSeparator(),YS({pendingTurns:U,queueSize:$e.size,ownTurnInFlight:wt!==null,hasInFlightHead:Y!==void 0,replayDraining:A,amended:g.amended===!0})&&Pt(-U)}};let Vh=b;b=[];let Td=[];for(let{event:g}of Vh)g.kind==="user-text"&&typeof g.text=="string"&&Td.push(g.text);I.pauseRepaint(),A=!0;try{for(let{event:g,rawUpdate:S}of Vh)v(g,S)}finally{A=!1,I.resumeRepaint()}if(Td.length>0){let g=If(nn,Td);g!==nn&&(nn=g,In=If(In,Td),Ae.setHistory(oc(ke,In)),Xr(Ks,nn).catch(()=>{}))}Bn=!0,i.sidebarVisible&&cu(!0),(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let S=await g.json(),x=S.compactionState?.status;if(x==="requested"||x==="running"?I.setCompactionIndicator("compacting..."):(x==="swap_pending"||x==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!jo||S.shouldCompact!==!0)return;let R=S.approxTokens??0;G=!0,I.setCompactionPrompt({message:`This session has ~${My(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(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let S=await g.json();if(We&&nt===null&&pe===null&&typeof S.updatedAt=="string"){let x=Date.parse(S.updatedAt);Number.isFinite(x)&&(nt=x,I.setSidebarSnapshot({lastTurnEndedAt:nt}))}S.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),Ar()):S.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),kn!==void 0&&U>0?(pe=kn,I.setBanner({status:"busy",elapsedMs:Date.now()-kn}),It===null&&(It=Ee()),ft===null&&Fh(),ft=kn,Ye()):kn===void 0&&U>0&&Pt(-U),qs=!0;let Jk=()=>{if(Ne){let g=Ne.resolve;Ne=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}Ge(),is()},Gh=()=>{ft!==null&&(Ft=Date.now(),dn="reconnect-recovery-failed",Ye(),Xl(),at.clear(),tr.clear(),ss.length=0,ft=null,Ft=null,dn=null)};return m=g=>{re({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},h=async()=>{if(re({src:"reconnect",step:"begin",sessionId:me}),t.isLocal)try{let D=await Wt(await xe());(D.baseUrl!==t.baseUrl||D.wsUrl!==t.wsUrl)&&(re({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){re({src:"reconnect",step:"target-refresh-failed",message:D instanceof Error?D.message:String(D)})}Jk();let g={jsonrpc:"2.0",id:`tui-reinit-${uk()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:be}}};re({src:"reconnect",step:"initialize-send"});try{await y.request(g),re({src:"reconnect",step:"initialize-ok"})}catch(D){re({src:"reconnect",step:"initialize-fail",message:D.message})}let S=_t!==void 0,x={jsonrpc:"2.0",id:`tui-reattach-${uk()}`,method:"session/attach",params:{sessionId:me,historyPolicy:S?"after_message":"none",...S?{afterMessageId:_t}:{},clientInfo:{name:"hydra-acp-tui",version:be},...(()=>{let D={};return Ln!==void 0&&(D.resume={upstreamSessionId:Ln,agentId:Ht,cwd:ot}),e.tui.toolContent==="references"&&(D.toolContent="references"),Object.keys(D).length>0?{_meta:{[Bt]:D}}:{}})()}};bn=[];let R,C,O;re({src:"reconnect",step:"attach-send",useAfterMessage:S,lastSeenMessageId:_t});try{let D=await y.request(x);if(re({src:"reconnect",step:"attach-resp",hasError:!!D.error}),D.error)throw new Error(D.error.message);O=GS(D.result),R=O.appliedPolicy,O.clientId!==void 0&&(Gn=O.clientId)}catch(D){C=D,re({src:"reconnect",step:"attach-fail",message:C.message})}let K=bn??[];if(bn=null,C)Gh(),I.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(S&&R!=="after_message")Gh(),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 K)bi(D)}finally{A=!1}}if(O){let D=QS({daemonTurnStartedAt:O.turnStartedAt,pendingTurns:U});D.pendingTurnsDelta!==0&&Pt(D.pendingTurnsDelta),D.banner==="busy"&&D.busySince!==void 0?(pe=D.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-D.busySince}),It===null&&(It=Ee())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:U>0?"busy":"ready",elapsedMs:U>0?0:void 0});re({src:"reconnect",step:"end"})},w.onClose(g=>{g&&n.red(`
|
|
264
264
|
connection lost: ${g.message}
|
|
265
|
-
`),
|
|
266
|
-
`),null)}for(;;){let a=await Wn(t,{includeNonInteractive:!0}),d=s.agentId??i.lastChosenAgent??e.defaultAgent,c=d?e.defaultModels?.[d]:void 0,l=[];try{l=await ri(t)}catch{}let
|
|
267
|
-
fork failed: ${
|
|
268
|
-
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:c,cwd:o,upstreamSessionId:""}}:{}}}}function mk(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function gk(n,e,t,s,r){if(t.agentId||await dm())return"ok";let i;try{i=await ri(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await xe(),a=s.lastChosenAgent??o.defaultAgent,d=await Za(n,i,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";if(t.agentId=d.agentId,s.lastChosenAgent=d.agentId,d.persist)try{await Di(d.agentId)}catch{}return"ok"}function
|
|
265
|
+
`),Xs(g?1:0)}),process.on("SIGINT",Qn),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&er(s.initialPrompt??"",s.initialAttachments??[]),await Vo}async function j_(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 gk(n,t,s,i)!=="ok"?null:mk(s,o,e);if(s.resume){let a=JS();if(a){let u=(await Wn(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 d=await Wn(t,{cwd:o,all:!0}),c=Jc(d,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o,resolved:c}:(n.yellow(`No sessions found for ${o}.
|
|
266
|
+
`),null)}for(;;){let a=await Wn(t,{includeNonInteractive:!0}),d=s.agentId??i.lastChosenAgent??e.defaultAgent,c=d?e.defaultModels?.[d]:void 0,l=[];try{l=await ri(t)}catch{}let u=await Sh(n,{cwd:o,sessions:a,config:e,target:t,prefs:r,...d?{composerAgentId:d}:{},...c?{composerModel:c}:{},...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 gk(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 v=mk(s,o,e);return w&&(v.installStatus=w),v}if(u.kind==="fork"){let w=await vk(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 wk(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 Xa(h.cwd)).ok){p();let b=await yi(n,h,{defaultCwd:st(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 v=u.agentId??h.agentId??"";return{sessionId:u.sessionId,agentId:v,cwd:b.path,resumeHint:{agentId:v,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 wk(n,e,t,s,r){for(;;){let i=await RS(n,t);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let c=s.agentId??t.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:t.cwd}}}let o=await bk(n,e,s.agentId??t.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await yi(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let d=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:a.path,resumeHint:{agentId:d,cwd:a.path,upstreamSessionId:""}}}}}async function bk(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let s;try{s=await ri(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 Za(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 vk(n,e,t,s){let r=s.find(u=>u.sessionId===t.sourceSessionId),i=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,o=t.sourceCwd,a=await bk(n,e,t.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let d=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let u=await yi(n,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let c=d??t.sourceAgentId??"",l;try{l=await Kc(e,t.sourceSessionId,{...i?{cwd:o}:{},...d?{agentId:d}:{}})}catch(u){return n.red(`
|
|
267
|
+
fork failed: ${u.message}
|
|
268
|
+
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:c,cwd:o,upstreamSessionId:""}}:{}}}}function mk(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function gk(n,e,t,s,r){if(t.agentId||await dm())return"ok";let i;try{i=await ri(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await xe(),a=s.lastChosenAgent??o.defaultAgent,d=await Za(n,i,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";if(t.agentId=d.agentId,s.lastChosenAgent=d.agentId,d.persist)try{await Di(d.agentId)}catch{}return"ok"}function q_(n,e){re({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Th,F_,L_,hk,D_,Sk=J(()=>{"use strict";Yr();Nt();Cp();et();Mp();Jr();ni();Ma();aa();Bv();ps();we();Vr();gn();yl();Ep();ac();Na();Dv();Hv();NS();wh();cl();gh();hh();Fp();Ap();HS();ph();Of();Hp();Il();Cl();jS();VS();Hl();yh();XS();ur();oi();ek();sk();qp();ik();lk();Th="dismiss";F_=12e4;L_=[["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"],["^S","show / hide sidebar (with an empty draft; amends otherwise)"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter \xB7 sidebar)"],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)"],["Double-click","open file under cursor / sidebar file row (tui.openFileCommand, else $VISUAL/$EDITOR)"],["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"]];hk=!1;D_=2});var kk={};lu(kk,{runTui:()=>yk});var Ik=J(()=>{"use strict";Sk()});import{readFileSync as W_}from"fs";import{fileURLToPath as z_}from"url";import{dirname as K_,resolve as J_}from"path";var Yh=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"]),Gk=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Qh(n){for(let e of Object.keys(n))if(!Yh.has(e)&&!Gk.has(e))return e}function uu(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 d=r.slice(2,i);t[d]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(Yh.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 Yk(n,e){let t=n[e];if(typeof t=="string")return t}function Fi(n,e){return n[e]===!0||n[e]==="true"}var Qk="HYDRA_ACP_";function Xk(n){return Qk+n.toUpperCase().replace(/-/g,"_")}function Rt(n,e){let t=Yk(n,e);return t!==void 0?t:process.env[Xk(e)]}et();Jr();async function Am(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=yu(t);return{target:await Im(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await xe();return{target:await Wt(s),sessionId:t,fromUrl:!1}}function Tu(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}Vr();we();et();Ms();import*as Tm from"fs/promises";async function Em(n){if(await Tm.mkdir(L.home(),{recursive:!0}),await Pd(),!await Bi()){let t=Li();await Ni(t),process.stdout.write(`Initialized ${L.authToken()}
|
|
269
269
|
Service token: ${t}
|
|
270
|
-
`);return}if(Fi(n,"rotate-token")){let t=Li();await Ni(t),process.stdout.write(`Rotated token in ${
|
|
270
|
+
`);return}if(Fi(n,"rotate-token")){let t=Li();await Ni(t),process.stdout.write(`Rotated token in ${L.authToken()}
|
|
271
271
|
New token: ${t}
|
|
272
|
-
`);return}process.stdout.write(`Service token already exists at ${
|
|
272
|
+
`);return}process.stdout.write(`Service token already exists at ${L.authToken()}.
|
|
273
273
|
`),process.stdout.write(`Pass --rotate-token to generate a new service token.
|
|
274
|
-
`)}we();Ui();et();
|
|
274
|
+
`)}we();Ui();et();Ms();import{setTimeout as fR}from"timers/promises";import Mw from"chalk";import*as xw from"fs";import*as ws from"fs/promises";import*as Aw from"net";import*as go from"path";import*as Cw from"tls";import YC from"fastify";import QC from"@fastify/websocket";var Pm="acp.v1";function Mm(n,e){return n.has(Pm)?Pm:!1}et();import kw from"pino";import XC from"pino-roll";we();import*as Lt from"fs/promises";import{createHash as NI}from"crypto";import{gzip as DI,gunzip as HI}from"zlib";import{promisify as _m}from"util";var $m=_m(DI),UI=_m(HI),Fm=/^[A-Za-z0-9_-]+$/,jI=/^[a-f0-9]{64}$/,Eu=!0;function Om(n){Eu=n}function Od(n,e){return Fm.test(n)?e===void 0||jI.test(e):!1}function Ld(n,e){return`${L.toolBlobFile(n,e)}.gz`}async function Pu(n,e){if(!Od(n))return null;let t=NI("sha256").update(e,"utf8").digest("hex"),s=Ld(n,t),r=L.toolBlobFile(n,t);for(let a of[s,r])try{return await Lt.access(a),t}catch{}await Lt.mkdir(L.toolsDir(n),{recursive:!0});let i=Eu?s:r,o=Eu?await $m(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Lt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function ua(n,e){if(!Od(n,e))return null;try{let t=await Lt.readFile(Ld(n,e));return(await UI(t)).toString("utf8")}catch{}try{return await Lt.readFile(L.toolBlobFile(n,e),"utf8")}catch{return null}}async function Lm(n,e){if(!Od(n,e))return null;try{return await Lt.readFile(Ld(n,e))}catch{}try{let t=await Lt.readFile(L.toolBlobFile(n,e));return await $m(t)}catch{return null}}async function Bm(n,e,t){if(!Od(n,e))return;let s=Ld(n,e);try{await Lt.access(s);return}catch{}await Lt.mkdir(L.toolsDir(n),{recursive:!0}),await Lt.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Nm(n){Fm.test(n)&&await Lt.rm(L.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}we();et();qr();Wi();import*as Gm from"fs/promises";import*as Nd from"path";import{z as de}from"zod";we();Wi();import*as pn from"fs/promises";import*as us from"path";import{spawn as GI}from"child_process";var Lu=n=>{process.stderr.write(n+`
|
|
275
275
|
`)};function Bu(n){Lu=n??(e=>process.stderr.write(e+`
|
|
276
|
-
`))}async function Wm(n){let e=Pn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=
|
|
277
|
-
stderr: ${l}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<QI)return await new Promise(r=>setTimeout(r,XI*(e+1))),zm(n,e+1);throw t}}function ex(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 tx(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Km(n,e){let t=us.join(n,"node_modules",e,"package.json");try{let s=await pn.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 qm(n){let e=us.join(n.installDir,"node_modules",".bin"),t=us.join(e,n.hint);if(await Gr(t))return{binName:n.hint,binPath:t};let s=await Km(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=us.join(e,i);if(await Gr(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=us.join(e,i);if(await Gr(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=us.join(e,n.basename);if(await Gr(r))return{binName:n.basename,binPath:r}}}async function Gr(n){try{return await pn.access(n),!0}catch{return!1}}var nx=de.object({package:de.string(),bin:de.string().optional(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),zi=de.object({archive:de.string().url().optional(),cmd:de.string().optional(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),sx=de.object({"darwin-aarch64":zi.optional(),"darwin-x86_64":zi.optional(),"linux-aarch64":zi.optional(),"linux-x86_64":zi.optional(),"windows-x86_64":zi.optional(),"windows-aarch64":zi.optional()}),rx=de.object({package:de.string(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),ix=de.object({command:de.string(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),ox=de.object({command:de.string().optional(),url:de.string().optional(),description:de.string().optional()}),ax=de.object({npx:nx.optional(),binary:sx.optional(),uvx:rx.optional(),exec:ix.optional()}),dx=de.object({id:de.string(),name:de.string(),version:de.string().optional(),description:de.string().optional(),authors:de.array(de.string()).optional(),license:de.string().optional(),icon:de.string().optional(),repository:de.string().optional(),website:de.string().optional(),distribution:ax,onboarding:ox.optional(),requiredEnv:de.array(de.string().min(1)).optional()}),Jm=de.object({version:de.string(),agents:de.array(dx),extensions:de.array(de.unknown()).optional()}),Bd=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=>Nu(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(d=>d.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:st(t.command??e),args:t.args?.map(st),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:cx(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=Jm.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 Tn(
|
|
278
|
-
`);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let
|
|
276
|
+
`))}async function Wm(n){let e=Pn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentNpmInstallDir(n.agentId,e,n.version),s=ex(n.packageSpec),r=tx(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=us.join(t,"node_modules",".bin",n.bin);if(await Gr(o))return o;if(await Gr(t)){let u=await qm(i);if(u)return u.binPath}await YI({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await qm(i);if(a)return a.binPath;let d=await Km(t,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],l=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${l}`)}async function YI(n){await pn.mkdir(us.dirname(n.installDir),{recursive:!0});let e=await pn.mkdtemp(`${n.installDir}.partial-`);try{Lu(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),Ou(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ZI({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await pn.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Gr(n.installDir)){await pn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ou(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Lu(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Ou(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await pn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Ou(n,e){if(n)try{n(e)}catch{}}var QI=5,XI=25;function ZI(n){return zm(n,0)}async function zm(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=GI("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,d)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${c})
|
|
277
|
+
stderr: ${l}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<QI)return await new Promise(r=>setTimeout(r,XI*(e+1))),zm(n,e+1);throw t}}function ex(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 tx(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Km(n,e){let t=us.join(n,"node_modules",e,"package.json");try{let s=await pn.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 qm(n){let e=us.join(n.installDir,"node_modules",".bin"),t=us.join(e,n.hint);if(await Gr(t))return{binName:n.hint,binPath:t};let s=await Km(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=us.join(e,i);if(await Gr(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=us.join(e,i);if(await Gr(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=us.join(e,n.basename);if(await Gr(r))return{binName:n.basename,binPath:r}}}async function Gr(n){try{return await pn.access(n),!0}catch{return!1}}var nx=de.object({package:de.string(),bin:de.string().optional(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),zi=de.object({archive:de.string().url().optional(),cmd:de.string().optional(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),sx=de.object({"darwin-aarch64":zi.optional(),"darwin-x86_64":zi.optional(),"linux-aarch64":zi.optional(),"linux-x86_64":zi.optional(),"windows-x86_64":zi.optional(),"windows-aarch64":zi.optional()}),rx=de.object({package:de.string(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),ix=de.object({command:de.string(),args:de.array(de.string()).optional(),env:de.record(de.string()).optional()}),ox=de.object({command:de.string().optional(),url:de.string().optional(),description:de.string().optional()}),ax=de.object({npx:nx.optional(),binary:sx.optional(),uvx:rx.optional(),exec:ix.optional()}),dx=de.object({id:de.string(),name:de.string(),version:de.string().optional(),description:de.string().optional(),authors:de.array(de.string()).optional(),license:de.string().optional(),icon:de.string().optional(),repository:de.string().optional(),website:de.string().optional(),distribution:ax,onboarding:ox.optional(),requiredEnv:de.array(de.string().min(1)).optional()}),Jm=de.object({version:de.string(),agents:de.array(dx),extensions:de.array(de.unknown()).optional()}),Bd=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=>Nu(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(d=>d.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:st(t.command??e),args:t.args?.map(st),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:cx(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=Jm.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 Tn(L.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Jm.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await fn(L.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function cx(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 Nu(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 Ki(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 Du(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function Du(n){let e=Pn();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=$u(n.distribution.binary,e);if(s?.cmd){let r=Nd.resolve(L.agentInstallDir(n.id,e,t),s.cmd);if(await Vm(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??Nu(n)??s.package,i=L.agentNpmInstallDir(n.id,e,t),o=Nd.join(i,"node_modules",".bin",r);if(await Vm(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Vm(n){try{return await Gm.access(n),!0}catch{return!1}}async function Mn(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??Nu(n)??r.package,a=t.onInstallProgress;return{command:await Wm({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=$u(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${Pn()??"this platform"}.`);let i=t.onInstallProgress,o=await jm({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as hx}from"child_process";import*as zd from"fs";import*as ug from"path";Nt();function Wd(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
|
|
278
|
+
`);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}d=t.indexOf(`
|
|
279
279
|
`)}}),n.on("end",()=>o()),n.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let d=JSON.stringify(a)+`
|
|
280
|
-
`;await new Promise((c,l)=>{e.write(d,
|
|
280
|
+
`;await new Promise((c,l)=>{e.write(d,u=>{if(u){l(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Yr();we();var mx=4096,or=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??mx,this.killEscalationMs=e.killEscalationMs??gx,this.logger=e.logger,this.fileLog=yx(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()} ---
|
|
281
281
|
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Wd(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()} ---
|
|
282
282
|
`),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()} ---
|
|
283
283
|
`),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}
|
|
284
284
|
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=hx(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()} ---
|
|
285
285
|
`),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()} ---
|
|
286
|
-
`),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)})}},gx=2e3;function yx(n){try{let e=
|
|
286
|
+
`),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)})}},gx=2e3;function yx(n){try{let e=L.agentLogFile(n);zd.mkdirSync(ug.dirname(e),{recursive:!0});let t=zd.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}pa();import*as ei from"fs/promises";import*as yy from"os";import*as Ra from"path";import{customAlphabet as NA}from"nanoid";zu();ps();ff();we();qr();import*as _s from"fs/promises";import{z as hs}from"zod";var fA=hs.object({version:hs.literal(1),agentId:hs.string(),upstreamSessionId:hs.string(),deletedAt:hs.string(),upstreamUpdatedAt:hs.string().optional(),cwd:hs.string().optional(),title:hs.string().optional(),reason:hs.enum(["user","expired"]).optional(),interactive:hs.boolean().optional()}),tc=class{async add(e){let t={version:1,...e};await fn(L.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await _s.access(L.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=L.tombstoneFile(e,t),r=await Tn(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return fA.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await _s.unlink(L.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await _s.rmdir(L.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(L.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(L.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 Wg(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as sy from"fs/promises";Nt();gn();Zd();Yd();var mA=12e4;async function Kg(n,e,t){let s=n.timeoutMs??mA,r,i,o=!1;try{let a=(async()=>{r=or.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let d=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:be}}),c=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),l=c.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=yA(c);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=gA(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((d,c)=>{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`),d(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||d(l)},l=>{i&&clearTimeout(i),o||c(l)})})}catch(a){let d=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${d}`),n.onFailure?.(`agent ${n.agentId} failed: ${d}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function sc(n){let e=Zi(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}
|
|
287
287
|
|
|
288
288
|
${e}
|
|
289
289
|
|
|
@@ -295,41 +295,41 @@ ${e}
|
|
|
295
295
|
|
|
296
296
|
${rf}`:`${t}
|
|
297
297
|
|
|
298
|
-
${rf}`;return Kg(n,s,jg)}function gA(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 yA(n){let e=new Set;zg(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&zg(e,t.availableModels),e}function zg(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)}}}mf();we();var wA=2,rc=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??wA}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 d=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await Mn(c,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,u=s==="compaction"?this.opts.compactionModel??(f?i.currentModel:void 0):this.opts.synopsisModel,p=O.sessionDir(e);if(await sy.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${o.length} model=${JSON.stringify(u??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,w,b=0,v,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 Jg({agentId:d,cwd:p,plan:l,history:H,modelId:u,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=>{v=B}});if(_){let B=ey(_.synopsis,H);B&&ty(B)&&(await this.opts.persistSynopsis(e,B,H.length),w=B,b=H.length,v=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=${ny(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}: ${v??"no reason captured"}`);let H=v??(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 sc({agentId:d,cwd:p,plan:l,history:o,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=ey(h.synopsis,o);m&&ty(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=${ny(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 ey(n,e){let t=Qg(e),s=Yg(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 ty(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 ny(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(",")}]`}we();import*as Oe from"fs/promises";import{createReadStream as IA}from"fs";import{createGunzip as xA,gzip as AA,gunzip as CA}from"zlib";import{createInterface as RA}from"readline";import{promisify as cy}from"util";function ry(n){return n==="summary"?"summary":"inline"}var gf=256;function iy(n,e){return e!=="summary"?n:n.map(bA)}function bA(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(oy));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=yf(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function vA(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function oy(n){if(vA(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=yf(e.text)),typeof e.content=="string"?t.content=yf(e.content):e.content&&typeof e.content=="object"&&(t.content=oy(e.content)),t}function yf(n){if(typeof n=="string"&&n.length>gf){let e=n.length-gf;return`${n.slice(0,gf)}\u2026[+${e} chars omitted from summary export]`}return n}var SA=2048;function ay(n){let e=new Set,t=s=>{if(dy(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 dy(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function kA(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 vf(n,e){if(!kA(n))return n;let t=n.params,s=t.update,r=await wf(s,e);return{...n,params:{...t,update:r}}}async function wf(n,e){if(typeof n=="string"){if(n.length<=SA)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 wf(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await wf(r,e);return t}return n}async function Sf(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await bf(t,e);return s===t?n:{...n,params:s}}async function bf(n,e){if(dy(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await bf(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 bf(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var TA=cy(AA),EA=cy(CA),PA=/^history\.jsonl\.(\d+)(\.gz)?$/,jn=/^[A-Za-z0-9_-]+$/,MA=1e3,_A=1e7,$A=10,ic=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??MA,this.archiveMaxBytes=e.archiveMaxBytes??_A,this.archiveTiers=e.archiveTiers??$A}async append(e,t){if(jn.test(e))return this.enqueue(e,async()=>{await Oe.mkdir(O.sessionDir(e),{recursive:!0});let s=await vf(t,i=>Pu(e,i)),r=JSON.stringify(s)+`
|
|
299
|
-
`;await Oe.appendFile(
|
|
298
|
+
${rf}`;return Kg(n,s,jg)}function gA(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 yA(n){let e=new Set;zg(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&zg(e,t.availableModels),e}function zg(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)}}}mf();we();var wA=2,rc=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??wA}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 d=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await Mn(c,[],{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=L.sessionDir(e);if(await sy.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} 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,v,k=Date.now(),A={targetAgentId:r},E=H=>this.opts.onCompactionStateChange?.(e,H,A)??Promise.resolve(),_=H=>{this.opts.broadcastHydraCompaction?.(e,H,A)};await E({status:"requested",requestedAt:k}),_({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 P=await Jg({agentId:d,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=>{v=B}});if(P){let B=ey(P.synopsis,H);B&&ty(B)&&(await this.opts.persistSynopsis(e,B,H.length),w=B,b=H.length,v=void 0,await E({status:"running",requestedAt:k,iter:m}),_({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=${ny(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}: ${v??"no reason captured"}`);let H=v??(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}),_({sessionUpdate:"hydra_compaction",phase:"failed",error:H})}}catch(H){let P=H instanceof Error?H.message:String(H);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${P}`),await E({status:"failed",requestedAt:k,iter:m,lastError:P}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:P},{targetAgentId:r})}}else{let h=await sc({agentId:d,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=ey(h.synopsis,o);m&&ty(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=${ny(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 ey(n,e){let t=Qg(e),s=Yg(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 ty(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 ny(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(",")}]`}we();import*as Oe from"fs/promises";import{createReadStream as IA}from"fs";import{createGunzip as xA,gzip as AA,gunzip as CA}from"zlib";import{createInterface as RA}from"readline";import{promisify as cy}from"util";function ry(n){return n==="summary"?"summary":"inline"}var gf=256;function iy(n,e){return e!=="summary"?n:n.map(bA)}function bA(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(oy));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=yf(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function vA(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function oy(n){if(vA(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=yf(e.text)),typeof e.content=="string"?t.content=yf(e.content):e.content&&typeof e.content=="object"&&(t.content=oy(e.content)),t}function yf(n){if(typeof n=="string"&&n.length>gf){let e=n.length-gf;return`${n.slice(0,gf)}\u2026[+${e} chars omitted from summary export]`}return n}var SA=2048;function ay(n){let e=new Set,t=s=>{if(dy(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 dy(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function kA(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 vf(n,e){if(!kA(n))return n;let t=n.params,s=t.update,r=await wf(s,e);return{...n,params:{...t,update:r}}}async function wf(n,e){if(typeof n=="string"){if(n.length<=SA)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 wf(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await wf(r,e);return t}return n}async function Sf(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await bf(t,e);return s===t?n:{...n,params:s}}async function bf(n,e){if(dy(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await bf(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 bf(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var TA=cy(AA),EA=cy(CA),PA=/^history\.jsonl\.(\d+)(\.gz)?$/,jn=/^[A-Za-z0-9_-]+$/,MA=1e3,_A=1e7,$A=10,ic=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??MA,this.archiveMaxBytes=e.archiveMaxBytes??_A,this.archiveTiers=e.archiveTiers??$A}async append(e,t){if(jn.test(e))return this.enqueue(e,async()=>{await Oe.mkdir(L.sessionDir(e),{recursive:!0});let s=await vf(t,i=>Pu(e,i)),r=JSON.stringify(s)+`
|
|
299
|
+
`;await Oe.appendFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(jn.test(e))return this.enqueue(e,async()=>{await Oe.mkdir(L.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await vf(i,o=>Pu(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
|
|
300
300
|
`)+`
|
|
301
|
-
`;await Oe.writeFile(
|
|
302
|
-
`).filter(a=>a.length>0);if(r.length<=t)return;let i=r.slice(0,r.length-t),o=r.slice(-t);this.archiveMaxBytes>0&&i.length>0&&await this.spillToArchive(e,i),await Oe.writeFile(
|
|
301
|
+
`;await Oe.writeFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(jn.test(e))return this.enqueue(e,async()=>{let s;try{s=await Oe.readFile(L.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let r=s.split(`
|
|
302
|
+
`).filter(a=>a.length>0);if(r.length<=t)return;let i=r.slice(0,r.length-t),o=r.slice(-t);this.archiveMaxBytes>0&&i.length>0&&await this.spillToArchive(e,i),await Oe.writeFile(L.historyFile(e),o.join(`
|
|
303
303
|
`)+`
|
|
304
304
|
`,{encoding:"utf8",mode:384})})}async spillToArchive(e,t){let s=t.join(`
|
|
305
305
|
`)+`
|
|
306
|
-
`,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=
|
|
307
|
-
`)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let c=d;typeof c.method=="string"&&typeof c.recordedAt=="number"&&r.push({method:c.method,params:c.params,recordedAt:c.recordedAt})}}return r}async*streamFile(e){let t;try{t=IA(e)}catch(o){if(o.code==="ENOENT")return;throw o}if(await new Promise(o=>{let a=!1,d=c=>{a||(a=!0,o(c))};t.once("error",c=>{c.code==="ENOENT"?d(!0):(t.destroy(),d(!1))}),t.once("readable",()=>d(!1)),t.once("end",()=>d(!1))}))return;let r=e.endsWith(".gz")?t.pipe(xA()):t,i=RA({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 d=a;typeof d.method=="string"&&typeof d.recordedAt=="number"&&(yield{method:d.method,params:d.params,recordedAt:d.recordedAt})}}finally{i.close(),t.destroy()}}async getArchiveLineCounts(e){if(!jn.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(c=>c.index===i&&c.path===o);if(a){r.push(a);continue}let d=0;for await(let c of this.streamFile(o))d+=1;r.push({index:i,path:o,lineCount:d})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,s){return Sf(t,async r=>{let i=s.get(r);if(i!==void 0)return i;let o=await ua(e,r);return s.set(r,o),o})}async*iterRecallNewestFirst(e){if(!jn.test(e))return;let t=this.writeQueues.get(e);t&&await t;let s=await this.getArchiveLineCounts(e),r=0;for(let c of s)r+=c.lineCount;let i=new Map,o=[];for await(let c of this.streamFile(
|
|
308
|
-
`)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=t.maxEntries??this.maxEntries,d=o.length>a?o.slice(-a):o;if(!s)return d;let c=new Map,l=async u=>{let p=c.get(u);if(p!==void 0)return p;let h=await ua(e,u);return c.set(u,h),h},f=[];for(let u of d)f.push(await Sf(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(jn.test(e))return this.enqueue(e,async()=>{try{await Oe.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 Nm(e);try{await Oe.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}};we();et();ac();Zr();Gd();Nt();Nt();gn();Zu();var fy=900*1e3,DA="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",dc=NA(DA,16),cc=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>ir.spawn(a)),this.store=s??new ec,this.tombstones=r.tombstones??new tc,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new ic({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 rc({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,d)=>{let c=this.get(a);if(c){await c.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,c)=>this.persistSynopsis(a,d,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,c)=>{if(c.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,c)=>{this.emitSwapPhase(a,c.targetAgentId,d)},onSynthesisArtifact:async(a,d,c,l)=>{await this.dispatchSynthesisSwap(a,d,c,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 d=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,d)}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 d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.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 Ki(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_${dc()}`,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 no({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=W.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=W.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await Mn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}});o=m.agentCapabilities,i.authMethods=Aa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),dr(m,i)}let a;try{let m=py(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===W.AuthRequired)throw await i.kill().catch(()=>{}),dr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
309
|
-
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Tf(a??{}),c=e.agentModes??Af(Rf(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let l=await Vi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=xf(a??{}),u=Af(Cf(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Gi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new no({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:c,agentModels:u,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),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 Vi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Gi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new no({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:c.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(c,l)=>this.bootstrapAgentLoad(c,{...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(d.sessionId),scheduleCompaction:c=>this.scheduleCompaction(d.sessionId,c),resolveAgentId:async c=>(await this.registry.getAgent(c))?.id,getCompactionState:()=>this.getCompactionState(d.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(d.sessionId),uncompactHook:()=>this.performUncompact(d.sessionId),forkHook:c=>this.forkSession(d.sessionId,c??{}),onCompactionSwapHook:c=>{this.mutateRecord(d.sessionId,{rollbackBreadcrumb:c}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(d.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(d),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${d.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?d.seedFromFork(e.synopsis).catch(()=>{}):d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await ei.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:st(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=W.AgentNotInstalled,p}let s=await Mn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:yy.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}})}catch(p){throw await r.kill().catch(()=>{}),dr(p,r)}if(r.authMethods=Aa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=O.sessionsDir(),f=[],u=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(d.has(h)){u+=1;continue}if(HA(p.cwd,l)){u+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Wg(m,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(h);let y=`${zt}${dc()}`,w=new Date().toISOString(),b=p.updatedAt??w,v={sessionId:y,lineageId:ba(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(v.title=p.title);let k=uf(v);await this.store.write(k),f.push({version:1,...k})}return{synced:f,skipped:u}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.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=W.AgentNotInstalled,i}let s=await Mn(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:Ji,clientInfo:{name:"hydra",version:be}}),o=i.agentCapabilities;r.authMethods=Aa(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=xf(a),l=Cf(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let h=Xi(f,l),m=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,d,f,m)&&(c=f);else if(h.kind==="resolved")(h.modelId===c||await this.applySeedModel(r,d,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(c=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(c)}`);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(c)}`)}}let u=Rf(a),p=Tf(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),dr(my(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=W.AgentNotInstalled,o}let r=await Mn(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:Ji,clientInfo:{name:"hydra",version:be}}),a=o.agentCapabilities;i.authMethods=Aa(o.authMethods);let d=py(t.agentId,void 0),c=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...d&&{_meta:d}}),l=xf(c),f=Af(Cf(c)),u=Rf(c),p=Tf(c);return{agent:i,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),dr(my(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 d=new Error(`agent ${e} not found in registry`);throw d.code=W.AgentNotInstalled,d}let i=await Mn(r,[],{npmRegistry:this.npmRegistry}),o=t??st(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}});a.authMethods=Aa(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),dr(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=W.AgentNotInstalled,s}return Mn(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=oo({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:wy(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=UA(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 ua(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:jA(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,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=eo(r.update.prompt),o=nf(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(zt))return;let t=zt+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=W.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,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Ca(t.sessionId),d=oo({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await Ca(s.sessionId),i=oo(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=>Ca(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=oo({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let h=u.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:f.attachedCount,status:"warm",agentPid:f.agentPid,busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let d=(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)),c=await Promise.all(d.map(l=>Ca(l.sessionId)));for(let l=0;l<d.length;l+=1){let f=d[l],u=c[l],p=oo(f,u.hasContent);if(!r(p))continue;let h=u.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((l,f)=>l.updatedAt<f.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=ba(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),r=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await gy(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of ay(o)){let l=await Lm(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=W.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${zt}${dc()}`;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 v=new Error(`source session not found: ${e}`);throw v.code=W.SessionNotFound,v}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=W.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,d,c=t.mode??"synthesis",l,f,u,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let v=Xd(o,t.forkAt);if(v<0){let k=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw k.code=W.InvalidParams,k}d=t.forkAt,a=o.slice(0,v+1)}else{let v=WA(o);v?(d=v.messageId,a=o.slice(0,v.index+1)):(d="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let k=Xd(o,t.forkAt);if(k<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=W.InvalidParams,A}d=t.forkAt,a=o.slice(0,k+1)}else d="",a=o;let v=await this.registry.getAgent(r);if(!v){let k=new Error(`agent ${r} not found in registry`);throw k.code=W.AgentNotInstalled,k}u=v,f=s.currentModel,l="running"}let h=await gy(e),m=c==="synthesis",y={...s,lineageId:ba(),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=xa({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:be,machine:or()}),b=`${zt}${dc()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let v=await Mn(u,[],{npmRegistry:this.npmRegistry}),k=await sc({agentId:r,cwd:t.cwd??O.sessionDir(e),plan:v,history:a,modelId:f,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(b,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(v){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${v.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:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Bm(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await ei.utimes(O.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Xr(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 Ca(e),i=oo(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},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let c={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(c)})}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 Tg(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<fy),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${fy/1e3}s)`),await ga(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 ga(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function HA(n,e){if(typeof n!="string"||n.length===0)return!1;let t=Ra.resolve(n),s=Ra.resolve(e);return t===s||t.startsWith(s+Ra.sep)}function UA(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 f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return uf({sessionId:n.sessionId,lineageId:e?.lineageId??ba(),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:wy(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function wy(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function jA(n){return n?{...n}:void 0}function py(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function lc(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=qA(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function xf(n){return lc(n,{nestedKey:"models",configId:"model",fromObject:e=>ms(e.currentModelId)??ms(e.currentModel)??ms(e.modelId)??ms(e.model),fromConfig:e=>ms(e.currentValue)})}function dr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==W.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=W.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function hy(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function my(n,e,t,s){if(n&&typeof n=="object"&&n.code===W.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 ${hy(s.cwd)} && ${[s.command,...s.args].map(hy).join(" ")})`:"";if(!o&&!a)return n;let d=[i?r:`agent ${t} failed to start: ${r}`];o&&d.push(`stderr: ${o}`),a&&d.push(a);let c=new Error(d.join(`
|
|
310
|
-
`));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(c.code=l.code),l.data!==void 0&&(c.data=l.data)}return c}function Aa(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function ms(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function qA(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 Af(n){return n.length>0?n:void 0}function Cf(n){return lc(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=to(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=to(e.options);return t.length>0?t:void 0}})??[]}function Rf(n){return lc(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=ya(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=ya(e.options);return t.length>0?t:void 0}})??[]}function Tf(n){return lc(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ms(e.currentModeId)??ms(e.currentMode)??ms(e.modeId)??ms(e.mode),fromConfig:e=>ms(e.currentValue)})}function WA(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 gy(n){try{let e=await ei.readFile(
|
|
311
|
-
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function Ca(n){try{let e=await ei.stat(
|
|
312
|
-
`);let d=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=d,e.version=void 0;let c={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[l,...
|
|
313
|
-
`),a.end();return}let
|
|
306
|
+
`,r=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,r);let i=L.historyArchiveFile(e,r);await Oe.mkdir(L.sessionDir(e),{recursive:!0}),await Oe.appendFile(i,s,{encoding:"utf8",mode:384});let o=0;try{o=(await Oe.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=L.historyArchiveFile(e,t),r;try{r=await Oe.readFile(s)}catch(o){if(o.code==="ENOENT")return;throw o}let i=await TA(r);await Oe.writeFile(s+".gz",i,{mode:384});try{await Oe.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=L.historyArchiveFile(e,r),a=o+".gz",d=!1;try{await Oe.access(a),d=!0}catch{d=!1}if(d)i=r+1;else try{(await Oe.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=L.historyArchiveFile(e,t);for(let r of[s,s+".gz"])try{await Oe.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await Oe.readdir(L.sessionDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=new Set;for(let r of t){let i=PA.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(!jn.test(e))return[];let t=await this.listArchiveIndices(e),s=[];for(let r of t){let i=L.historyArchiveFile(e,r),o=i+".gz",a=i;try{await Oe.access(o),a=o}catch{a=i}s.push({index:r,path:a})}return s}async loadArchives(e){if(!jn.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 Oe.readFile(i);o=(await EA(a)).toString("utf8")}else o=await Oe.readFile(i,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of o.split(`
|
|
307
|
+
`)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let c=d;typeof c.method=="string"&&typeof c.recordedAt=="number"&&r.push({method:c.method,params:c.params,recordedAt:c.recordedAt})}}return r}async*streamFile(e){let t;try{t=IA(e)}catch(o){if(o.code==="ENOENT")return;throw o}if(await new Promise(o=>{let a=!1,d=c=>{a||(a=!0,o(c))};t.once("error",c=>{c.code==="ENOENT"?d(!0):(t.destroy(),d(!1))}),t.once("readable",()=>d(!1)),t.once("end",()=>d(!1))}))return;let r=e.endsWith(".gz")?t.pipe(xA()):t,i=RA({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 d=a;typeof d.method=="string"&&typeof d.recordedAt=="number"&&(yield{method:d.method,params:d.params,recordedAt:d.recordedAt})}}finally{i.close(),t.destroy()}}async getArchiveLineCounts(e){if(!jn.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(c=>c.index===i&&c.path===o);if(a){r.push(a);continue}let d=0;for await(let c of this.streamFile(o))d+=1;r.push({index:i,path:o,lineCount:d})}return this.archiveLineCounts.set(e,r),r}async hydrateEntry(e,t,s){return Sf(t,async r=>{let i=s.get(r);if(i!==void 0)return i;let o=await ua(e,r);return s.set(r,o),o})}async*iterRecallNewestFirst(e){if(!jn.test(e))return;let t=this.writeQueues.get(e);t&&await t;let s=await this.getArchiveLineCounts(e),r=0;for(let c of s)r+=c.lineCount;let i=new Map,o=[];for await(let c of this.streamFile(L.historyFile(e)))o.push(c);for(let c=o.length-1;c>=0;c--){let l=await this.hydrateEntry(e,o[c],i);yield{entryId:r+c,entry:l}}let a=new Array(s.length),d=0;for(let c=0;c<s.length;c++)a[c]=d,d+=s[c].lineCount;for(let c=s.length-1;c>=0;c--){let l=s[c],u=[];for await(let p of this.streamFile(l.path))u.push(p);let f=a[c];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(!jn.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=[],d=new Map,c=0;for(let l of i){let u=c,f=c+l.lineCount;if(c=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,d);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(L.historyFile(e))){if(f>u)break;if(f>=l){let h=await this.hydrateEntry(e,p,d);a.push({entryId:o+f,entry:h})}f+=1}}return a}async getRecallTotalCount(e){if(!jn.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(L.historyFile(e)))r+=1;return s+r}async load(e,t={}){if(!jn.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Oe.readFile(L.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
|
|
308
|
+
`)){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,d=o.length>a?o.slice(-a):o;if(!s)return d;let c=new Map,l=async f=>{let p=c.get(f);if(p!==void 0)return p;let h=await ua(e,f);return c.set(f,h),h},u=[];for(let f of d)u.push(await Sf(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(jn.test(e))return this.enqueue(e,async()=>{try{await Oe.unlink(L.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 Nm(e);try{await Oe.rmdir(L.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}};we();et();ac();Zr();Gd();Nt();Nt();gn();Zu();var fy=900*1e3,DA="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",dc=NA(DA,16),cc=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>or.spawn(a)),this.store=s??new ec,this.tombstones=r.tombstones??new tc,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new ic({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 rc({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,d)=>{let c=this.get(a);if(c){await c.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,c)=>this.persistSynopsis(a,d,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,c)=>{if(c.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,c)=>{this.emitSwapPhase(a,c.targetAgentId,d)},onSynthesisArtifact:async(a,d,c,l)=>{await this.dispatchSynthesisSwap(a,d,c,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 d=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,d)}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 d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.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 Ki(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_${dc()}`,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 no({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=W.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=W.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await Mn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}});o=m.agentCapabilities,i.authMethods=Aa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),cr(m,i)}let a;try{let m=py(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===W.AuthRequired)throw await i.kill().catch(()=>{}),cr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
309
|
+
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Tf(a??{}),c=e.agentModes??Af(Rf(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let l=await Vi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=xf(a??{}),f=Af(Cf(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 Gi({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 no({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:c,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 Vi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Gi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new no({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:c.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(c,l)=>this.bootstrapAgentLoad(c,{...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(d.sessionId),scheduleCompaction:c=>this.scheduleCompaction(d.sessionId,c),resolveAgentId:async c=>(await this.registry.getAgent(c))?.id,getCompactionState:()=>this.getCompactionState(d.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(d.sessionId),uncompactHook:()=>this.performUncompact(d.sessionId),forkHook:c=>this.forkSession(d.sessionId,c??{}),onCompactionSwapHook:c=>{this.mutateRecord(d.sessionId,{rollbackBreadcrumb:c}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(d.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(d),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${d.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?d.seedFromFork(e.synopsis).catch(()=>{}):d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await ei.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:st(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=W.AgentNotInstalled,p}let s=await Mn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:yy.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}})}catch(p){throw await r.kill().catch(()=>{}),cr(p,r)}if(r.authMethods=Aa(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=L.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(d.has(h)){f+=1;continue}if(HA(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Wg(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>"})`)}d.add(h);let y=`${Kt}${dc()}`,w=new Date().toISOString(),b=p.updatedAt??w,v={sessionId:y,lineageId:ba(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(v.title=p.title);let k=uf(v);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),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.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=W.AgentNotInstalled,i}let s=await Mn(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:Ji,clientInfo:{name:"hydra",version:be}}),o=i.agentCapabilities;r.authMethods=Aa(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=xf(a),l=Cf(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let h=Xi(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,d,u,m)&&(c=u);else if(h.kind==="resolved")(h.modelId===c||await this.applySeedModel(r,d,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(c=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(c)}`);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(c)}`)}}let f=Rf(a),p=Tf(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),cr(my(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=W.AgentNotInstalled,o}let r=await Mn(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:Ji,clientInfo:{name:"hydra",version:be}}),a=o.agentCapabilities;i.authMethods=Aa(o.authMethods);let d=py(t.agentId,void 0),c=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...d&&{_meta:d}}),l=xf(c),u=Af(Cf(c)),f=Rf(c),p=Tf(c);return{agent:i,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),cr(my(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 d=new Error(`agent ${e} not found in registry`);throw d.code=W.AgentNotInstalled,d}let i=await Mn(r,[],{npmRegistry:this.npmRegistry}),o=t??st(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ji,clientInfo:{name:"hydra",version:be}});a.authMethods=Aa(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),cr(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=W.AgentNotInstalled,s}return Mn(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=oo({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:wy(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=UA(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 ua(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:jA(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,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=eo(r.update.prompt),o=nf(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(Kt))return;let t=Kt+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=W.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,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Ca(t.sessionId),d=oo({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await Ca(s.sessionId),i=oo(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=>Ca(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=oo({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",agentPid:u.agentPid,busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let d=(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)),c=await Promise.all(d.map(l=>Ca(l.sessionId)));for(let l=0;l<d.length;l+=1){let u=d[l],f=c[l],p=oo(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 c=ba(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await gy(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of ay(o)){let l=await Lm(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=W.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Kt}${dc()}`;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 v=new Error(`source session not found: ${e}`);throw v.code=W.SessionNotFound,v}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=W.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,d,c=t.mode??"synthesis",l,u,f,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let v=Xd(o,t.forkAt);if(v<0){let k=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw k.code=W.InvalidParams,k}d=t.forkAt,a=o.slice(0,v+1)}else{let v=WA(o);v?(d=v.messageId,a=o.slice(0,v.index+1)):(d="",a=o.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let k=Xd(o,t.forkAt);if(k<0){let A=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw A.code=W.InvalidParams,A}d=t.forkAt,a=o.slice(0,k+1)}else d="",a=o;let v=await this.registry.getAgent(r);if(!v){let k=new Error(`agent ${r} not found in registry`);throw k.code=W.AgentNotInstalled,k}f=v,u=s.currentModel,l="running"}let h=await gy(e),m=c==="synthesis",y={...s,lineageId:ba(),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=xa({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:be,machine:ar()}),b=`${Kt}${dc()}`;return await this.writeImportedRecord({sessionId:b,bundle:w,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let v=await Mn(f,[],{npmRegistry:this.npmRegistry}),k=await sc({agentId:r,cwd:t.cwd??L.sessionDir(e),plan:v,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(v){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${v.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:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Bm(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await ei.utimes(L.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Xr(L.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 Ca(e),i=oo(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},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let c={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(c)})}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 Tg(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<fy),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${fy/1e3}s)`),await ga(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 ga(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function HA(n,e){if(typeof n!="string"||n.length===0)return!1;let t=Ra.resolve(n),s=Ra.resolve(e);return t===s||t.startsWith(s+Ra.sep)}function UA(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(),c=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return uf({sessionId:n.sessionId,lineageId:e?.lineageId??ba(),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:wy(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function wy(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function jA(n){return n?{...n}:void 0}function py(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function lc(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=qA(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function xf(n){return lc(n,{nestedKey:"models",configId:"model",fromObject:e=>ms(e.currentModelId)??ms(e.currentModel)??ms(e.modelId)??ms(e.model),fromConfig:e=>ms(e.currentValue)})}function cr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==W.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=W.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function hy(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function my(n,e,t,s){if(n&&typeof n=="object"&&n.code===W.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 ${hy(s.cwd)} && ${[s.command,...s.args].map(hy).join(" ")})`:"";if(!o&&!a)return n;let d=[i?r:`agent ${t} failed to start: ${r}`];o&&d.push(`stderr: ${o}`),a&&d.push(a);let c=new Error(d.join(`
|
|
310
|
+
`));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(c.code=l.code),l.data!==void 0&&(c.data=l.data)}return c}function Aa(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function ms(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function qA(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 Af(n){return n.length>0?n:void 0}function Cf(n){return lc(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=to(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=to(e.options);return t.length>0?t:void 0}})??[]}function Rf(n){return lc(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=ya(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=ya(e.options);return t.length>0?t:void 0}})??[]}function Tf(n){return lc(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ms(e.currentModeId)??ms(e.currentMode)??ms(e.modeId)??ms(e.mode),fromConfig:e=>ms(e.currentValue)})}function WA(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 gy(n){try{let e=await ei.readFile(L.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
|
|
311
|
+
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function Ca(n){try{let e=await ei.stat(L.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function oo(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Qr?!1:e?!0:void 0}import{spawn as zA}from"child_process";import*as fc from"fs";import*as $s from"fs/promises";import*as pc from"path";import KA from"pino-roll";var uc=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_}};et();var JA=1e3,VA=6e4,Ef=3e3,ao=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??JA,this.restartCapMs=r.restartCapMs??VA;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()},Ef);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 Ta(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Ta(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 Ta(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 Ta(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 Ta(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{}},Ef);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 uc(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"&&Pf(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ef;for(;Date.now()<i&&Pf(r);)await new Promise(o=>setTimeout(o,50));if(Pf(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=pc.dirname(this.adapter.paths.logFile(r.name)),a;try{await $s.mkdir(o,{recursive:!0}),a=await KA({file:pc.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})
|
|
312
|
+
`);let d=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=d,e.version=void 0;let c={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:d,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
|
|
313
|
+
`),a.end();return}let f=st(l),p=[...u,...r.args].map(st),h;try{h=zA(f,p,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
|
|
314
314
|
`),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{fc.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
|
|
315
315
|
`,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${y.message}
|
|
316
316
|
`)}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}
|
|
317
317
|
`)}),h.on("exit",(y,w)=>{try{fc.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${w??"null"}
|
|
318
318
|
`),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 v=e.breaker.recordExit(y,r.name,this.adapter.kind);if(typeof v=="object"){e.failureReason=v.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${v.tripped}
|
|
319
|
-
`);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 Pf(n){try{return process.kill(n,0),!0}catch{return!1}}function Ta(n,e){return n.code=e,n}we();var GA={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:
|
|
319
|
+
`);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 Pf(n){try{return process.kill(n,0),!0}catch{return!1}}function Ta(n,e){return n.code=e,n}we();var GA={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:L.extensionsDir,logFile:L.extensionLogFile,pidFile:L.extensionPidFile}},hc=class extends ao{constructor(e,t,s={}){super(e,GA,t,s)}};we();var YA={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:L.transformersDir,logFile:L.transformerLogFile,pidFile:L.transformerPidFile}},mc=class extends ao{connected=new Map;constructor(e,t,s={}){super(e,YA,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 gc=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{}}};we();Ui();Wi();we();Wi();import*as Pa from"fs/promises";import*as yc from"path";var Ea=n=>{process.stderr.write(n+`
|
|
320
320
|
`)};function Mf(n){Ea=n??(e=>process.stderr.write(e+`
|
|
321
|
-
`))}async function by(n,e){let t=Pn();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=yc.join(
|
|
321
|
+
`))}async function by(n,e){let t=Pn();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=yc.join(L.agentsDir(),t),a;try{a=await Pa.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;Ea(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=yc.join(o,c),p;try{p=await Pa.readdir(f,{withFileTypes:!0})}catch(h){Ea(`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=yc.join(f,m);try{await Pa.rm(y,{recursive:!0,force:!0}),Ea(`hydra-acp: pruned stale ${c} ${m} (${y})`)}catch(w){Ea(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function vy(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await Du(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 d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function _f(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),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(c+=1)}catch(h){l+=1,t("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${QA(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Sy(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await _f({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 QA(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`}gn();Ma();we();qr();import*as xy from"path";import{createHash as ZA,randomBytes as e0,timingSafeEqual as t0}from"crypto";var Ay="hydra_session_",n0=3600*24*30,ky=12,s0=32,r0=50;function i0(){return xy.join(L.home(),"session-tokens.json")}function Iy(n){return ZA("sha256").update(n).digest("hex")}function Cy(n){return e0(n).toString("hex")}function o0(){return Cy(ky).slice(0,ky*2)}function a0(){return`${Ay}${Cy(s0)}`}var wc=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=i0(),s=await Tn(t);s&&Array.isArray(s.records)&&(e=s.records.filter(d0));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=a0(),s=Iy(t),r=o0(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:n0,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Ay))return;let t=Iy(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||!t0(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(()=>{})},r0))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>fn(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 d0(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")}Ms();var Ry="Bearer ",bc=class{constructor(e){this.token=e}token;async validate(e){return c0(e,this.token)?"service":void 0}},vc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Sc=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Ty(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Ry)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Ry.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Ey(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 kc=class{tokens=new Map;mint(e,t){let s=Li();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 c0(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 Ic=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)}};pa();we();et();Of();Zr();Cc();import*as Df from"fs";import*as Gy from"os";import*as Yy from"path";import*as Hf from"readline";ur();ps();function Rc(n,e={}){let t=B0(n),s=N0(t),r=[];D0(r,n),H0(r,t,s,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let i=r.join(`
|
|
322
322
|
`);return i.endsWith(`
|
|
323
323
|
`)||(i+=`
|
|
324
324
|
`),i}function B0(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=gs(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function N0(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 D0(n,e){let t=e.session,s=ut(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${uo(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Bf(a.size)}`:void 0;d.push(c?`${Bf(a.used)} / ${c} tokens`:`${Bf(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
|
|
325
|
-
`)),n.push("")}function H0(n,e,t,s){let{includeTools:r,includeThoughts:i}=s;if(!e.some(m=>U0(m.event,i))){n.push("_No conversation history recorded._"),n.push("");return}let o=0,a="",d="",c=[],l=new Set,
|
|
326
|
-
`);for(let a=0;a<o.length;a++){let d=o[a],c=uo(d);n.push(a===0&&a===o.length-1?`${t}${c}${t}`:a===0?`${t}${c}`:a===o.length-1?`${c}${t}`:c)}r<s.length-1&&n.push("")}}function uo(n){return n.replace(/</g,"<").replace(/>/g,">")}function Bf(n){return n.toLocaleString("en-US")}Nt();gn();oa();lr();function W0(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let l of s){let f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>z0(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function z0(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Uy(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:Uy(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Uy(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function K0(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var J0=5,V0=200,jy=30;async function zy(n,e,t={}){let s=W0(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??J0,i=t.maxSessions??V0,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(f=>o.has(f.sessionId)):a,c=[],l=!1;for(let f of d){if(c.length>=i){l=!0;break}let u=await n.loadHistory(f.sessionId).catch(()=>[]),p=G0(u,s,r);if(p.snippets.length===0)continue;let h={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(h.title=f.title),c.push(h)}return{query:e,truncated:l,results:c}}function G0(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=Y0(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 Y0(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Q0(a).filter(c=>K0(t,c.kind));for(let c of d){let l=c.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(i+=u,o.length<s){let p=l.indexOf(r),h={kind:c.kind,text:nC(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(h.toolName=c.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Q0(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=Tc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?St(s.text):Tc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(eC(s))return[];let i=Tc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=tC(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return X0(s);default:return[]}}function X0(n){let e=qy(n,"name"),t=qy(n,"title"),s=[];if(t!==void 0){let a=Te(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Wy(r);if(a.length>0){let d={kind:"tool-input",text:Te(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Wy(i);if(a.length>0){let d={kind:"tool-input",text:Te(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=Z0(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Z0(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 eC(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 Tc(n){if(typeof n=="string")return St(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?St(e.text):""}function tC(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Tc(t);s.length>0&&e.push(s)}return e.join("")}function qy(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Wy(n){try{return JSON.stringify(n)}catch{return""}}function nC(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-jy),d=Math.min(s.length,o+i.length+jy),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}import{randomBytes as Jy}from"crypto";function Ky(n){let e=Jy(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 Nf(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(Ky({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Ky({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=fo(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function fo(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=Jy(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 Ec=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Vy(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Wr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Qy(n,e,t,s={}){n.get("/v1/sessions",async c=>{let l=c.query,f=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.getOne(u);return p||(l.code(404).send({error:"session not found"}),l)}),n.post("/v1/sessions/search",async(c,l)=>{let f=c.body??{},u=typeof f.q=="string"?f.q:"";if(u.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await zy(e,u,{sessionIds:p})}),n.post("/v1/sessions",async(c,l)=>{let f=c.body??{},u=st(f.cwd??t.cwd),p=f.agentId??t.agentId,h=fo(s),m=h!==void 0?[...f.mcpServers??[],...h.descriptors]:f.mcpServers;try{let y=await e.create({cwd:u,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),n.post("/v1/sessions/collect",async(c,l)=>{let f=c.body??{},u=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,p=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,h=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await _f({manager:e,maxAgeMs:u,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(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=c.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=>Yy.join(Gy.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(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let h=c.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(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(u,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(u)!==void 0||await e.hasRecord(u))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(u),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(u,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.delete("/v1/sessions/:id",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(u),await e.hasRecord(u)&&await e.deleteRecord(u),l.code(204).send();return}if(!await e.deleteRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.get("/v1/sessions/:id/export",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.query?.tools,h=p==="references"?"references":ry(p),m=await e.exportBundle(u,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=xa({record:m.record,history:h==="summary"?iy(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:be,machine:or(),hydraHost:Vy(t)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${u}-${w}.hydra"`),l.code(200).send(y)}),n.get("/v1/sessions/:id/diff",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=c.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=co(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:lo(b.hunks)}))),l.code(200).send(w)}),n.get("/v1/sessions/:id/tools/:hash",async(c,l)=>{let f=c.params,u=await e.resolveCanonicalId(f.id)??f.id,p=await e.loadToolBlob(u,f.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),n.get("/v1/sessions/:id/transcript",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let h=xa({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:be,machine:or(),hydraHost:Vy(t)}),m=c.query,y=w=>w==="1"||w==="true"||w==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Rc(h,{includeTools:y(m?.tools),includeThoughts:y(m?.thoughts)}))}),n.post("/v1/sessions/:id/fork",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.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=st(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(u,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===W.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===W.InvalidParams||y.code===W.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.post("/v1/sessions/import",async(c,l)=>{let f=c.body??{};if(f.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let u;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}u=f.cwd}let p;try{p=qn(f.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:f.replace===!0,...u!==void 0?{cwd:u}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===W.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(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(u),h===void 0&&!await e.hasRecord(u))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(u),y=await e.getRollbackBreadcrumb(u),w=!1,b,k=await e.getHistory(u).catch(()=>[])??[];if(k.length>0&&t.compaction){let A=h??0,E=k.length,H=k.slice(A).reduce((N,q)=>N+JSON.stringify(q.params).length,0);b=Ff(H);let _=p?.currentModel,F=k.at(-1).recordedAt,B=p?.currentUsage;w=Py({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(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f;if(e.get(u)){e.scheduleCompaction(u),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(u),l.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(u),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),n.get("/v1/sessions/:id/history",async(c,l)=>{let f=c.params.id,u=c.query,p=u?.follow==="1"||u?.follow==="true",h=await e.resolveCanonicalId(f)??f,m=e.get(h),y,w,b=!1,v=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
|
|
325
|
+
`)),n.push("")}function H0(n,e,t,s){let{includeTools:r,includeThoughts:i}=s;if(!e.some(m=>U0(m.event,i))){n.push("_No conversation history recorded._"),n.push("");return}let o=0,a="",d="",c=[],l=new Set,u=!1,f=()=>{if(c.length!==0){for(let m of c)n.push(m);n.push(""),c=[]}},p=()=>{f(),d.length>0&&(Hy(n,d.trimEnd(),"*"),n.push(""),d=""),a.length!==0&&(n.push(a.trimEnd()),n.push(""),a="")},h=()=>{u||(u=!0)};for(let{event:m}of e)switch(m.kind){case"user-text":{p(),n.push("---"),n.push(""),o+=1,Hy(n,m.text,"**"),n.push(""),u=!0;break}case"agent-text":h(),a+=m.text;break;case"agent-thought":{if(!i)break;h(),a.length>0&&(n.push(a.trimEnd()),n.push(""),a=""),d+=m.text;break}case"tool-call":{if(!r||(h(),(a.length>0||d.length>0)&&p(),l.has(m.toolCallId)))break;l.add(m.toolCallId);let y=t.get(m.toolCallId)??{title:m.title,status:m.status??"pending"};c.push(`- ${q0(y.status)} ${j0(y)}`);break}case"tool-call-update":break;case"plan":{h(),p(),n.push("**Plan:**"),n.push("");for(let y of m.entries){let w=y.status==="completed"?"[x]":"[ ]";n.push(`- ${w} ${uo(y.content)}`)}n.push("");break}case"mode-changed":h(),p(),n.push(`_mode: ${uo(m.mode)}_`),n.push("");break;case"model-changed":h(),p(),n.push(`_model: ${uo(m.model)}_`),n.push("");break;case"turn-complete":p();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}p()}function U0(n,e){switch(n.kind){case"agent-thought":return e;case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function j0(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${uo(n.title)}${t}`}function q0(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 Hy(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(`
|
|
326
|
+
`);for(let a=0;a<o.length;a++){let d=o[a],c=uo(d);n.push(a===0&&a===o.length-1?`${t}${c}${t}`:a===0?`${t}${c}`:a===o.length-1?`${c}${t}`:c)}r<s.length-1&&n.push("")}}function uo(n){return n.replace(/</g,"<").replace(/>/g,">")}function Bf(n){return n.toLocaleString("en-US")}Nt();gn();oa();ur();function W0(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>z0(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function z0(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Uy(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:Uy(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Uy(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function K0(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var J0=5,V0=200,jy=30;async function zy(n,e,t={}){let s=W0(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??J0,i=t.maxSessions??V0,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],l=!1;for(let u of d){if(c.length>=i){l=!0;break}let f=await n.loadHistory(u.sessionId).catch(()=>[]),p=G0(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),c.push(h)}return{query:e,truncated:l,results:c}}function G0(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=Y0(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 Y0(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Q0(a).filter(c=>K0(t,c.kind));for(let c of d){let l=c.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:c.kind,text:nC(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(h.toolName=c.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Q0(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=Tc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?St(s.text):Tc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(eC(s))return[];let i=Tc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=tC(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return X0(s);default:return[]}}function X0(n){let e=qy(n,"name"),t=qy(n,"title"),s=[];if(t!==void 0){let a=Te(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=Te(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Wy(r);if(a.length>0){let d={kind:"tool-input",text:Te(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Wy(i);if(a.length>0){let d={kind:"tool-input",text:Te(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=Z0(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Z0(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 eC(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 Tc(n){if(typeof n=="string")return St(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?St(e.text):""}function tC(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Tc(t);s.length>0&&e.push(s)}return e.join("")}function qy(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Wy(n){try{return JSON.stringify(n)}catch{return""}}function nC(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-jy),d=Math.min(s.length,o+i.length+jy),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}import{randomBytes as Jy}from"crypto";function Ky(n){let e=Jy(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 Nf(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(Ky({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Ky({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=fo(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function fo(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=Jy(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 Ec=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Vy(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Wr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Qy(n,e,t,s={}){n.get("/v1/sessions",async c=>{let l=c.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),n.get("/v1/sessions/:id",async(c,l)=>{let u=c.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(c,l)=>{let u=c.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 zy(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(c,l)=>{let u=c.body??{},f=st(u.cwd??t.cwd),p=u.agentId??t.agentId,h=fo(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(c,l)=>{let u=c.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 _f({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(c,l)=>{let u=c.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(c,l)=>{let u=c.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=c.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=>Yy.join(Gy.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(c,l)=>{let u=c.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=c.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(c,l)=>{let u=c.params.id,f=await e.resolveCanonicalId(u)??u,p=c.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(c,l)=>{let u=c.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(c,l)=>{let u=c.params.id,f=await e.resolveCanonicalId(u)??u,p=c.query?.tools,h=p==="references"?"references":ry(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=xa({record:m.record,history:h==="summary"?iy(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:be,machine:ar(),hydraHost:Vy(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(c,l)=>{let u=c.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=c.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=co(p.history);y&&(w=w.filter(b=>y.has(b.path))),m&&(w=w.map(b=>({...b,hunks:lo(b.hunks)}))),l.code(200).send(w)}),n.get("/v1/sessions/:id/tools/:hash",async(c,l)=>{let u=c.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(c,l)=>{let u=c.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=xa({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:be,machine:ar(),hydraHost:Vy(t)}),m=c.query,y=w=>w==="1"||w==="true"||w==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Rc(h,{includeTools:y(m?.tools),includeThoughts:y(m?.thoughts)}))}),n.post("/v1/sessions/:id/fork",async(c,l)=>{let u=c.params.id,f=await e.resolveCanonicalId(u)??u,p=c.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=st(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===W.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===W.InvalidParams||y.code===W.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.post("/v1/sessions/import",async(c,l)=>{let u=c.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=qn(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===W.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(c,l)=>{let u=c.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,U)=>N+JSON.stringify(U.params).length,0);b=Ff(H);let P=p?.currentModel,$=k.at(-1).recordedAt,B=p?.currentUsage;w=Py({summarizedThroughEntry:A,totalEntries:E,unsummarizedChars:H,compactionInFlight:e.getCompactionInFlight(),currentModel:P,lastActivityMs:$,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(c,l)=>{let u=c.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(c,l)=>{let u=c.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(c,l)=>{let u=c.params.id,f=c.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,w,b=!1,v=1e4,k=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify(E)+`
|
|
327
327
|
`):(k.push(E),k.length>v&&k.shift()))})),c.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)+`
|
|
328
|
-
`);let
|
|
329
|
-
`)}}return b=!0,w||l.raw.end(),l});function r(c,l,
|
|
330
|
-
`),await d(A),A.exhausted){try{A.rl.close()}catch{}b.splice(v,1)}}}catch(v){for(let k of b)try{k.rl.close()}catch{}throw v}return l.raw.end(),l}),n.get("/v1/sessions/:id/events",async(c,l)=>{let
|
|
331
|
-
`)}}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(c,l)=>{let
|
|
332
|
-
`;await ur.mkdir(O.home(),{recursive:!0}),await ur.writeFile(Uf(),s,{encoding:"utf8",mode:384})}async function Mc(){try{return(await ur.readFile(Uf(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function _c(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ur.readFile(Uf(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await aw(n,o,a.length,{N:s,r,p:i,maxmem:dw});return d.length!==a.length?!1:aC(d,a)}var uC=po.object({password:po.string().min(1),label:po.string().min(1).max(256).optional(),ttlSec:po.number().int().positive().optional()}),fC=po.object({id:po.string().optional()}).optional();function lw(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=pC(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=uC.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Mc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await _c(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=fC.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function pC(n){return n.ip||"unknown"}Yr();ho();import{nanoid as jf}from"nanoid";Gd();Nt();gn();import{randomBytes as fw}from"crypto";import*as pw from"os";import*as hw from"path";function se(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function wC(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function yn(n,e,t){let s=n.get(e);if(!s)throw se(W.SessionNotFound,t??`session ${e} not found`);return s}async function $c(n,e){let t=fo(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=fw(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]:[]],d=Nf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}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(c),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,f=n.mcpTokenRegistry;r.complete(c),c.onClose(()=>{f.unbind(l)})}return RC(c,n),gw(c.sessionId,n),c}function mw(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Ey({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=ys(t),a=new Zt(o),d={clientId:`hydra_client_${jf(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly)throw se(W.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=Ym.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),CC()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return f.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,y),{ok:!0,registered:y.length}});let u=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw se(W.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(W.InvalidParams,"key is required");if(!e.manager)throw se(W.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=u(p);if(!e.manager)throw se(W.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(W.InvalidParams,"key is required");if(m.value===void 0)throw se(W.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(W.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(W.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=u(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(W.InvalidParams,"key is required");if(!e.manager)throw se(W.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(W.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{f.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async u=>{let p=u??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw se(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw se(-32602,"emit_message requires method");let b=yn(e.manager,h),v=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(v)return b.dischargeClaim(v,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let p=u??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return yn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async u=>kC(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let p=u??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let P=e.manager.get(y);P&&(m=P.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:v,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(W.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,b=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(W.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let f=async(u,p)=>{let h=u??{};if(typeof h.sessionId!="string")throw se(W.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async u=>(await f(u,"session/delete"),{})),a.onRequest("session/close",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw se(W.InvalidParams,"session/close requires sessionId");c(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(W.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async u=>{let{id:p,existed:h}=await f(u,"hydra-acp/session/delete");if(!h)throw se(W.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw se(-32602,"await_child requires childSessionId");let w=yn(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(q),_?.(),F?.(),b(H?{entries:A,truncated:!0}:{entries:A}))};_=w.onBroadcast(Q=>{let X=wC(Q);for(A.push(Q),E.push(X),P+=X;A.length>0&&(A.length>1e3||P>1048576);)A.shift(),P-=E.shift()??0,H=!0;m==="turn_complete"&&Q.params?.update?.sessionUpdate==="turn_complete"&&N()});let q=setTimeout(N,y);typeof q.unref=="function"&&q.unref(),F=w.onClose(()=>N())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let p=u??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>IC(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>xC(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let p=u??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw se(W.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,h=await e.manager.loadToolBlob(p,u.hash);if(h===null)throw se(W.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async f=>bC(f,e)),a.onRequest("logout",async f=>vC(f,e)),a.onRequest("session/new",async f=>{let u=Qm.parse(f),p=hn(f?._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=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=fw(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let q={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...u.mcpServers??[],q]}let v,k,A=fo(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=Nf({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),P;try{P=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:uw(a),transformChain:m,originatingClient:d.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,q=e.mcpTokenRegistry;w.complete(P),P.onClose(()=>{q.unbind(N)})}if(v!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=v,q=e.mcpTokenRegistry;k.complete(P),P.onClose(()=>{q.unbind(N)})}A!==void 0&&A.bindToSession(P),gw(P.sessionId,e);let H,_;try{Bc(d,P,P.sessionId),H=Oa(a,P,d),{entries:_}=await P.attach(H,"full")}catch(N){throw await P.close({deleteRecord:!1}).catch(()=>{}),N}d.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=Fc(P),B=Oc(P);return{sessionId:P.sessionId,...F?{modes:F}:{},...B?{models:B}:{},configOptions:P.buildConfigOptions(),_meta:Lc(e.manager,P,{clientId:H.clientId})}}),a.onRequest("session/attach",async f=>{let u=Zm.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=hn(u._meta),m=h.resume,y=h.readonly===!0,w=h.env;n.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,v=e.manager.get(b);if(!v&&y){let B=await e.manager.loadFromDisk(b);if(!B)throw se(W.SessionNotFound,`session ${u.sessionId} not found`);let N=await e.manager.loadHistory(b),q=u.clientId??`cli_${jf(8)}`;d.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:q,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${q} attachedCount=${d.attached.size} replayed=${N.length}`);for(let Q of N)await a.notify(Q.method,Q.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:q,connectedClients:[q],historyPolicy:"full",replayed:N.length,_meta:AC(B)}}let k=!v;if(!v){let B=await e.manager.loadFromDisk(b),N=B;if(m&&(N={...B,hydraSessionId:u.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!N)throw se(W.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw se(W.SessionNotFound,`session ${u.sessionId} was deleted`);let q=N.originatingClient?N:{...N,originatingClient:d.clientInfo},Q=w!==void 0?{...q,forwardedEnv:w}:q;v=await $c(e,{...Q,onInstallProgress:uw(a)})}Bc(d,v,v.sessionId);let A=Oa(a,v,d,u.clientInfo,u.clientId),E=h.replayMode==="drip",{entries:P,appliedPolicy:H}=await v.attach(A,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(d.attached.set(v.sessionId,{sessionId:v.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(v.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${v.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.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 q=null;for(let Q of P){let X=typeof Q.recordedAt=="number"?Q.recordedAt:null;if(q!==null&&X!==null){let G=Math.min(N,Math.max(0,(X-q)/B));G>0&&await new Promise(pe=>setTimeout(pe,G))}X!==null&&(q=X);try{await a.notify(Q.method,Q.params)}catch{return}}})()}else for(let B=0;B<P.length&&!a.isClosed();B++){let N=P[B],q=a.notify(N.method,N.params).catch(()=>{});(B+1)%200===0&&await q}v.replayPendingPermissions(A);let _=Fc(v),F=Oc(v);return{sessionId:v.sessionId,clientId:A.clientId,connectedClients:v.connectedClients(A.clientId),historyPolicy:H,replayed:P.length,..._?{modes:_}:{},...F?{models:F}:{},configOptions:v.buildConfigOptions(),_meta:Lc(e.manager,v,{resurrected:k})}}),a.onRequest("session/detach",async f=>{let u=eg.parse(f),p=d.attached.get(u.sessionId);if(!p)throw se(W.SessionNotFound,"client not attached to that session");let h=e.manager.get(u.sessionId);return h?.detach(p.clientId),d.attached.delete(u.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[Bt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=tg.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==Qr).map(ng)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(W.InternalError,"agent registry unavailable");return Ki(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let u=f??{};if(typeof u.agentId!="string"||u.agentId.length===0)throw se(W.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(u.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let u=sg.parse(f);c(u.sessionId,"session/prompt");let p=d.attached.get(u.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),se(W.SessionNotFound,"not attached to session");let h=e.manager.get(u.sessionId);if(!h){let m=await e.manager.loadFromDisk(u.sessionId);if(!m)throw se(W.SessionNotFound,`session ${u.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),h=await $c(e,m);let y=Oa(a,h,d,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,u)});let l=f=>{let u;try{u=jd.parse(f)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let h=e.manager.get(u.sessionId);h&&h.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${u.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=jd.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=ig.parse(f);return c(u.sessionId,"hydra-acp/prompt/cancel"),yn(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=jd.parse(f);return c(u.sessionId,"hydra-acp/session/force_cancel"),yn(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=og.parse(f);return c(u.sessionId,"hydra-acp/prompt/update"),yn(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=ag.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p)throw se(W.SessionNotFound,"not attached to session");return yn(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/resume",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(W.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let v=await e.manager.loadFromDisk(h);if(!v)throw se(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await $c(e,v)}Bc(d,m,m.sessionId);let y=Oa(a,m,d);await m.attach(y,"pending_only"),d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=Fc(m),b=Oc(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:Lc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw se(W.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw se(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await $c(e,k)}Bc(d,m,m.sessionId);let y=Oa(a,m,d),{entries:w}=await m.attach(y,"pending_only");d.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=Fc(m),v=Oc(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:Lc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=SC(f,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),se(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",{...f,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw se(W.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw se(W.InvalidParams,"session/set_mode requires string modeId");let h=yn(e.manager,u.sessionId),m=await h.forwardRequest("session/set_mode",f);return h.applyModeChange(u.modeId),m}),a.onRequest("session/set_config_option",async f=>{let u=f,p=w=>se(W.InvalidParams,w),h=u?.sessionId;if(typeof h=="string"&&c(h,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let m=yn(e.manager,u.sessionId),y=m.buildConfigOptions().find(w=>w.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(w=>w.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),m.applyModelChange(u.value);break}case"mode":{u.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),m.applyModeChange(u.value);break}case"agent":{u.value!==m.agentId&&await m.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=u.startsWith("session/"),m=u.startsWith("hydra-acp/");if(!h&&!m||f===null||typeof f!="object"||p.has(u))throw se(W.MethodNotFound,`Method not found: ${u}`);let y=f.sessionId;if(typeof y!="string")throw se(W.MethodNotFound,`Method not found: ${u}`);return c(y,u),yn(e.manager,y).forwardRequest(u,f)})})}async function bC(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw se(W.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 d=a.authMethods??[],c=d.find(p=>p.id===s);if(!c){let p=d.map(h=>h.id);throw se(W.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=c._meta?.type,f=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:f!==void 0?"terminal":"agent"))==="terminal"){let p=(v,k)=>{if(!Array.isArray(v))throw se(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${v===null?"null":typeof v}`);for(let A of v)if(typeof A!="string")throw se(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return v},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(f?.args!==void 0){let v=typeof f.command=="string"?f.command:void 0;m=v!==void 0&&hw.isAbsolute(v)?v:h.command,y=p(f.args,'_meta["terminal-auth"].args')}else{let v=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,k=v!==void 0?p(v.raw,v.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[v,k]of Object.entries(process.env))typeof k=="string"&&(w[v]=k);Object.assign(w,h.env);let b=pw.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 dr(p,a)}}async function vC(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 uw(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(qd,t).catch(()=>{})}}function Fc(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 Oc(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function SC(n,e){if(!n||typeof n!="object")return{kind:"error",code:W.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:W.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:W.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:W.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Xi(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:W.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 kC(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(W.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw se(W.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw se(W.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return yn(t.manager,r).addTransformer(i),{ok:!0}}async function IC(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 se(W.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(W.InvalidParams,"hydra-acp/attention/set requires string reason");return yn(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function xC(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 se(W.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(W.InvalidParams,"hydra-acp/attention/clear requires string reason");return yn(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function AC(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{[Bt]:Hd(e,t)}}function Lc(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 fa(e.agentMeta,Hd(s,r))}function CC(){return{protocolVersion:1,agentInfo:{name:"hydra",version:be},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:fa(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 RC(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 gw(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 Oa(n,e,t,s,r){return{clientId:r??`cli_${jf(8)}`,connection:n,clientInfo:s}}function Bc(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var Nc=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 TC}from"crypto";import{McpServer as EC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as PC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Dt}from"zod";function qf(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 en(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var yw="Bearer ";function mo(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(yw))return;let t=e.slice(yw.length).trim();return t.length>0?t:void 0}function MC(n){let e=new EC({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:Dt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return en(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:Dt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return en(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:Dt.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:Dt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Dt.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 en(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:Dt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Dt.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 en({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:Dt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Dt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Dt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Dt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Dt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Dt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Dt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Dt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Dt.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 en(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 en(t)}),e}var _C=1e4;function ww(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=MC(a),l=new PC({sessionIdGenerator:()=>TC()});await c.connect(l);let f={server:c,transport:l};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=mo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),_C)}),h=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let f=await s(d,l);a.hijack(),await f.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)})}Yd();import{randomUUID as $C}from"crypto";import{McpServer as FC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as OC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as fr}from"zod";function LC(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function BC(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 NC(n){let e=new FC({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:fr.string().min(1).describe("Case-insensitive substring to search for."),limit:fr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:fr.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 en({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:c,entry:l}of i.iterRecallNewestFirst()){let f=qf(l);if(!f)continue;let{kind:u}=f;if(u==="tool_call"&&!r)continue;let p=Zi([l]),h=p.toLowerCase().indexOf(a);if(h<0)continue;let m=LC(u),y=BC(p,h),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(o.push({entryId:c,speaker:m,snippet:y,timestamp:w}),o.length>=s)break}o.sort((c,l)=>c.entryId-l.entryId);let d=o.length>=s;return en({matches:o,total_matched:o.length,truncated:d})}),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:fr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:fr.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 en({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 en({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),d=Math.min(s,o-1),c=a>t||d<s;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await r.sliceRecallHistory(a,d),f=Zi(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:c}}}),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:fr.string().optional(),file_path:fr.string().optional(),limit:fr.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 en({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 d=new Map,c=Math.max(r*4,200);for await(let{entryId:p,entry:h}of i.iterRecallNewestFirst()){let m=qf(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}`,v=d.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(b,v)),p<v.entryId&&(v.entryId=p),typeof w.name=="string"&&w.name.length>0?v.toolName=w.name:v.toolName==="(unnamed)"&&typeof w.title=="string"&&w.title.length>0&&(v.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))v.rawInput[A]===void 0&&(v.rawInput[A]=E);if(Array.isArray(w.locations))for(let A of w.locations){let E=A?.path;typeof E=="string"&&E.length>0&&!v.locations.includes(E)&&v.locations.push(E)}if(typeof w.status=="string"&&v.status==="in_progress"&&(v.status=w.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt)),d.size>=c)break}let l=[...d.keys()].sort((p,h)=>d.get(p).entryId-d.get(h).entryId),f=[];for(let p of l){let h=d.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 v of w){let k=h.rawInput[v];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let v of h.locations)if(v.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),f.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),f.length>=r)break}let u=f.length>=r;return en({calls:f,truncated:u})}),e}var DC=1e4;function bw(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=NC(a),l=new OC({sessionIdGenerator:()=>$C()});await c.connect(l);let f={server:c,transport:l};return t.set(o,f),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=mo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(d,async()=>{if(c.session!==void 0)return c.session;let u,p=new Promise(m=>{u=setTimeout(()=>m(void 0),DC)}),h=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};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 Dc=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 JC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as VC}from"crypto";import{Server as HC}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as UC,ListToolsRequestSchema as jC}from"@modelcontextprotocol/sdk/types.js";function vw(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new HC({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(jC,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let d=await s.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(UC,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,f=WC(l,d.sendNotification);try{let u=await r(),p=await zC(e.connection,n,c,a.params.arguments??{},u);return KC(p,c)}catch(u){return Wf(u instanceof Error?u.message:String(u))}finally{f()}}),i}var qC=15e3;function WC(n,e,t=qC){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 zC(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function KC(n,e){if(n===null||typeof n!="object")return Wf(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Wf(`extension ${e} omitted content array`)}function Wf(n){return{content:[{type:"text",text:n}],isError:!0}}var GC=1e4;function Sw(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 f of s.values()){let u=f.get(l);u!==void 0&&(f.delete(l),r(u))}}async function o(l,f){for(let[u,p]of s){if(e.lookup(u)?.session?.sessionId!==l)continue;let m=p.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(l=>{i(l)});async function a(l,f){let u=s.get(l);u===void 0&&(u=new Map,s.set(l,u),e.addDisposer(l,async()=>{let k=s.get(l);if(k!==void 0){s.delete(l);for(let A of k.values())await r(A)}}));let p=u.get(f);if(p!==void 0)return p.transport;let h=t.lookup(f);if(h===void 0)return;let b=vw(f,h,async()=>{let k=e.lookup(l);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let A,E=new Promise(H=>{A=setTimeout(()=>H(void 0),GC)}),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}}),v=new JC({sessionIdGenerator:()=>VC()});return await b.connect(v),u.set(f,{server:b,transport:v}),v}async function d(l,f){let u=mo(l);if(u===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){f.code(404).send({error:"unknown mcp token"});return}let h=l.params.name,m=await a(u,h);if(m===void 0){f.code(404).send({error:`unknown mcp server: ${h}`});return}f.hijack(),await m.handleRequest(l.raw,f.raw,l.body)}let c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(l,f)=>{await d(l,f)}),n.get("/mcp/:name",c,async(l,f)=>{await d(l,f)}),n.delete("/mcp/:name",c,async(l,f)=>{await d(l,f)}),{notifyToolListChanged:o}}async function Rw(n,e){nR(n);let t=n.daemon.tls?await ws.readFile(st(n.daemon.tls.key)):void 0,s=n.daemon.tls?await ws.readFile(st(n.daemon.tls.cert)):void 0;await ws.mkdir(O.home(),{recursive:!0});let{stream:r,fileStream:i}=await eR(n.daemon.logLevel),o=YC({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(QC,{options:{handleProtocols:Mm}}),Fu(ee=>{o.log.info(ee)}),Bu(ee=>{o.log.info(ee)});let a=await wc.load(),d=new Ic,c=new kc,l=new Sc([new bc(e),new vc(a),c]),f=Ty({validator:l});o.addHook("onRequest",async(ee,Ee)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await f(ee,Ee)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{d.sweepExpired()},300*1e3);p.unref();let h=new Bd(n,{onFetched:()=>{by(h,b)}});Mf(ee=>o.log.info(ee));let m={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},y=ee=>ir.spawn({...ee,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Om(n.compressToolContent);let w=new gc,b=new cc(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}),v=new hc(nm(n),void 0,{tokenRegistry:c}),k=new mc(sm(n),void 0,{tokenRegistry:c});Zy(o,be,cr(n));let A=new Nc,E=new Dc,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};Qy(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}),Xy(o,h,b,{npmRegistry:n.npmRegistry}),ew(o,v),tw(o,k),nw(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]}),lw(o,{store:a,rateLimiter:d}),ww(o,A),bw(o,A);let _=Sw(o,A,E);mw(o,{validator:l,manager:b,defaultAgent:n.defaultAgent,processRegistry:c,onExtensionVersion:(ee,Ee)=>v.reportVersion(ee,Ee),onTransformerVersion:(ee,Ee)=>k.reportVersion(ee,Ee),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,q,Q=n.daemon.host,X=N;if(F&&t&&s){q=tR({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=q.address();ee&&typeof ee=="object"&&(X=ee.port)}await ws.mkdir(O.home(),{recursive:!0}),await fm({pid:process.pid,host:Q,port:X,loopbackPort:N,startedAt:new Date().toISOString()});let G={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()};v.setContext(G),k.setContext(G),await v.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 pe=n.daemon.agentSyncIntervalMinutes*60*1e3,nt=pe>0?vy({registry:h,manager:b,intervalMs:pe,logger:m}):void 0,js=n.daemon.sessionGcIntervalMinutes*60*1e3,We=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,kt=js>0?Sy({manager:b,intervalMs:js,maxAgeMs:We,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:v,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:c,shutdown:async()=>{kt&&kt(),nt&&nt(),clearInterval(u),clearInterval(p);let ee=async(Ee,Je)=>{try{await Je()}catch(Pt){o.log.warn(`shutdown step ${Ee} failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>v.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()),Fu(null),Bu(null),Mf(null),q&&await ee("tlsTerminator.close",()=>new Promise(Ee=>q.close(()=>Ee()))),await ee("app.close",()=>o.close());try{xw.unlinkSync(O.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}var Iw=20;async function ZC(n,e){let t=go.dirname(n),s=go.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await ws.readdir(t)}catch{return}let o=[];for(let d of i){let c=d.match(r);c&&o.push({name:d,n:Number(c[1])})}if(o.length<=e)return;o.sort((d,c)=>d.n-c.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(d=>ws.unlink(go.join(t,d.name))))}async function eR(n){await ZC(O.logFile(),Iw);let e=await XC({file:O.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Iw,removeOtherLogFiles:!0}}),t=kw.destination(2);return{stream:kw.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function tR(n){let e=Cw.createServer(n.tlsOptions,t=>{let s=Aw.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 nR(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.`)}ni();gn();Ma();La();async function _w(n={}){let e=await xe(),t=await ra();if(await Hc(e)){let r=await bo();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
328
|
+
`);let _=E;typeof _.recordedAt=="number"&&A.add(String(_.recordedAt))}for(;k.length>0;){let E=k.splice(0,k.length);for(let _ of E){let H=_,P=typeof H.recordedAt=="number"?String(H.recordedAt):"";P&&A.has(P)||l.raw.write(JSON.stringify(_)+`
|
|
329
|
+
`)}}return b=!0,w||l.raw.end(),l});function r(c,l,u){let f=typeof c=="string"?c.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(c,l,u){let p=l.params.update,h={sessionId:c,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(c,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(c,h.entry,m)}}}}async function a(c,l,u,f){let p=Hf.createInterface({input:Df.createReadStream(l),crlfDelay:1/0}),h=o(c,p,u,f),m=await h.next(),y=m.done?null:m.value;return{sessionId:c,rl:p,gen:h,current:y,exhausted:y===null}}async function d(c){let l=await c.gen.next();l.done?(c.exhausted=!0,c.current=null):c.current=l.value}n.get("/v1/sessions/events",async(c,l)=>{let u=c.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(v=>v.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let v of p)if(!Ec.has(v))return l.code(400).send({error:`kind "${v}" is not queryable; allowed kinds: ${[...Ec].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let v=new Date(u.since);if(isNaN(v.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=v.getTime()}let y=await e.list({includeNonInteractive:!0}),w=m!==void 0?y.filter(v=>new Date(v.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let b=[];for(let v of w)try{let k=L.historyFile(v.sessionId),A=await a(v.sessionId,k,h,m);A.exhausted||b.push(A)}catch(k){if(k.code==="ENOENT")continue;throw k}c.raw.on("close",()=>{for(let v of b)try{v.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;b.length>0;){let v=-1,k=1/0;for(let E=0;E<b.length;E++){let _=b[E];_.current!==null&&_.current.ts<k&&(k=_.current.ts,v=E)}if(v===-1)break;let A=b[v];if(l.raw.write(JSON.stringify(A.current.row)+`
|
|
330
|
+
`),await d(A),A.exhausted){try{A.rl.close()}catch{}b.splice(v,1)}}}catch(v){for(let k of b)try{k.rl.close()}catch{}throw v}return l.raw.end(),l}),n.get("/v1/sessions/:id/events",async(c,l)=>{let u=c.params.id,f=c.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(!Ec.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...Ec].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 v=L.historyFile(p),k=Df.createReadStream(v),A=Hf.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 _=typeof E=="string"?E.trim():"";if(_.length===0)continue;let H;try{H=JSON.parse(_)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",v);continue}if(!H||typeof H!="object"||Array.isArray(H)){console.debug("events endpoint: skipping non-object JSONL line in %s",v);continue}let P=H;if(typeof P.recordedAt!="number"||typeof P.params!="object"||P.params===null||Array.isArray(P.params))continue;let $=P.params;if(typeof $.update!="object"||$.update===null||Array.isArray($.update))continue;let B=$.update,N=B.sessionUpdate;if(typeof N!="string"||!w.has(N)||b!==void 0&&P.recordedAt<b)continue;let U={ts:new Date(P.recordedAt).toISOString(),kind:N,update:B};B.messageId!==void 0&&B.messageId!==null&&(U.messageId=B.messageId),l.raw.write(JSON.stringify(U)+`
|
|
331
|
+
`)}}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(c,l)=>{let u=c.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(c,l)=>{let u=c.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(c,l)=>{let u=c.params.id,f=await e.resolveCanonicalId(u)??u,h=c.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(_=>`${_.source}::${_.reason}`);for(let _ of E)w.clearAttentionFlag(_.split("::")[0],_.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let b=e.store,v=await b.read(f);if(!v){l.code(404).send({error:"session not found"});return}let k=v.attentionFlags??[],A;if(m.length>0&&y.length>0){let E=`${m}::${y}`;A=k.filter(_=>`${_.source}::${_.reason}`!==E)}else A=[];if(A.length===k.length&&A.every((E,_)=>E.source===k[_].source&&E.reason===k[_].reason)){l.code(204).send();return}await b.write({...v,attentionFlags:A}),l.code(204).send()})}Nt();function Xy(n,e,t,s={}){n.get("/v1/agents",async()=>Ki(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await Mn(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===W.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function Zy(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var sC=/^[A-Za-z0-9._-]+$/;function Pc(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=rC(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){Fa(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){Fa(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){Fa(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){Fa(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){Fa(o,d)}})}function Fa(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 rC(n){let e=n.name;if(typeof e!="string"||!sC.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 ew(n,e){Pc(n,"extension",e)}function tw(n,e){Pc(n,"transformer",e)}function nw(n,e){n.get("/v1/config",async()=>e)}import{z as po}from"zod";we();import*as fr from"fs/promises";import*as ow from"path";import{randomBytes as iC,scrypt as oC,timingSafeEqual as aC}from"crypto";import{promisify as dC}from"util";var aw=dC(oC);function Uf(){return ow.join(L.home(),"password-hash")}var sw=32768,rw=8,iw=1,cC=64,lC=16,dw=128*1024*1024;async function cw(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=iC(lC),t=await aw(n,e,cC,{N:sw,r:rw,p:iw,maxmem:dw}),s=`scrypt$${sw}$${rw}$${iw}$${e.toString("hex")}$${t.toString("hex")}
|
|
332
|
+
`;await fr.mkdir(L.home(),{recursive:!0}),await fr.writeFile(Uf(),s,{encoding:"utf8",mode:384})}async function Mc(){try{return(await fr.readFile(Uf(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function _c(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await fr.readFile(Uf(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await aw(n,o,a.length,{N:s,r,p:i,maxmem:dw});return d.length!==a.length?!1:aC(d,a)}var uC=po.object({password:po.string().min(1),label:po.string().min(1).max(256).optional(),ttlSec:po.number().int().positive().optional()}),fC=po.object({id:po.string().optional()}).optional();function lw(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=pC(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=uC.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Mc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await _c(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=fC.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function pC(n){return n.ip||"unknown"}Yr();ho();import{nanoid as jf}from"nanoid";Gd();Nt();gn();import{randomBytes as fw}from"crypto";import*as pw from"os";import*as hw from"path";function se(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function wC(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function yn(n,e,t){let s=n.get(e);if(!s)throw se(W.SessionNotFound,t??`session ${e} not found`);return s}async function $c(n,e){let t=fo(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=fw(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]:[]],d=Nf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}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(c),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,u=n.mcpTokenRegistry;r.complete(c),c.onClose(()=>{u.unbind(l)})}return RC(c,n),gw(c.sessionId,n),c}function mw(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Ey({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=ys(t),a=new Zt(o),d={clientId:`hydra_client_${jf(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,f)=>{if(d.attached.get(u)?.readonly)throw se(W.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Ym.parse(u??{});f.clientInfo?.name&&(d.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),CC()}),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 v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).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 se(W.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 se(W.InvalidParams,"key is required");if(!e.manager)throw se(W.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 se(W.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 se(W.InvalidParams,"key is required");if(m.value===void 0)throw se(W.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(W.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(W.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 se(W.InvalidParams,"key is required");if(!e.manager)throw se(W.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(W.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 se(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw se(-32602,"emit_message requires method");let b=yn(e.manager,h),v=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(v)return b.dischargeClaim(v,y),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return yn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>kC(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,v=b&&typeof b.title=="string"?b.title:void 0,k=b&&typeof b.model=="string"?b.model:void 0;if(!m&&y){let _=e.manager.get(y);_&&(m=_.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:A,transformChain:[],title:v,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(W.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 se(W.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 se(W.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 se(W.InvalidParams,"session/close requires sessionId");c(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(W.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 se(W.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 se(-32602,"await_child requires childSessionId");let w=yn(e.manager,h,`child session ${h} not found`);return new Promise(b=>{let A=[],E=[],_=0,H=!1,P,$,B=!1,N=()=>{B||(B=!0,clearTimeout(U),P?.(),$?.(),b(H?{entries:A,truncated:!0}:{entries:A}))};P=w.onBroadcast(G=>{let X=wC(G);for(A.push(G),E.push(X),_+=X;A.length>0&&(A.length>1e3||_>1048576);)A.shift(),_-=E.shift()??0,H=!0;m==="turn_complete"&&G.params?.update?.sessionUpdate==="turn_complete"&&N()});let U=setTimeout(N,y);typeof U.unref=="function"&&U.unref(),$=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 se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>IC(f,i.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>xC(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 se(W.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw se(W.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>bC(u,e)),a.onRequest("logout",async u=>vC(u,e)),a.onRequest("session/new",async u=>{let f=Qm.parse(u),p=hn(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=fw(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let U={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};b=[...f.mcpServers??[],U]}let v,k,A=fo(e);A!==void 0&&(b=[...b??[],...A.descriptors]);let E=Nf({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),_;try{_=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:uw(a),transformChain:m,originatingClient:d.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,U=e.mcpTokenRegistry;w.complete(_),_.onClose(()=>{U.unbind(N)})}if(v!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=v,U=e.mcpTokenRegistry;k.complete(_),_.onClose(()=>{U.unbind(N)})}A!==void 0&&A.bindToSession(_),gw(_.sessionId,e);let H,P;try{Bc(d,_,_.sessionId),H=Oa(a,_,d),{entries:P}=await _.attach(H,"full")}catch(N){throw await _.close({deleteRecord:!1}).catch(()=>{}),N}d.attached.set(_.sessionId,{sessionId:_.sessionId,clientId:H.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of P){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let $=Fc(_),B=Oc(_);return{sessionId:_.sessionId,...$?{modes:$}:{},...B?{models:B}:{},configOptions:_.buildConfigOptions(),_meta:Lc(e.manager,_,{clientId:H.clientId})}}),a.onRequest("session/attach",async u=>{let f=Zm.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=hn(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,v=e.manager.get(b);if(!v&&y){let B=await e.manager.loadFromDisk(b);if(!B)throw se(W.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(b),U=f.clientId??`cli_${jf(8)}`;d.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:U,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${U} attachedCount=${d.attached.size} replayed=${N.length}`);for(let G of N)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:U,connectedClients:[U],historyPolicy:"full",replayed:N.length,_meta:AC(B)}}let k=!v;if(!v){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 se(W.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw se(W.SessionNotFound,`session ${f.sessionId} was deleted`);let U=N.originatingClient?N:{...N,originatingClient:d.clientInfo},G=w!==void 0?{...U,forwardedEnv:w}:U;v=await $c(e,{...G,onInstallProgress:uw(a)})}Bc(d,v,v.sessionId);let A=Oa(a,v,d,f.clientInfo,f.clientId),E=h.replayMode==="drip",{entries:_,appliedPolicy:H}=await v.attach(A,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(d.attached.set(v.sessionId,{sessionId:v.sessionId,clientId:A.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(v.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${v.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${H} replayed=${_.length} readonly=${y}${E?" replayMode=drip":""}`),E){let B=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,N=750;(async()=>{let U=null;for(let G of _){let X=typeof G.recordedAt=="number"?G.recordedAt:null;if(U!==null&&X!==null){let Y=Math.min(N,Math.max(0,(X-U)/B));Y>0&&await new Promise(pe=>setTimeout(pe,Y))}X!==null&&(U=X);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let B=0;B<_.length&&!a.isClosed();B++){let N=_[B],U=a.notify(N.method,N.params).catch(()=>{});(B+1)%200===0&&await U}v.replayPendingPermissions(A);let P=Fc(v),$=Oc(v);return{sessionId:v.sessionId,clientId:A.clientId,connectedClients:v.connectedClients(A.clientId),historyPolicy:H,replayed:_.length,...P?{modes:P}:{},...$?{models:$}:{},configOptions:v.buildConfigOptions(),_meta:Lc(e.manager,v,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=eg.parse(u),p=d.attached.get(f.sessionId);if(!p)throw se(W.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),d.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Bt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=tg.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Qr).map(ng)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(W.InternalError,"agent registry unavailable");return Ki(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw se(W.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=sg.parse(u);c(f.sessionId,"session/prompt");let p=d.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),se(W.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw se(W.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await $c(e,m);let y=Oa(a,h,d,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=jd.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.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=jd.parse(u);return c(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=ig.parse(u);return c(f.sessionId,"hydra-acp/prompt/cancel"),yn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=jd.parse(u);return c(f.sessionId,"hydra-acp/session/force_cancel"),yn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=og.parse(u);return c(f.sessionId,"hydra-acp/prompt/update"),yn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=ag.parse(u);c(f.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(f.sessionId);if(!p)throw se(W.SessionNotFound,"not attached to session");return yn(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 se(W.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let v=await e.manager.loadFromDisk(h);if(!v)throw se(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await $c(e,v)}Bc(d,m,m.sessionId);let y=Oa(a,m,d);await m.attach(y,"pending_only"),d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=Fc(m),b=Oc(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...b?{models:b}:{},configOptions:m.buildConfigOptions(),_meta:Lc(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 se(W.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw se(W.SessionNotFound,`session ${p} not found in memory or on disk`);m=await $c(e,k)}Bc(d,m,m.sessionId);let y=Oa(a,m,d),{entries:w}=await m.attach(y,"pending_only");d.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=Fc(m),v=Oc(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:Lc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=SC(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),se(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"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw se(W.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw se(W.InvalidParams,"session/set_mode requires string modeId");let h=yn(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=>se(W.InvalidParams,w),h=f?.sessionId;if(typeof h=="string"&&c(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=yn(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 se(W.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw se(W.MethodNotFound,`Method not found: ${f}`);return c(y,f),yn(e.manager,y).forwardRequest(f,u)})})}async function bC(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw se(W.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 d=a.authMethods??[],c=d.find(p=>p.id===s);if(!c){let p=d.map(h=>h.id);throw se(W.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=c._meta?.type,u=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(v,k)=>{if(!Array.isArray(v))throw se(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${v===null?"null":typeof v}`);for(let A of v)if(typeof A!="string")throw se(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(A)}`);return v},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let v=typeof u.command=="string"?u.command:void 0;m=v!==void 0&&hw.isAbsolute(v)?v:h.command,y=p(u.args,'_meta["terminal-auth"].args')}else{let v=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,k=v!==void 0?p(v.raw,v.label):[];m=h.command,y=[...h.args,...k]}let w={};for(let[v,k]of Object.entries(process.env))typeof k=="string"&&(w[v]=k);Object.assign(w,h.env);let b=pw.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 cr(p,a)}}async function vC(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 uw(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(qd,t).catch(()=>{})}}function Fc(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 Oc(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function SC(n,e){if(!n||typeof n!="object")return{kind:"error",code:W.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:W.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:W.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:W.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Xi(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:W.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 kC(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(W.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw se(W.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw se(W.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return yn(t.manager,r).addTransformer(i),{ok:!0}}async function IC(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 se(W.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(W.InvalidParams,"hydra-acp/attention/set requires string reason");return yn(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function xC(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 se(W.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(W.InvalidParams,"hydra-acp/attention/clear requires string reason");return yn(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function AC(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{[Bt]:Hd(e,t)}}function Lc(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 fa(e.agentMeta,Hd(s,r))}function CC(){return{protocolVersion:1,agentInfo:{name:"hydra",version:be},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:fa(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 RC(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 gw(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 Oa(n,e,t,s,r){return{clientId:r??`cli_${jf(8)}`,connection:n,clientInfo:s}}function Bc(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var Nc=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 TC}from"crypto";import{McpServer as EC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as PC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Dt}from"zod";function qf(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 en(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var yw="Bearer ";function mo(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(yw))return;let t=e.slice(yw.length).trim();return t.length>0?t:void 0}function MC(n){let e=new EC({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:Dt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return en(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:Dt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return en(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:Dt.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:Dt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Dt.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 en(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:Dt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Dt.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 en({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:Dt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Dt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Dt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Dt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Dt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Dt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Dt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Dt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Dt.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 en(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 en(t)}),e}var _C=1e4;function ww(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=MC(a),l=new PC({sessionIdGenerator:()=>TC()});await c.connect(l);let u={server:c,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=mo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),_C)}),h=await Promise.race([c.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(d,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)})}Yd();import{randomUUID as $C}from"crypto";import{McpServer as FC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as OC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as pr}from"zod";function LC(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function BC(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 NC(n){let e=new FC({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:pr.string().min(1).describe("Case-insensitive substring to search for."),limit:pr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:pr.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 en({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:c,entry:l}of i.iterRecallNewestFirst()){let u=qf(l);if(!u)continue;let{kind:f}=u;if(f==="tool_call"&&!r)continue;let p=Zi([l]),h=p.toLowerCase().indexOf(a);if(h<0)continue;let m=LC(f),y=BC(p,h),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(o.push({entryId:c,speaker:m,snippet:y,timestamp:w}),o.length>=s)break}o.sort((c,l)=>c.entryId-l.entryId);let d=o.length>=s;return en({matches:o,total_matched:o.length,truncated:d})}),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:pr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:pr.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 en({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 en({text:"",entry_count:0,truncated:!1});let a=Math.min(t,o-1),d=Math.min(s,o-1),c=a>t||d<s;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await r.sliceRecallHistory(a,d),u=Zi(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:c}}}),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:pr.string().optional(),file_path:pr.string().optional(),limit:pr.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 en({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 d=new Map,c=Math.max(r*4,200);for await(let{entryId:p,entry:h}of i.iterRecallNewestFirst()){let m=qf(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}`,v=d.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(b,v)),p<v.entryId&&(v.entryId=p),typeof w.name=="string"&&w.name.length>0?v.toolName=w.name:v.toolName==="(unnamed)"&&typeof w.title=="string"&&w.title.length>0&&(v.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))v.rawInput[A]===void 0&&(v.rawInput[A]=E);if(Array.isArray(w.locations))for(let A of w.locations){let E=A?.path;typeof E=="string"&&E.length>0&&!v.locations.includes(E)&&v.locations.push(E)}if(typeof w.status=="string"&&v.status==="in_progress"&&(v.status=w.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt)),d.size>=c)break}let l=[...d.keys()].sort((p,h)=>d.get(p).entryId-d.get(h).entryId),u=[];for(let p of l){let h=d.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 v of w){let k=h.rawInput[v];if(typeof k=="string"&&k.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let v of h.locations)if(v.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 en({calls:u,truncated:f})}),e}var DC=1e4;function bw(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=NC(a),l=new OC({sessionIdGenerator:()=>$C()});await c.connect(l);let u={server:c,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=mo(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await s(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),DC)}),h=await Promise.race([c.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 Dc=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 JC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as VC}from"crypto";import{Server as HC}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as UC,ListToolsRequestSchema as jC}from"@modelcontextprotocol/sdk/types.js";function vw(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new HC({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(jC,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let d=await s.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(UC,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,u=WC(l,d.sendNotification);try{let f=await r(),p=await zC(e.connection,n,c,a.params.arguments??{},f);return KC(p,c)}catch(f){return Wf(f instanceof Error?f.message:String(f))}finally{u()}}),i}var qC=15e3;function WC(n,e,t=qC){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 zC(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function KC(n,e){if(n===null||typeof n!="object")return Wf(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Wf(`extension ${e} omitted content array`)}function Wf(n){return{content:[{type:"text",text:n}],isError:!0}}var GC=1e4;function Sw(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=vw(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),GC)}),_=await Promise.race([k.sessionReady.catch(()=>{}),E]);if(A!==void 0&&clearTimeout(A),_===void 0)throw new Error("session not ready");return _.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 _=[];for(let H of E){if(!H||typeof H!="object")continue;let P=H;if(typeof P.name!="string"||P.name.length===0||typeof P.description!="string"||P.inputSchema===null||typeof P.inputSchema!="object")continue;let $={name:P.name,description:P.description,inputSchema:P.inputSchema};P.outputSchema!==null&&typeof P.outputSchema=="object"&&($.outputSchema=P.outputSchema),_.push($)}return _}}),v=new JC({sessionIdGenerator:()=>VC()});return await b.connect(v),f.set(u,{server:b,transport:v}),v}async function d(l,u){let f=mo(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 c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)}),{notifyToolListChanged:o}}async function Rw(n,e){nR(n);let t=n.daemon.tls?await ws.readFile(st(n.daemon.tls.key)):void 0,s=n.daemon.tls?await ws.readFile(st(n.daemon.tls.cert)):void 0;await ws.mkdir(L.home(),{recursive:!0});let{stream:r,fileStream:i}=await eR(n.daemon.logLevel),o=YC({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(QC,{options:{handleProtocols:Mm}}),Fu(ee=>{o.log.info(ee)}),Bu(ee=>{o.log.info(ee)});let a=await wc.load(),d=new Ic,c=new kc,l=new Sc([new bc(e),new vc(a),c]),u=Ty({validator:l});o.addHook("onRequest",async(ee,Ee)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await u(ee,Ee)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{d.sweepExpired()},300*1e3);p.unref();let h=new Bd(n,{onFetched:()=>{by(h,b)}});Mf(ee=>o.log.info(ee));let m={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},y=ee=>or.spawn({...ee,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Om(n.compressToolContent);let w=new gc,b=new cc(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}),v=new hc(nm(n),void 0,{tokenRegistry:c}),k=new mc(sm(n),void 0,{tokenRegistry:c});Zy(o,be,lr(n));let A=new Nc,E=new Dc,_,H=()=>{if(_!==void 0)return _;let ee=o.server.address();return _=`http://127.0.0.1:${ee&&typeof ee=="object"?ee.port:n.daemon.port}`,_};Qy(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}),Xy(o,h,b,{npmRegistry:n.npmRegistry}),ew(o,v),tw(o,k),nw(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]}),lw(o,{store:a,rateLimiter:d}),ww(o,A),bw(o,A);let P=Sw(o,A,E);mw(o,{validator:l,manager:b,defaultAgent:n.defaultAgent,processRegistry:c,onExtensionVersion:(ee,Ee)=>v.reportVersion(ee,Ee),onTransformerVersion:(ee,Ee)=>k.reportVersion(ee,Ee),transformers:k,extensionCommands:w,mcpTokenRegistry:A,extensionMcp:E,extensionMcpControls:P,getDaemonOrigin:H,registry:h});let $=!!n.daemon.tls;await o.listen({host:$?"127.0.0.1":n.daemon.host,port:$?0:n.daemon.port});let B=o.server.address(),N=B&&typeof B=="object"?B.port:n.daemon.port,U,G=n.daemon.host,X=N;if($&&t&&s){U=tR({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=U.address();ee&&typeof ee=="object"&&(X=ee.port)}await ws.mkdir(L.home(),{recursive:!0}),await fm({pid:process.pid,host:G,port:X,loopbackPort:N,startedAt:new Date().toISOString()});let Y={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:L.home()};v.setContext(Y),k.setContext(Y),await v.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 pe=n.daemon.agentSyncIntervalMinutes*60*1e3,nt=pe>0?vy({registry:h,manager:b,intervalMs:pe,logger:m}):void 0,qs=n.daemon.sessionGcIntervalMinutes*60*1e3,We=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,It=qs>0?Sy({manager:b,intervalMs:qs,maxAgeMs:We,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:v,transformers:k,mcpTokenRegistry:A,extensionMcp:E,processRegistry:c,shutdown:async()=>{It&&It(),nt&&nt(),clearInterval(f),clearInterval(p);let ee=async(Ee,Je)=>{try{await Je()}catch(Pt){o.log.warn(`shutdown step ${Ee} failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>v.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()),Fu(null),Bu(null),Mf(null),U&&await ee("tlsTerminator.close",()=>new Promise(Ee=>U.close(()=>Ee()))),await ee("app.close",()=>o.close());try{xw.unlinkSync(L.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}var Iw=20;async function ZC(n,e){let t=go.dirname(n),s=go.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await ws.readdir(t)}catch{return}let o=[];for(let d of i){let c=d.match(r);c&&o.push({name:d,n:Number(c[1])})}if(o.length<=e)return;o.sort((d,c)=>d.n-c.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(d=>ws.unlink(go.join(t,d.name))))}async function eR(n){await ZC(L.logFile(),Iw);let e=await XC({file:L.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:Iw,removeOtherLogFiles:!0}}),t=kw.destination(2);return{stream:kw.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function tR(n){let e=Cw.createServer(n.tlsOptions,t=>{let s=Aw.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 nR(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.`)}ni();gn();Ma();La();async function _w(n={}){let e=await xe(),t=await ra();if(await Hc(e)){let r=await bo();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
333
333
|
`);return}if(Fi(n,"foreground")){process.title="hydra-acp-daemon";let r=await Rw(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
334
334
|
`);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
|
|
335
335
|
`),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
|
|
@@ -344,20 +344,20 @@ ${rf}`;return Kg(n,s,jg)}function gA(n){if(!n||typeof n!="object")return"";let e
|
|
|
344
344
|
`),process.exit(1)}await pR(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
|
|
345
345
|
`),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
|
|
346
346
|
`);if(Uc(),await jc(n),await Hc(n)){let t=await bo();process.stdout.write(`Daemon restarted on ${n.daemon.host}:${n.daemon.port}`+(t?` pid=${t.pid}`:"")+`
|
|
347
|
-
`)}}async function pR(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!En(n))return!0;await fR(50)}return!1}async function Ow(n){await wo(
|
|
347
|
+
`)}}async function pR(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!En(n))return!0;await fR(50)}return!1}async function Ow(n){await wo(L.currentLogFile(),n,"No daemon log file (daemon never ran?)")}async function Lw(){let n=await bo();if(!n){process.stdout.write(`Daemon: not running
|
|
348
348
|
`),process.stdout.write(`CLI version: ${be}
|
|
349
349
|
`);return}let e=En(n.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${n.pid} host=${n.host} port=${n.port} started=${n.startedAt}
|
|
350
|
-
`);let t,s;if(e)try{let o=await xe();t=await ti(o),s=
|
|
350
|
+
`);let t,s;if(e)try{let o=await xe();t=await ti(o),s=lr(o)}catch{}if(!t||t.version===void 0){process.stdout.write(`CLI version: ${be}
|
|
351
351
|
`),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
|
|
352
352
|
`);return}let r=t.version===be,i=t.configDigest!==void 0&&s!==void 0&&t.configDigest===s;if(r&&i){process.stdout.write(`Version: ${be}
|
|
353
353
|
`);return}process.stdout.write(`CLI version: ${be}
|
|
354
354
|
`),process.stdout.write(`Daemon version: ${t.version}
|
|
355
|
-
`),r||process.stdout.write(Mw.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Mw.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function bo(){return ls()}et();
|
|
355
|
+
`),r||process.stdout.write(Mw.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Mw.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function bo(){return ls()}et();Ms();mr();Jr();oa();ps();Na();Zr();import*as _n from"fs/promises";import*as Gw from"os";import*as $n from"path";Yc();async function Yw(n={}){let e=await xe(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",r=(await Le(`/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)+`
|
|
356
356
|
`);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.
|
|
357
357
|
`);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
|
|
358
358
|
`);return}process.stdout.write(`No active sessions.
|
|
359
|
-
`);return}let d=a.slice().sort((y,w)=>{let b=(w.status==="warm"?1:0)-(y.status==="warm"?1:0);return b!==0?b:String(w.updatedAt||"").localeCompare(String(y.updatedAt||""))}),c=d,l=0;if(!n.all){let y=d.filter(k=>k.status!=="cold").length,w=e.sessionListColdLimit,b=d.slice(y,y+w),v=d.length-y-b.length;c=[...d.slice(0,y),...b],l=v}let
|
|
360
|
-
`);for(let y of
|
|
359
|
+
`);return}let d=a.slice().sort((y,w)=>{let b=(w.status==="warm"?1:0)-(y.status==="warm"?1:0);return b!==0?b:String(w.updatedAt||"").localeCompare(String(y.updatedAt||""))}),c=d,l=0;if(!n.all){let y=d.filter(k=>k.status!=="cold").length,w=e.sessionListColdLimit,b=d.slice(y,y+w),v=d.length-y-b.length;c=[...d.slice(0,y),...b],l=v}let u=Date.now(),f=c.map(y=>Ao(y,u)),p={columns:n.columns??e.tui.sessionColumns??Io,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Co(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(gr(xo,h,m,p)+`
|
|
360
|
+
`);for(let y of f)process.stdout.write(gr(y,h,m,p)+`
|
|
361
361
|
`);l>0&&process.stdout.write(`
|
|
362
362
|
... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
|
|
363
363
|
`)}async function Qw(n){n||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
|
|
@@ -377,8 +377,8 @@ ${rf}`;return Kg(n,s,jg)}function gA(n){if(!n||typeof n!="object")return"";let e
|
|
|
377
377
|
`)||process.stdout.write(`
|
|
378
378
|
`);return}let d=e==="."?MR(o,n):e;await _n.mkdir($n.dirname($n.resolve(d)),{recursive:!0}),await _n.writeFile(d,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${d}
|
|
379
379
|
`)}async function tb(n,e,t={}){n||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools] [--thoughts]
|
|
380
|
-
`),process.exit(2));let s=t.includeTools??!1,r=t.includeThoughts??!1,i,o,a=await CR(n);if(a!==null){let c=RR(a.raw);i=Rc(c,{includeTools:s,includeThoughts:r});let l=new Date().toISOString().replace(/[:.]/g,"-");o=`${$n.basename(n,$n.extname(n))}-${l}.md`}else{let c=await jr(),l=await vo(),
|
|
381
|
-
`),process.exit(1)}i=await
|
|
380
|
+
`),process.exit(2));let s=t.includeTools??!1,r=t.includeThoughts??!1,i,o,a=await CR(n);if(a!==null){let c=RR(a.raw);i=Rc(c,{includeTools:s,includeThoughts:r});let l=new Date().toISOString().replace(/[:.]/g,"-");o=`${$n.basename(n,$n.extname(n))}-${l}.md`}else{let c=await jr(),l=await vo(),u=new URL(`${l}/v1/sessions/${encodeURIComponent(n)}/transcript`);s&&u.searchParams.set("tools","1"),r&&u.searchParams.set("thoughts","1");let f=await fetch(u,{headers:{Authorization:`Bearer ${c}`}});if(!f.ok){let h=await f.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${f.status}: ${h}
|
|
381
|
+
`),process.exit(1)}i=await f.text();let p=new Date().toISOString().replace(/[:.]/g,"-");o=`hydra-${n}-${p}.md`}if(!e){process.stdout.write(i),i.endsWith(`
|
|
382
382
|
`)||process.stdout.write(`
|
|
383
383
|
`);return}let d=e==="."?o:e;await _n.mkdir($n.dirname($n.resolve(d)),{recursive:!0}),await _n.writeFile(d,i,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${d}
|
|
384
384
|
`)}async function CR(n){try{if(!(await _n.stat(n)).isFile())return null}catch{return null}let e=await _n.readFile(n,"utf8");try{return{raw:JSON.parse(e)}}catch(t){process.stderr.write(`Failed to parse bundle file: ${t.message}
|
|
@@ -392,8 +392,8 @@ ${rf}`;return Kg(n,s,jg)}function gA(n){if(!n||typeof n!="object")return"";let e
|
|
|
392
392
|
`),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
|
|
393
393
|
`:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
|
|
394
394
|
`)}function TR(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 ER(n,e){let t;try{t=qn(n)}catch(c){process.stderr.write(`Not a valid bundle: ${c.message}
|
|
395
|
-
`),process.exit(1)}let s=TR(t),r=Ao(s),i={columns:Gc,cwdMaxWidth:e},o=Co([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(
|
|
396
|
-
`),process.stdout.write(
|
|
395
|
+
`),process.exit(1)}let s=TR(t),r=Ao(s),i={columns:Gc,cwdMaxWidth:e},o=Co([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(gr(xo,o,a,i)+`
|
|
396
|
+
`),process.stdout.write(gr(r,o,a,i)+`
|
|
397
397
|
`);let d=t.session.upstreamSessionId??"-";process.stdout.write(`
|
|
398
398
|
lineage: ${t.session.lineageId}
|
|
399
399
|
exported: ${t.exportedAt} from ${t.exportedFrom.machine} (hydra ${t.exportedFrom.hydraVersion})
|
|
@@ -401,45 +401,45 @@ origin session: ${t.session.sessionId}
|
|
|
401
401
|
origin upstream: ${d}
|
|
402
402
|
history entries: ${t.history.length}`+(t.promptHistory?`, prompt history: ${t.promptHistory.length}
|
|
403
403
|
`:`
|
|
404
|
-
`))}async function PR(){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 MR(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 sb(n,e={}){let t=await xe(),s;if(n!==void 0&&n.length>0)s=n;else{let c=await
|
|
405
|
-
`),process.exit(1)),s=
|
|
404
|
+
`))}async function PR(){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 MR(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 sb(n,e={}){let t=await xe(),s;if(n!==void 0&&n.length>0)s=n;else{let c=await Wt(t),l=e.cwd?$n.resolve(e.cwd):process.cwd(),u=await Wn(c,{cwd:l,all:!0}),f=Jc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
|
|
405
|
+
`),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=_R(e.host,t),a=ut(s),d=cm({host:r,port:i,sessionId:a});process.stdout.write(d+`
|
|
406
406
|
`),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.
|
|
407
|
-
`)}function _R(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Vw(n,Un);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Vw(e.daemon.publicHost,Un);return{host:t,port:s,isFallback:!1}}return $R(e.daemon.host)?{host:FR(),port:e.daemon.port,isFallback:!1}:Wr(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 $R(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function FR(){let n=Gw.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Vw(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}}up();Yc();ap();et();we();La();
|
|
408
|
-
`);return}let u
|
|
409
|
-
`);for(let y of
|
|
410
|
-
`);for(let y of
|
|
407
|
+
`)}function _R(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Vw(n,Un);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Vw(e.daemon.publicHost,Un);return{host:t,port:s,isFallback:!1}}return $R(e.daemon.host)?{host:FR(),port:e.daemon.port,isFallback:!1}:Wr(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 $R(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function FR(){let n=Gw.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Vw(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}}up();Yc();ap();et();we();La();mr();var yT={extension:{singular:"extension",plural:"extensions",logFile:n=>L.extensionLogFile(n)},transformer:{singular:"transformer",plural:"transformers",logFile:n=>L.transformerLogFile(n)}};function nl(n){if(n&&typeof n=="object"&&"error"in n){let e=n.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function To(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function sl(n){let e=yT[n],t=`/v1/${e.plural}`;async function s(){let u=(await Le(t,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
|
|
408
|
+
`);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?So(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:To(p.name,f.map(y=>y.name)),status:To(p.status,f.map(y=>y.status)),version:To(p.version,f.map(y=>y.version)),pid:To(p.pid,f.map(y=>y.pid)),restarts:To(p.restarts,f.map(y=>y.restarts)),started:To(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)+`
|
|
409
|
+
`);for(let y of f)process.stdout.write(m(y)+`
|
|
410
|
+
`);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
|
|
411
411
|
`)}async function r(c,l){if(!c){process.stderr.write(`Usage: hydra-acp ${e.plural} add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
|
|
412
412
|
`),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(c)){process.stderr.write(`Invalid ${e.singular} name '${c}': must match [A-Za-z0-9._-]+
|
|
413
|
-
`),process.exit(2);return}await xe();let
|
|
414
|
-
`),process.exit(1);return}let h=zc(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[c]=y,await Kf(
|
|
413
|
+
`),process.exit(2);return}await xe();let u=await ko(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[c]){process.stderr.write(`${vb(e.singular)} '${c}' already exists in config.
|
|
414
|
+
`),process.exit(1);return}let h=zc(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[c]=y,await Kf(u),process.stdout.write(`Added ${e.singular} '${c}' to ${L.config()}
|
|
415
415
|
`);let w={name:c,...y};try{let b=await Le(t,{method:"POST",body:w,rethrowNetworkError:!0});if(b.ok){let v=b.body,k=v.pid!=null?` pid=${v.pid}`:"";process.stdout.write(`${c}: ${v.status}${k}
|
|
416
416
|
`);return}process.stderr.write(`Daemon refused to register ${c} (HTTP ${b.status}${nl(b.body)}). Restart the daemon to apply.
|
|
417
417
|
`)}catch{}}async function i(c){if(!c){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
|
|
418
|
-
`),process.exit(2);return}await xe();let l=await ko(),
|
|
419
|
-
`),process.exit(1);return}delete
|
|
418
|
+
`),process.exit(2);return}await xe();let l=await ko(),u=l,f=u[e.plural]??{};if(!f[c]){process.stderr.write(`${vb(e.singular)} '${c}' not found in config.
|
|
419
|
+
`),process.exit(1);return}delete f[c],u[e.plural]=f,await Kf(l),process.stdout.write(`Removed ${e.singular} '${c}' from ${L.config()}
|
|
420
420
|
`);try{let p=await Le(`${t}/${encodeURIComponent(c)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${c}: stopped
|
|
421
421
|
`);return}process.stderr.write(`Daemon refused to unregister ${c} (HTTP ${p.status}${nl(p.body)}).
|
|
422
422
|
`)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
|
|
423
423
|
`)}}async function o(c,l){if(!c){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
|
|
424
|
-
`),process.exit(2);return}if(c==="all"){await a(l);return}let
|
|
425
|
-
`),process.exit(1);return}let u
|
|
424
|
+
`),process.exit(2);return}if(c==="all"){await a(l);return}let u=await Le(`${t}/${encodeURIComponent(c)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${nl(u.body)}
|
|
425
|
+
`),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${c}: ${f.status}${p}
|
|
426
426
|
`)}async function a(c){let p=((await Le(t,{expectStatus:200})).body[e.plural]??[]).filter(m=>c==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=c==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${c}: ${m}.
|
|
427
427
|
`);return}let h=0;for(let m of p)try{let y=await Le(`${t}/${encodeURIComponent(m.name)}/${c}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${nl(y.body)}
|
|
428
428
|
`),h+=1;continue}let w=y.body,b=w.pid!=null?` pid=${w.pid}`:"";process.stdout.write(`${m.name}: ${w.status}${b}
|
|
429
429
|
`)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
|
|
430
|
-
`),h+=1}h>0&&process.exit(1)}async function d(c){let{name:l,rest:
|
|
431
|
-
`),process.exit(2);return}let
|
|
432
|
-
`),{exitCode:0}):
|
|
433
|
-
`),{exitCode:1}):(process.stderr.write(`auth process exited with code ${
|
|
430
|
+
`),h+=1}h>0&&process.exit(1)}async function d(c){let{name:l,rest:u}=qc(c);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
|
|
431
|
+
`),process.exit(2);return}let f=e.logFile(l);await wo(f,u,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:c=>o(c,"start"),stop:c=>o(c,"stop"),restart:c=>o(c,"restart"),logs:d}}function vb(n){return n.charAt(0).toUpperCase()+n.slice(1)}var ai=sl("extension"),Sb=ai.list,kb=ai.add,Ib=ai.remove,xb=ai.start,Ab=ai.stop,Cb=ai.restart,Rb=ai.logs;var di=sl("transformer"),Tb=di.list,Eb=di.add,Pb=di.remove,Mb=di.start,_b=di.stop,$b=di.restart,Fb=di.logs;cl();Ba();ho();Yr();et();Jr();ni();Nt();gn();Dd();Ap();import FT from"os";import{spawn as OT}from"child_process";async function LT({conn:n,agentId:e,authMethods:t,method:s,spawn:r}){let i;try{let d=await n.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(d?.authMethods)?d.authMethods:[]}catch{i=void 0}let o=d=>new Promise(c=>{let l=r(d.command,d.args,{stdio:"inherit",env:d.env,cwd:d.cwd});l.on("exit",u=>{c({exitCode:u})}),l.on("error",()=>{c({exitCode:-1})})}),a=async(d,c)=>{let l=await BT(d,s),u=await xp(l,{authenticate:f=>n.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:c}}}),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
|
|
432
|
+
`),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
|
|
433
|
+
`),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
|
|
434
434
|
`),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await n.request("session/new",{cwd:FT.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
|
|
435
|
-
`),{exitCode:0}}catch(d){if(d instanceof Error&&"code"in d&&d.code===W.AuthRequired){let c=d.data,l=c?._meta?.["hydra-acp"]?.authMethods??t,
|
|
435
|
+
`),{exitCode:0}}catch(d){if(d instanceof Error&&"code"in d&&d.code===W.AuthRequired){let c=d.data,l=c?._meta?.["hydra-acp"]?.authMethods??t,u=c?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw d}}async function BT(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}
|
|
436
436
|
`),process.exit(2)}if(n.length===1)return n[0];if(process.stdin.isTTY===!0){let s=n.map((d,c)=>`${c+1}) ${d.id} \u2014 ${d.name??d.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
|
|
437
437
|
${s.join(`
|
|
438
438
|
`)}
|
|
439
439
|
`);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}
|
|
440
440
|
`),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})
|
|
441
441
|
`),process.exit(2)}async function sv(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
|
|
442
|
-
`),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(cl(),Db)),s=await t(n,"hydra agent auth"),r=await xe(),i=await
|
|
442
|
+
`),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(cl(),Db)),s=await t(n,"hydra agent auth"),r=await xe(),i=await Wt(r);await hr(r,i);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await si(i.wsUrl,o),d=ys(a),c=new Zt(d);try{await c.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:be}})}catch{}let l;try{l=await LT({conn:c,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:OT})}finally{a.close()}process.exit(l.exitCode)}La();vu();mr();async function rv(n){let e=Fi(n,"force");if(await Mc()&&!e){let r=await Hi("Current password: ");await _c(r)||(process.stderr.write(`Wrong password.
|
|
443
443
|
`),process.exit(1))}let t=await Hi("New password: ");t.length===0&&(process.stderr.write(`Password must not be empty.
|
|
444
444
|
`),process.exit(2));let s=await Hi("Confirm new password: ");t!==s&&(process.stderr.write(`Passwords did not match.
|
|
445
445
|
`),process.exit(1)),await cw(t),process.stdout.write(`Password set.
|
|
@@ -450,26 +450,26 @@ ${s.join(`
|
|
|
450
450
|
`),process.exit(2));let e=await Le(`/v1/auth/sessions/${n}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${n}
|
|
451
451
|
`);return}e.status===404&&(process.stderr.write(`No session token with id ${n}
|
|
452
452
|
`),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
|
|
453
|
-
`),process.exit(1)}function hl(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as
|
|
453
|
+
`),process.exit(1)}function hl(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as vr from"fs";et();Jr();ni();Cp();Nt();var ml=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Tp(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(Rp(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(!Rp(e)&&!Tp(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(Rp(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(!Tp(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=hn(i),a=o.upstreamSessionId,d=o.agentId,c="";(t.kind==="new"||t.kind==="load")&&(c=t.data.cwd);let l=o.cwd??c;!a||!d||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:d,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let 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 Rp(n){return"method"in n&&"id"in n&&n.id!==void 0}function Tp(n){return!("method"in n)&&"id"in n}yl();gn();we();aa();import{writeFileSync as qT}from"fs";var WT=n=>{qT("/proc/self/comm",n)};function Oo(n,e={}){if(process.title=n,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??WT;try{s(e.commName??cs())}catch{}}function Lo(n,e=cs()){return n.length===0?e:`${e} ${n.join(" ")}`}async function bl(n){Oo(Lo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await xe(),t=n.target??await Wt(e);t.isLocal&&!n.target&&await hr(e,t);let s=new ml,r=Wd(process.stdin,process.stdout),i=t.isLocal?async()=>(await Wt(await xe())).wsUrl:t.wsUrl,o=["acp.v1",`hydra-acp-token.${t.token}`],a=new Fo({url:i,subprotocols:o,onConnect:async d=>{if(d)return;s.clearPending(),await YT(s,r);let c=s.list();if(c.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${c.length} session(s)
|
|
454
454
|
`);for(let l of c)await QT(a,l,s.lastMessageId(l.sessionId))}}});zT({opts:n,upstream:a,downstream:r,tracker:s}),a.onClose(d=>{d&&process.stderr.write(`hydra-acp: ${d.message}
|
|
455
455
|
`),r.close(),process.exit(d?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(c=>setTimeout(c,1e3))]),process.exit(0)))()}),await a.start()}function zT({opts:n,upstream:e,downstream:t,tracker:s}){e.onMessage(i=>{if(pv("daemon\u2192client",i),s.observeFromServer(i),n.dangerouslySkipPermissions===!0&&tE(i)){e.send({jsonrpc:"2.0",id:i.id,result:hi(i.params)});return}KT(i,s,t),t.send(i)});let r={name:n.name,used:!1};t.onMessage(i=>{if(pv("client\u2192daemon",i),s.observeFromClient(i),ZT(i)){e.send(eE(i));return}if(XT(i)){if(n.sessionId){e.send(nE(i,n.sessionId));return}let o=i;n.agentId&&(o=wl(o,{agentId:n.agentId})),n.agentArgs&&n.agentArgs.length>0&&(o=wl(o,{agentArgs:n.agentArgs})),r.name&&!r.used&&(o=wl(o,{title:r.name}),r.used=!0),n.model&&(o=wl(o,{model:n.model})),e.send(o);return}e.send(i)})}function KT(n,e,t){let s=JT(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=GT(s);t.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function JT(n){if(!VT(n))return;let t=(n.params??{}).update;if(!(!t||typeof t!="object"||t.sessionUpdate!=="permission_resolved"))return t}function VT(n){return"method"in n&&n.method==="session/update"&&!("id"in n&&n.id!==void 0)}function GT(n){if(n.outcome&&typeof n.outcome=="object")return n.outcome;if(typeof n.chosenOptionId=="string")return{kind:"selected",optionId:n.chosenOptionId}}async function YT(n,e){let t=n.takePendingPermissions();if(t.length!==0){process.stderr.write(`hydra-acp: cancelling ${t.length} pending permission request(s)
|
|
456
456
|
`);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 QT(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}
|
|
457
457
|
`)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
|
|
458
|
-
`)}}function XT(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function ZT(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function eE(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:be}}}}function tE(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function nE(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var sE=25*1024*1024,fv=!1,mi=null;function pv(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!fv){fv=!0;try{mi=
|
|
459
|
-
`;
|
|
458
|
+
`)}}function XT(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function ZT(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function eE(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:be}}}}function tE(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function nE(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var sE=25*1024*1024,fv=!1,mi=null;function pv(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!fv){fv=!0;try{mi=L.shimWireLogFile(),vr.mkdirSync(L.home(),{recursive:!0});let t=vr.statSync(mi,{throwIfNoEntry:!1});t&&t.size>sE&&vr.renameSync(mi,`${mi}.1`)}catch{mi=null}}if(mi)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
|
|
459
|
+
`;vr.appendFile(mi,t,()=>{})}catch{}}}function wl(n,e){let t=n.params??{},s=t._meta??{},r=s["hydra-acp"]??{};return{...n,params:{...t,_meta:{...s,"hydra-acp":{...r,...e}}}}}Yr();ho();Ba();et();Jr();ni();ur();Nt();gn();yl();import{mkdtempSync as hE,rmSync as mE}from"fs";import{tmpdir as gE}from"os";import{join as yE}from"path";function hv(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())}}}oi();import rE from"chalk";import iE from"strip-ansi";var vl=new rE.Instance({level:3});function mv(n,e){if(n.length===0)return"";let t=br(n);if(t.length===0)return"";let s=[];for(let i of t)s.push(oE(i,e));let r=s.join(`
|
|
460
460
|
`);return r.endsWith(`
|
|
461
461
|
`)||(r+=`
|
|
462
462
|
`),r}function oE(n,e){let t=fE(n.body,e);return e==="ansi"?t=pE(t,n.bodyStyle):t=iE(t),t}var aE="\x1B[1m",dE="\x1B[96m",cE="\x1B[93m",lE="\x1B[0m",uE="\0";function fE(n,e){let t=n.replace(/\^\^/g,uE);return e==="ansi"&&(t=t.replace(/\^\+/g,aE).replace(/\^C/g,dE).replace(/\^Y/g,cE).replace(/\^:/g,lE)),t=t.replace(/\^[+\-:CcKY]/g,""),t=t.replace(/\x00/g,"^"),t}function pE(n,e){if(n.length===0||e===void 0)return n;switch(e){case"heading-1":return vl.bold.yellowBright(n);case"heading-2":return vl.bold.cyanBright(n);case"heading-3":return vl.bold(n);case"dim":return vl.dim(n);default:return n}}var wE=1*1024*1024,gv="mcp__hydra-acp-stdin__";function yv(n,e){return{sessionId:n,prompt:e,_meta:{[Bt]:{ancillary:!0}}}}function bE(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 vE(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(gv))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(gv))}async function wv(n){if(Oo(Lo(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.
|
|
463
|
-
`),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let d=hE(yE(gE(),"hydra-cat-"));n.cwd=d,n.detach||process.once("exit",()=>{try{mE(d,{recursive:!0,force:!0})}catch{}})}let e=await xe(),t=n.target??await
|
|
464
|
-
`:"";y(pe+
|
|
465
|
-
`),
|
|
466
|
-
`);return}b()}},A=0,E,
|
|
467
|
-
`),A=1),H||(H=!0,b(),E({exitCode:A}))});let
|
|
468
|
-
`),A=1,N=!0,!B
|
|
469
|
-
`),A=1,N=!0,!B
|
|
470
|
-
`),A=1,N=!0,!B
|
|
471
|
-
`),A=1,N=!0,!B
|
|
472
|
-
`)})},y=async()=>{c="inline";let b=Buffer.concat(f
|
|
463
|
+
`),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let d=hE(yE(gE(),"hydra-cat-"));n.cwd=d,n.detach||process.once("exit",()=>{try{mE(d,{recursive:!0,force:!0})}catch{}})}let e=await xe(),t=n.target??await Wt(e);t.isLocal&&!n.target&&await hr(e,t);let s=["acp.v1",`hydra-acp-token.${t.token}`],r=await si(t.wsUrl,s),i=ys(r),o=new Zt(i),a=await kE({conn:o,opts:n,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:d=>process.stdout.write(d),stderr:d=>{process.stderr.write(d)},streamClient:SE(t.baseUrl,t.token)});process.exit(a.exitCode)}function SE(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 kE(n){let{conn:e,opts:t,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=n,d=i?"ansi":"plain",c=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 Y=>t.dangerouslySkipPermissions?hi(Y):vE(Y)?hi(Y):cv(Y));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Qr,version:be}})}catch{}let u=await AE(e,t,l),f=!1,p=!0,h="",m=0,y=Y=>{Y.length!==0&&(o(Y),p=Y.charCodeAt(Y.length-1)===10,f=!0)},w=()=>{if(c||h.length===0)return;let Y=mv(h,d);if(h="",Y.length===0)return;let pe=m>0?`
|
|
464
|
+
`:"";y(pe+Y),m+=1},b=()=>{w(),f&&!p&&y(`
|
|
465
|
+
`),f=!1};e.onNotification("session/update",Y=>{let pe=Y?.update,nt=gs(pe,{cwd:t.cwd});if(nt){if(nt.kind==="agent-text"){c?y(nt.text):h+=nt.text;return}if(nt.kind==="turn-complete"){b();return}switch(nt.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 v=!1,k=async Y=>{let pe=[];if(t.prompt&&!v&&pe.push({type:"text",text:t.prompt}),Y.length>0&&pe.push({type:"text",text:Y}),pe.length!==0){try{await e.request("session/prompt",yv(u,pe)),v=!0}catch(nt){a(`hydra-acp cat: prompt failed: ${nt.message}
|
|
466
|
+
`);return}b()}},A=0,E,_=new Promise(Y=>{E=Y}),H=!1,P=async Y=>{H||(H=!0,b(),t.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(nt=>setTimeout(nt,500))]),await e.close().catch(()=>{}),E({exitCode:Y}))};e.onClose(Y=>{Y&&(a(`hydra-acp cat: ${Y.message}
|
|
467
|
+
`),A=1),H||(H=!0,b(),E({exitCode:A}))});let $=[],B=!1,N=!1,U=async()=>{if(!B){B=!0;try{for(;$.length>0;){let Y=$.shift();if(Y===void 0)break;await k(Y)}}finally{B=!1,N&&$.length===0&&await P(A)}}};if(r&&!t.sessionId)return t.prompt&&await k(""),await P(0),_;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),IE({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!B&&$.length===0&&P(A)},onError:Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
|
|
468
|
+
`),A=1,N=!0,!B&&$.length===0&&P(A)},onPromptFailed:Y=>{a(`hydra-acp cat: ${Y.message}
|
|
469
|
+
`),A=1,N=!0,!B&&$.length===0&&P(A)}}),_;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),t.follow===!0||r&&!!t.sessionId){let Y=hv({scheduleFlushCheck:pe=>{let nt=setImmediate(pe);return()=>clearImmediate(nt)},onChunk:pe=>{$.push(pe),U()}});return s.on("data",pe=>{Y.feed(typeof pe=="string"?pe:pe.toString("utf8"))}),s.on("end",()=>{Y.eof(),N=!0,!B&&$.length===0&&P(A)}),s.on("error",pe=>{a(`hydra-acp cat: stdin error: ${pe.message}
|
|
470
|
+
`),A=1,N=!0,!B&&$.length===0&&P(A)}),_}let X="";return s.on("data",Y=>{X+=typeof Y=="string"?Y:Y.toString("utf8")}),s.on("end",()=>{N=!0,X.length>0&&$.push(X),U()}),s.on("error",Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
|
|
471
|
+
`),A=1,N=!0,!B&&$.length===0&&P(A)}),_}function IE(n){let{conn:e,streamClient:t,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=n,d=r.streamThreshold??wE,c="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(b,v)=>{let k=b.toString("base64");h=h.then(()=>t.write(s,k,v)).catch(A=>{o(`hydra-acp cat: stdin write failed: ${A.message}
|
|
472
|
+
`)})},y=async()=>{c="inline";let b=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(b)}catch(v){n.onPromptFailed(v);return}n.onEof()},w=async()=>{c="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),c="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let v=xE(r.prompt,b.capacityBytes);e.request("session/prompt",yv(s,[{type:"text",text:v}])).catch(A=>{n.onPromptFailed(new Error(`prompt failed: ${A.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),n.onEof()})};i.on("data",b=>{let v=typeof b=="string"?Buffer.from(b,"utf8"):b;if(c==="undecided"){u.push(v),f+=v.length,f>d&&w();return}if(c==="pivoting"){u.push(v),f+=v.length;return}if(c==="file"){m(v,!1);return}u.push(v),f+=v.length}),i.on("end",()=>{if(p=!0,c==="undecided"){y();return}if(c==="pivoting"){l=!0;return}c==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",n.onError)}function xE(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:
|
|
473
473
|
- \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
|
|
474
474
|
- \`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.
|
|
475
475
|
- \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
|
|
@@ -495,8 +495,8 @@ Use those tools to inspect the piped input and report what's there. Start with \
|
|
|
495
495
|
`),process.exit(1)}process.stdout.write(`unset ${n}
|
|
496
496
|
`)}async function xv(n){let e=await xe(),t=n?bv(e,Sl(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
|
|
497
497
|
`),process.exit(1)),process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
498
|
-
`)}function Av(){process.stdout.write(`${
|
|
499
|
-
`)}et();
|
|
498
|
+
`)}function Av(){process.stdout.write(`${L.config()}
|
|
499
|
+
`)}et();Ms();ni();gn();mr();async function Tv(n={}){let{report:e,configLoaded:t}=await RE();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
500
500
|
`);return}process.stdout.write(`CLI: ${e.cli}
|
|
501
501
|
`),t&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
|
|
502
502
|
`),e.daemonReachable&&(Cv("Extensions",e.extensions),Cv("Transformers",e.transformers)))}function Cv(n,e){if(process.stdout.write(`
|
|
@@ -505,15 +505,15 @@ ${n}:
|
|
|
505
505
|
`);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}
|
|
506
506
|
`)}}async function RE(){let n={cli:be,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await xe()}catch{return{report:n,configLoaded:!1}}let t=await ti(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 jr()}catch{return{report:n,configLoaded:!0}}let r=await vo(),i={Authorization:`Bearer ${s}`};return n.extensions=await Rv(`${r}/v1/extensions`,i,"extensions"),n.transformers=await Rv(`${r}/v1/transformers`,i,"transformers"),{report:n,configLoaded:!0}}async function Rv(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 TE}from"child_process";import{accessSync as EE,constants as PE,statSync as ME}from"fs";import{delimiter as _E,join as $E}from"path";var FE=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function OE(n){return FE.has(n)}function LE(n){for(let e of n)if(e!==void 0&&!e.startsWith("-"))return e}function BE(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 NE(n){try{if(!ME(n).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return EE(n,PE.X_OK),!0}catch{return!1}}function DE(n,e=process.env){let t=e.PATH??e.Path??"";if(t.length===0)return;let s=t.split(_E).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 d=$E(o,r+a);if(NE(d))return d}}function HE(n,e){let t=TE(n,e,{stdio:"inherit",env:process.env});t.error&&(process.stderr.write(`hydra-acp: failed to exec ${n}: ${t.error.message}
|
|
507
507
|
`),process.exit(1)),typeof t.status=="number"&&process.exit(t.status),t.signal&&process.kill(process.pid,t.signal),process.exit(1)}function Ev(n){let e=LE(n);if(e===void 0||OE(e))return!1;let t=DE(e);if(t===void 0)return!1;HE(t,BE(n))}Ep();var Ir=!1,xk=!1;function Ak(n){!n||xk||(xk=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
|
|
508
|
-
`))}async function
|
|
509
|
-
`),process.exit(2);return}let E=v??
|
|
510
|
-
`),process.exit(2);return}let
|
|
511
|
-
`);return}if(r.help===!0){$h(s[0]);return}let i=Eh(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,d=
|
|
512
|
-
`),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){Ir=!0,await Ck(r,{sessionId:m,agentId:c,name:d,model:l,target:y,dangerouslySkipPermissions:
|
|
513
|
-
`),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=
|
|
514
|
-
`),process.exit(2);return}await Yw({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:v});return}if(w==="info"){await bb(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 wb(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 Qw(s[2]);return}if(w==="remove"){await Xw(s[2]);return}if(w==="collect"){let b=
|
|
508
|
+
`))}async function V_(){let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(la(),wm));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),v=b[0],k=b.slice(1),{flags:A}=uu(w);if(Rk(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.
|
|
509
|
+
`),process.exit(2);return}let E=v??Rt(A,"agent");if(!E){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
|
|
510
|
+
`),process.exit(2);return}let _=await Tk(Tu(A),{allowPrompt:!1}),H=Rt(A,"name"),P=Rt(A,"model");Ir=!0;let $=A["dangerously-skip-permissions"]===!0;Ak($);let B={agentId:E,agentArgs:k,name:H,model:P,dangerouslySkipPermissions:$};_?.sessionId!==void 0&&(B.sessionId=_.sessionId),_?.target!==void 0&&_.fromUrl&&(B.target=_.target),await bl(B);return}Eh(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&Ev(e);let{positional:s,flags:r}=uu(e);if(Rk(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${G_()}
|
|
511
|
+
`);return}if(r.help===!0){$h(s[0]);return}let i=Eh(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,d=Rt(r,"name"),c=Rt(r,"agent"),l=Rt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Ak(u);let f=Tu(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Tk(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.
|
|
512
|
+
`),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){Ir=!0,await Ck(r,{sessionId:m,agentId:c,name:d,model:l,target:y,dangerouslySkipPermissions:u});return}Ir=!0;let w={name:d,model:l,agentId:c,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await bl(w);return}switch(a){case"acp":case"shim":{Ir=!0;let w={name:d,model:l,agentId:c,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await bl(w);return}case"cat":{let w=Eh(e),b=typeof r.prompt=="string"?r.prompt:void 0,v=w??b,k=Rt(r,"cwd"),A={prompt:v,sessionId:m,name:d,model:l,agentId:c,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=_h(r,"stream-threshold");E!==void 0&&(A.streamThreshold=E);let _=_h(r,"stream-bytes");_!==void 0&&(A.streamBufferBytes=_),c!==void 0&&await il(c),Ir=!0,await wv(A);return}case"version":{Ir=!0,await Tv({json:r.json===!0});return}case"init":await Em(r);return;case"daemon":{let w=e.indexOf("daemon"),b=e.slice(w+1),v=b[0];if(v===void 0||v==="status"){await Lw();return}if(v==="start"){await _w(r);return}if(v==="stop"){await $w();return}if(v==="restart"){await Fw();return}if(v==="log"||v==="logs"){await Ow(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${v}
|
|
513
|
+
`),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let b=Rt(r,"columns"),v;if(b!==void 0)try{v=Jw(b)}catch(k){process.stderr.write(`${k.message}
|
|
514
|
+
`),process.exit(2);return}await Yw({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:v});return}if(w==="info"){await bb(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 wb(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 Qw(s[2]);return}if(w==="remove"){await Xw(s[2]);return}if(w==="collect"){let b=Rt(r,"max-age-days"),v=Rt(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
|
|
515
515
|
`),process.exit(2);return}k.maxAgeDays=A}if(v!==void 0){let A=Number(v);if(!Number.isFinite(A)||A<=0){process.stderr.write(`--limit must be a positive number
|
|
516
|
-
`),process.exit(2);return}k.limit=A}await Zw(k);return}if(w==="export"){let b=
|
|
516
|
+
`),process.exit(2);return}k.limit=A}await Zw(k);return}if(w==="export"){let b=Rt(r,"out"),v=Rt(r,"tools");await eb(s[2],b,v);return}if(w==="transcript"){let b=Rt(r,"out"),v=r.tools===!0,k=r.thoughts===!0;await tb(s[2],b,{includeTools:v,includeThoughts:k});return}if(w==="import"){let b=Rt(r,"cwd");await nb(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(w==="share"){let b=Rt(r,"host"),v=Rt(r,"cwd");await sb(s[2],{...b!==void 0?{host:b}:{},...v!==void 0?{cwd:v}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
|
|
517
517
|
`),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),b=e.slice(w+1),v=b[0],k=b[1],A=b.slice(2);if(v===void 0||v==="list"){await Sb();return}if(v==="add"){await kb(k,A);return}if(v==="remove"){await Ib(k);return}if(v==="start"){await xb(k);return}if(v==="stop"){await Ab(k);return}if(v==="restart"){await Cb(k);return}if(v==="log"||v==="logs"){await Rb(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${v}
|
|
518
518
|
`),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),b=e.slice(w+1),v=b[0],k=b[1],A=b.slice(2);if(v===void 0||v==="list"){await Tb();return}if(v==="add"){await Eb(k,A);return}if(v==="remove"){await Pb(k);return}if(v==="start"){await Mb(k);return}if(v==="stop"){await _b(k);return}if(v==="restart"){await $b(k);return}if(v==="log"||v==="logs"){await Fb(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${v}
|
|
519
519
|
`),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await pp();return}if(w==="refresh"){await al();return}if(w==="install"){await hp(s[2]);return}if(w==="sync"){await mp(s[2]);return}if(w==="set"){await yp(s[2],s[3]);return}if(w==="pin"){await wp(s[2],s[3]);return}if(w==="add"){let b=e.indexOf(a),v=e.slice(b+1);await bp(v[1],v.slice(2));return}if(w==="remove"){await vp(s[2]);return}if(w==="uninstall"){await Sp(s[2]);return}if(w==="log"||w==="logs"){let b=e.indexOf(a),v=e.slice(b+2),{name:k,rest:A}=qc(v);await gp(k,A);return}if(w==="auth"){await sv(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
|
|
@@ -521,13 +521,13 @@ ${n}:
|
|
|
521
521
|
`),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let b=s[2];if(b===void 0||b==="set"){await rv(r);return}process.stderr.write(`Unknown auth password action: ${b}
|
|
522
522
|
`),process.exit(2);return}if(w===void 0||w==="list"){await iv();return}if(w==="revoke"){await ov(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
|
|
523
523
|
`),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await xv(s[2]);return}if(w==="get"){await Sv(s[2]);return}if(w==="set"){await kv(s[2],s[3]);return}if(w==="unset"){await Iv(s[2]);return}if(w==="path"){Av();return}process.stderr.write(`Unknown config subcommand: ${w}
|
|
524
|
-
`),process.exit(2);return}case"tui":Ir=!0,await Ck(r,{sessionId:m,agentId:c,name:d,model:l,target:y,dangerouslySkipPermissions:
|
|
525
|
-
`),$h(),process.exit(2)}}async function Ck(n,e){let t=
|
|
524
|
+
`),process.exit(2);return}case"tui":Ir=!0,await Ck(r,{sessionId:m,agentId:c,name:d,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
|
|
525
|
+
`),$h(),process.exit(2)}}async function Ck(n,e){let t=Rt(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 il(e.agentId),Oo(Lo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Ik(),kk)),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.
|
|
526
526
|
`),process.exit(2)),a.drip=!0;let d=_h(n,"drip-speed");d!==void 0&&d>0&&(a.dripSpeed=d)}await o(a)}function _h(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 Rk(n){let e=Qh(n);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
|
|
527
527
|
|
|
528
528
|
`),$h(),process.exit(2))}function Eh(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 Tk(n,e){try{return await Am(n,e)}catch(t){re({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`${t.message}
|
|
529
|
-
`),process.exit(1)}}function V_(){try{let n=z_(W_(import.meta.url));return JSON.parse(q_(K_(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Ph=["tui"],Ek=["shim","acp"],Et=["cat"],Vl=["launch"],G_=["init"],Gl=["daemon"],Y_=["version"],gt=["session","sessions"],cd=["extension","extensions"],ld=["transformer","transformers"],Vn=["agent","agents"],Q_=["registry"],ud=["config"],Mh=["auth"];function $h(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."},[Ph," hydra-acp tui [same flags] Force TUI explicitly."],[Ek," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Ek," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[Et," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[Et," Pipe-friendly headless mode. Reads stdin and sends it"],[Et," as a prompt to a fresh session, streams the agent's"],[Et," response to stdout, exits when stdin closes. A bounded"],[Et,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[Et," as one turn; a streaming input (e.g. `tail -f`) is"],[Et," chunked by the natural pauses in the writer. -p is an"],[Et," optional standing instruction prepended to every chunk;"],[Et," if stdin already contains the question, -p is not needed."],[Et," By default, agent markdown is post-processed: ANSI-styled"],[Et," on a TTY, stripped to plain text on a pipe, tables laid"],[Et," out in both modes. Tool calls / thoughts split paragraphs"],[Et," but otherwise stay hidden. --raw bypasses the renderer"],[Et," and emits chunks immediately, the way cat used to behave."],[Et," With --session, attach to an existing session instead"],[Et," of creating a new one. With --detach, the session"],[Et," survives in the daemon for slack/browser/notifier"],[Et," extensions."],[Vl," hydra-acp launch <agent> [agent-args...]"],[Vl," Shim mode, force daemon to spawn <agent>"],[Vl," from the registry. Args after <agent>"],[Vl," 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)."]]})(),[G_," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Gl," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Gl," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Gl," hydra-acp daemon stop|restart"],[Gl," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[Y_," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[gt," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[gt," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[gt," --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."],[gt," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[gt," --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."],[gt," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[gt," 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)."],[gt," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[gt," 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."],[gt," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[gt," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[gt," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[gt," 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."],[gt," hydra-acp session export <id> [--out <file>|.]"],[gt," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[gt," hydra-acp session transcript <id>|<file> [--out <file>|.] [--tools] [--thoughts]"],[gt," 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. --tools adds the tool-call list, --thoughts adds the agent's reasoning stream (both off by default)"],[gt," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[gt," 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"],[gt," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[gt," 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)."],[cd," hydra-acp extension list List configured extensions and live state"],[cd," hydra-acp extension add <name> [opts] Add an extension to config"],[cd," hydra-acp extension remove <name> Remove an extension from config"],[cd," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[cd," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[ld," hydra-acp transformer list List configured transformers and live state"],[ld," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[ld," hydra-acp transformer remove <name> Remove a transformer from config"],[ld," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[ld," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Vn," hydra-acp agent [list] List agents in the cached registry"],[Vn," hydra-acp agent refresh Force a registry re-fetch"],[Vn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Vn," 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>])."],[Vn," 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."],[Vn," 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)."],[Vn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Vn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[Q_," 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."],[Vn," 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`"],[Vn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Vn," hydra-acp agent auth <id> Run the auth flow for <id>"],[ud," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[ud," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[ud," 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."],[ud," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[ud," hydra-acp config path Print the config file path"],[Mh," hydra-acp auth password [--force] Set the daemon's master password"],[Mh," hydra-acp auth [list] List active session tokens"],[Mh," hydra-acp auth revoke <id> Revoke a session token"],[Ph," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Ph," 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(`
|
|
529
|
+
`),process.exit(1)}}function G_(){try{let n=K_(z_(import.meta.url));return JSON.parse(W_(J_(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Ph=["tui"],Ek=["shim","acp"],Et=["cat"],Vl=["launch"],Y_=["init"],Gl=["daemon"],Q_=["version"],gt=["session","sessions"],cd=["extension","extensions"],ld=["transformer","transformers"],Vn=["agent","agents"],X_=["registry"],ud=["config"],Mh=["auth"];function $h(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."},[Ph," hydra-acp tui [same flags] Force TUI explicitly."],[Ek," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Ek," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[Et," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[Et," Pipe-friendly headless mode. Reads stdin and sends it"],[Et," as a prompt to a fresh session, streams the agent's"],[Et," response to stdout, exits when stdin closes. A bounded"],[Et,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[Et," as one turn; a streaming input (e.g. `tail -f`) is"],[Et," chunked by the natural pauses in the writer. -p is an"],[Et," optional standing instruction prepended to every chunk;"],[Et," if stdin already contains the question, -p is not needed."],[Et," By default, agent markdown is post-processed: ANSI-styled"],[Et," on a TTY, stripped to plain text on a pipe, tables laid"],[Et," out in both modes. Tool calls / thoughts split paragraphs"],[Et," but otherwise stay hidden. --raw bypasses the renderer"],[Et," and emits chunks immediately, the way cat used to behave."],[Et," With --session, attach to an existing session instead"],[Et," of creating a new one. With --detach, the session"],[Et," survives in the daemon for slack/browser/notifier"],[Et," extensions."],[Vl," hydra-acp launch <agent> [agent-args...]"],[Vl," Shim mode, force daemon to spawn <agent>"],[Vl," from the registry. Args after <agent>"],[Vl," 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)."]]})(),[Y_," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Gl," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Gl," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Gl," hydra-acp daemon stop|restart"],[Gl," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[Q_," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[gt," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[gt," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[gt," --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."],[gt," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[gt," --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."],[gt," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[gt," 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)."],[gt," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[gt," 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."],[gt," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[gt," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[gt," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[gt," 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."],[gt," hydra-acp session export <id> [--out <file>|.]"],[gt," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[gt," hydra-acp session transcript <id>|<file> [--out <file>|.] [--tools] [--thoughts]"],[gt," 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. --tools adds the tool-call list, --thoughts adds the agent's reasoning stream (both off by default)"],[gt," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[gt," 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"],[gt," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[gt," 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)."],[cd," hydra-acp extension list List configured extensions and live state"],[cd," hydra-acp extension add <name> [opts] Add an extension to config"],[cd," hydra-acp extension remove <name> Remove an extension from config"],[cd," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[cd," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[ld," hydra-acp transformer list List configured transformers and live state"],[ld," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[ld," hydra-acp transformer remove <name> Remove a transformer from config"],[ld," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[ld," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Vn," hydra-acp agent [list] List agents in the cached registry"],[Vn," hydra-acp agent refresh Force a registry re-fetch"],[Vn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Vn," 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>])."],[Vn," 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."],[Vn," 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)."],[Vn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Vn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[X_," 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."],[Vn," 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`"],[Vn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Vn," hydra-acp agent auth <id> Run the auth flow for <id>"],[ud," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[ud," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[ud," 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."],[ud," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[ud," hydra-acp config path Print the config file path"],[Mh," hydra-acp auth password [--force] Set the daemon's master password"],[Mh," hydra-acp auth [list] List active session tokens"],[Mh," hydra-acp auth revoke <id> Revoke a session token"],[Ph," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Ph," 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(`
|
|
530
530
|
`)+`
|
|
531
531
|
`)}async function Pk(){if(!Ir)try{let n=await Ga();n&&process.stderr.write(`\u2728 ${Ya(n)}
|
|
532
|
-
`)}catch{}}
|
|
533
|
-
`),await Pk(),process.exit(1)});function Mk(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:Mk(e.cause)}}return String(n)}}function
|
|
532
|
+
`)}catch{}}V_().then(Pk).catch(async n=>{re({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n),cause:Mk(n.cause)});let e=Z_(n.cause),t=e?` (${e})`:"";process.stderr.write(`hydra-acp: ${n.message}${t}
|
|
533
|
+
`),await Pk(),process.exit(1)});function Mk(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:Mk(e.cause)}}return String(n)}}function Z_(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(" ")}
|